text:
package org.cyberneko.html;

import java.util.ArrayList;
import java.util.List;
import org.apache.xerces.util.XMLAttributesImpl;
import org.apache.xerces.xni.Augmentations;
import org.apache.xerces.xni.NamespaceContext;
import org.apache.xerces.xni.QName;
import org.apache.xerces.xni.XMLAttributes;
import org.apache.xerces.xni.XMLDocumentHandler;
import org.apache.xerces.xni.XMLLocator;
import org.apache.xerces.xni.XMLResourceIdentifier;
import org.apache.xerces.xni.XMLString;
import org.apache.xerces.xni.XNIException;
import org.apache.xerces.xni.parser.XMLComponentManager;
import org.apache.xerces.xni.parser.XMLConfigurationException;
import org.apache.xerces.xni.parser.XMLDocumentFilter;
import org.apache.xerces.xni.parser.XMLDocumentSource;
import org.cyberneko.html.HTMLElements.Element;
import org.cyberneko.html.filters.NamespaceBinder;
import org.cyberneko.html.xercesbridge.XercesBridge;
@SuppressWarnings("all")
/**
 * Balances tags in an HTML document. This component receives document events
 * and tries to correct many common mistakes that human (and computer) HTML
 * document authors make. This tag balancer can:
 *

 *
add missing parent elements;
 *
automatically close elements with optional end tags; and
 *
handle mis-matched inline element tags.
 *

 *

 * This component recognizes the following features:
 *

 *
http://cyberneko.org/html/features/augmentations
 *
http://cyberneko.org/html/features/report-errors
 *
http://cyberneko.org/html/features/balance-tags/document-fragment
 *
http://cyberneko.org/html/features/balance-tags/ignore-outside-content
 *

 *

 * This component recognizes the following properties:
 *

 *
http://cyberneko.org/html/properties/names/elems
 *
http://cyberneko.org/html/properties/names/attrs
 *
http://cyberneko.org/html/properties/error-reporter
 *
http://cyberneko.org/html/properties/balance-tags/current-stack
 *

 *
 * @see HTMLElements
 *
 * @author Andy Clark
 * @author Marc Guillemot
 *
 * @version $Id: HTMLTagBalancer.java,v 1.20 2005/02/14 04:06:22 andyc Exp $
 */
public class HTMLTagBalancer
    implements XMLDocumentFilter, HTMLComponent {

    //
    // Constants
    //

    // features

    /** Namespaces. */
    protected static final String NAMESPACES = "http://xml.org/sax/features/namespaces";

    /** Include infoset augmentations. */
    protected static final String AUGMENTATIONS = "http://cyberneko.org/html/features/augmentations";

    /** Report errors. */
    protected static final String REPORT_ERRORS = "http://cyberneko.org/html/features/report-errors";

    /** Document fragment balancing only (deprecated). */
    protected static final String DOCUMENT_FRAGMENT_DEPRECATED = "http://cyberneko.org/html/features/document-fragment";

    /** Document fragment balancing only. */
    protected static final String DOCUMENT_FRAGMENT = "http://cyberneko.org/html/features/balance-tags/document-fragment";

    /** Ignore outside content. */
    protected static final String IGNORE_OUTSIDE_CONTENT = "http://cyberneko.org/html/features/balance-tags/ignore-outside-content";

    /** Recognized features. */
    private static final String[] RECOGNIZED_FEATURES = {
        NAMESPACES,
        AUGMENTATIONS,
        REPORT_ERRORS,
        DOCUMENT_FRAGMENT_DEPRECATED,
        DOCUMENT_FRAGMENT,
        IGNORE_OUTSIDE_CONTENT,
    };

    /** Recognized features defaults. */
    private static final Boolean[] RECOGNIZED_FEATURES_DEFAULTS = {
        null,
        null,
        null,
        null,
        Boolean.FALSE,
        Boolean.FALSE,
    };

    // properties

    /** Modify HTML element names: { "upper", "lower", "default" }. */
    protected static final String NAMES_ELEMS = "http://cyberneko.org/html/properties/names/elems";

    /** Modify HTML attribute names: { "upper", "lower", "default" }. */
    protected static final String NAMES_ATTRS = "http://cyberneko.org/html/properties/names/attrs";

    /** Error reporter. */
    protected static final String ERROR_REPORTER = "http://cyberneko.org/html/properties/error-reporter";

    /**
     * EXPERIMENTAL: may change in next release

     * Name of the property holding the stack of elements in which context a document fragment should be parsed.
     **/
    public static final String FRAGMENT_CONTEXT_STACK = "http://cyberneko.org/html/properties/balance-tags/fragment-context-stack";

    /** Recognized properties. */
    private static final String[] RECOGNIZED_PROPERTIES = {
        NAMES_ELEMS,
        NAMES_ATTRS,
        ERROR_REPORTER,
        FRAGMENT_CONTEXT_STACK,
    };

    /** Recognized properties defaults. */
    private static final Object[] RECOGNIZED_PROPERTIES_DEFAULTS = {
        null,
        null,
        null,
        null,
    };

    // modify HTML names

    /** Don't modify HTML names. */
    protected static final short NAMES_NO_CHANGE = 0;

    /** Match HTML element names. */
    protected static final short NAMES_MATCH = 0;

    /** Uppercase HTML names. */
    protected static final short NAMES_UPPERCASE = 1;

    /** Lowercase HTML names. */
    protected static final short NAMES_LOWERCASE = 2;

    // static vars

    /** Synthesized event info item. */
    protected static final HTMLEventInfo SYNTHESIZED_ITEM =
        new HTMLEventInfo.SynthesizedItem();

    //
    // Data
    //

    // features

    /** Namespaces. */
    protected boolean fNamespaces;

    /** Include infoset augmentations. */
    protected boolean fAugmentations;

    /** Report errors. */
    protected boolean fReportErrors;

    /** Document fragment balancing only. */
    protected boolean fDocumentFragment;

    /** Ignore outside content. */
    protected boolean fIgnoreOutsideContent;

    // properties

    /** Modify HTML element names. */
    protected short fNamesElems;

    /** Modify HTML attribute names. */
    protected short fNamesAttrs;

    /** Error reporter. */
    protected HTMLErrorReporter fErrorReporter;

    // connections

    /** The document source. */
    protected XMLDocumentSource fDocumentSource;

    /** The document handler. */
    protected XMLDocumentHandler fDocumentHandler;

    // state

    /** The element stack. */
    protected final InfoStack fElementStack = new InfoStack();

    /** The inline stack. */
    protected final InfoStack fInlineStack = new InfoStack();

    /** True if seen anything. Important for xml declaration. */
    protected boolean fSeenAnything;

    /** True if root element has been seen. */
    protected boolean fSeenDoctype;

    /** True if root element has been seen. */
    protected boolean fSeenRootElement;

    /**
     * True if seen the end of the document element. In other words,
     * this variable is set to false until the end </HTML>
     * tag is seen (or synthesized). This is used to ensure that
     * extraneous events after the end of the document element do not
     * make the document stream ill-formed.
     */
    protected boolean fSeenRootElementEnd;

    /** True if seen <head< element. */
    protected boolean fSeenHeadElement;

    /** True if seen <body< element. */
    protected boolean fSeenBodyElement;

    /** True if a form is in the stack (allow to discard opening of nested forms) */
    protected boolean fOpenedForm;

    // temp vars

    /** A qualified name. */
    private final QName fQName = new QName();

    /** Empty attributes. */
    private final XMLAttributes fEmptyAttrs = new XMLAttributesImpl();

    /** Augmentations. */
    private final HTMLAugmentations fInfosetAugs = new HTMLAugmentations();

    protected HTMLTagBalancingListener tagBalancingListener;
    private LostText lostText_ = new LostText();

    private boolean forcedStartElement_ = false;
    private boolean forcedEndElement_ = false;

    /**
     * Stack of elements determining the context in which a document fragment should be parsed
     */
	private QName[] fragmentContextStack_ = null;
	private int fragmentContextStackSize_ = 0; // not 0 only when a fragment is parsed and fragmentContextStack_ is set

    private List/*ElementEntry*/ endElementsBuffer_ = new ArrayList();

    //
    // HTMLComponent methods
    //

    /** Returns the default state for a feature. */
    public Boolean getFeatureDefault(String featureId) {
        int length = RECOGNIZED_FEATURES != null ? RECOGNIZED_FEATURES.length : 0;
        for (int i = 0; i < length; i++) {
            if (RECOGNIZED_FEATURES[i].equals(featureId)) {
                return RECOGNIZED_FEATURES_DEFAULTS[i];
            }
        }
        return null;
    } // getFeatureDefault(String):Boolean

    /** Returns the default state for a property. */
    public Object getPropertyDefault(String propertyId) {
        int length = RECOGNIZED_PROPERTIES != null ? RECOGNIZED_PROPERTIES.length : 0;
        for (int i = 0; i < length; i++) {
            if (RECOGNIZED_PROPERTIES[i].equals(propertyId)) {
                return RECOGNIZED_PROPERTIES_DEFAULTS[i];
            }
        }
        return null;
    } // getPropertyDefault(String):Object

    //
    // XMLComponent methods
    //

    /** Returns recognized features. */
    public String[] getRecognizedFeatures() {
        return RECOGNIZED_FEATURES;
    } // getRecognizedFeatures():String[]

    /** Returns recognized properties. */
    public String[] getRecognizedProperties() {
        return RECOGNIZED_PROPERTIES;
    } // getRecognizedProperties():String[]

    /** Resets the component. */
    public void reset(XMLComponentManager manager)
        throws XMLConfigurationException {

        // get features
        fNamespaces = manager.getFeature(NAMESPACES);
        fAugmentations = manager.getFeature(AUGMENTATIONS);
        fReportErrors = manager.getFeature(REPORT_ERRORS);
        fDocumentFragment = manager.getFeature(DOCUMENT_FRAGMENT) ||
                            manager.getFeature(DOCUMENT_FRAGMENT_DEPRECATED);
        fIgnoreOutsideContent = manager.getFeature(IGNORE_OUTSIDE_CONTENT);

        // get properties
        fNamesElems = getNamesValue(String.valueOf(manager.getProperty(NAMES_ELEMS)));
        fNamesAttrs = getNamesValue(String.valueOf(manager.getProperty(NAMES_ATTRS)));
        fErrorReporter = (HTMLErrorReporter)manager.getProperty(ERROR_REPORTER);

        fragmentContextStack_ = (QName[]) manager.getProperty(FRAGMENT_CONTEXT_STACK);

    } // reset(XMLComponentManager)

    /** Sets a feature. */
    public void setFeature(String featureId, boolean state)
        throws XMLConfigurationException {

        if (featureId.equals(AUGMENTATIONS)) {
            fAugmentations = state;
            return;
        }
        if (featureId.equals(REPORT_ERRORS)) {
            fReportErrors = state;
            return;
        }
        if (featureId.equals(IGNORE_OUTSIDE_CONTENT)) {
            fIgnoreOutsideContent = state;
            return;
        }

    } // setFeature(String,boolean)

    /** Sets a property. */
    public void setProperty(String propertyId, Object value)
        throws XMLConfigurationException {

        if (propertyId.equals(NAMES_ELEMS)) {
            fNamesElems = getNamesValue(String.valueOf(value));
            return;
        }

        if (propertyId.equals(NAMES_ATTRS)) {
            fNamesAttrs = getNamesValue(String.valueOf(value));
            return;
        }

    } // setProperty(String,Object)

    //
    // XMLDocumentSource methods
    //

    /** Sets the document handler. */
    public void setDocumentHandler(XMLDocumentHandler handler) {
        fDocumentHandler = handler;
    } // setDocumentHandler(XMLDocumentHandler)

    // @since Xerces 2.1.0

    /** Returns the document handler. */
    public XMLDocumentHandler getDocumentHandler() {
        return fDocumentHandler;
    } // getDocumentHandler():XMLDocumentHandler

    //
    // XMLDocumentHandler methods
    //

    // since Xerces-J 2.2.0

    /** Start document. */
    public void startDocument(XMLLocator locator, String encoding,
                              NamespaceContext nscontext, Augmentations augs)
        throws XNIException {

        // reset state
        fElementStack.top = 0;
        if (fragmentContextStack_ != null) {
        	fragmentContextStackSize_ = fragmentContextStack_.length;
        	for (int i=0; i<fragmentContextStack_.length; ++i) {
        		final QName name = fragmentContextStack_[i];
            	final Element elt = HTMLElements.getElement(name.localpart);
            	fElementStack.push(new Info(elt, name));
        	}

        }
        else {
        	fragmentContextStackSize_ = 0;
        }
        fSeenAnything = false;
        fSeenDoctype = false;
        fSeenRootElement = false;
        fSeenRootElementEnd = false;
        fSeenHeadElement = false;
        fSeenBodyElement = false;

        // pass on event
        if (fDocumentHandler != null) {
        	XercesBridge.getInstance().XMLDocumentHandler_startDocument(fDocumentHandler, locator, encoding, nscontext, augs);
        }

    } // startDocument(XMLLocator,String,Augmentations)

    // old methods

    /** XML declaration. */
    public void xmlDecl(String version, String encoding, String standalone,
                        Augmentations augs) throws XNIException {
        if (!fSeenAnything && fDocumentHandler != null) {
            fDocumentHandler.xmlDecl(version, encoding, standalone, augs);
        }
    } // xmlDecl(String,String,String,Augmentations)

    /** Doctype declaration. */
    public void doctypeDecl(String rootElementName, String publicId, String systemId,
                            Augmentations augs) throws XNIException {
        fSeenAnything = true;
        if (fReportErrors) {
            if (fSeenRootElement) {
                fErrorReporter.reportError("HTML2010", null);
            }
            else if (fSeenDoctype) {
                fErrorReporter.reportError("HTML2011", null);
            }
        }
        if (!fSeenRootElement && !fSeenDoctype) {
            fSeenDoctype = true;
            if (fDocumentHandler != null) {
                fDocumentHandler.doctypeDecl(rootElementName, publicId, systemId, augs);
            }
        }
    } // doctypeDecl(String,String,String,Augmentations)

    /** End document. */
    public void endDocument(Augmentations augs) throws XNIException {

    	//  and  have been buffered to consider outside content
    	fIgnoreOutsideContent = true; // endElement should not ignore the elements passed from buffer
    	consumeBufferedEndElements();

        // handle empty document
        if (!fSeenRootElement && !fDocumentFragment) {
            if (fReportErrors) {
                fErrorReporter.reportError("HTML2000", null);
            }
            if (fDocumentHandler != null) {
            	fSeenRootElementEnd = false;
                forceStartBody(); // will force  and
                final String body = modifyName("body", fNamesElems);
                fQName.setValues(null, body, body, null);
                callEndElement(fQName, synthesizedAugs());

                final String ename = modifyName("html", fNamesElems);
                fQName.setValues(null, ename, ename, null);
                callEndElement(fQName, synthesizedAugs());
            }
        }

        // pop all remaining elements
        else {
            int length = fElementStack.top - fragmentContextStackSize_;
            for (int i = 0; i < length; i++) {
                Info info = fElementStack.pop();
                if (fReportErrors) {
                    String ename = info.qname.rawname;
                    fErrorReporter.reportWarning("HTML2001", new Object[]{ename});
                }
                if (fDocumentHandler != null) {
                    callEndElement(info.qname, synthesizedAugs());
                }
            }
        }

        // call handler
        if (fDocumentHandler != null) {
            fDocumentHandler.endDocument(augs);
        }

    } // endDocument(Augmentations)

    /**
     * Consume elements that have been buffered, like  that are first consumed
     * at the end of document
     */
	private void consumeBufferedEndElements() {
		final List toConsume = new ArrayList(endElementsBuffer_);
		endElementsBuffer_.clear();
		for (int i=0; i<toConsume.size(); ++i) {
    		final ElementEntry entry = (ElementEntry) toConsume.get(i);
    		forcedEndElement_ = true;
        	endElement(entry.name_, entry.augs_);
    	}
		endElementsBuffer_.clear();
	}

    /** Comment. */
    public void comment(XMLString text, Augmentations augs) throws XNIException {
        fSeenAnything = true;
        consumeEarlyTextIfNeeded();
        if (fDocumentHandler != null) {
            fDocumentHandler.comment(text, augs);
        }
    } // comment(XMLString,Augmentations)

	private void consumeEarlyTextIfNeeded() {
		if (!lostText_.isEmpty()) {
        	if (!fSeenBodyElement) {
        		forceStartBody();
        	}
            lostText_.refeed(this);
        }
	}

    /** Processing instruction. */
    public void processingInstruction(String target, XMLString data,
                                      Augmentations augs) throws XNIException {
        fSeenAnything = true;
        consumeEarlyTextIfNeeded();
        if (fDocumentHandler != null) {
            fDocumentHandler.processingInstruction(target, data, augs);
        }
    } // processingInstruction(String,XMLString,Augmentations)

    /** Start element. */
    public void startElement(final QName elem, XMLAttributes attrs, final Augmentations augs)
        throws XNIException {
        fSeenAnything = true;

        final boolean isForcedCreation = forcedStartElement_;
        forcedStartElement_ = false;

        // check for end of document
        if (fSeenRootElementEnd) {
        	notifyDiscardedStartElement(elem, attrs, augs);
            return;
        }

        // get element information
        final HTMLElements.Element element = getElement(elem);
        final short elementCode = element.code;

        // the creation of some elements like TABLE or SELECT can't be forced. Any others?
        if (isForcedCreation && (elementCode == HTMLElements.TABLE || elementCode == HTMLElements.SELECT)) {
        	return; // don't accept creation
        }

        // ignore multiple html, head, body elements
		if (fSeenRootElement && elementCode == HTMLElements.HTML) {
        	notifyDiscardedStartElement(elem, attrs, augs);
            return;
        }
        if (elementCode == HTMLElements.HEAD) {
            if (fSeenHeadElement) {
            	notifyDiscardedStartElement(elem, attrs, augs);
                return;
            }
            fSeenHeadElement = true;
        }
        else if (elementCode == HTMLElements.FRAMESET) {
        	consumeBufferedEndElements(); //  (if any) has been buffered
        }
        else if (elementCode == HTMLElements.BODY) {
    		// create  if none was present
    		if (!fSeenHeadElement) {
    			final QName head = createQName("head");
    			forceStartElement(head, null, synthesizedAugs());
    			endElement(head, synthesizedAugs());
    		}
        	consumeBufferedEndElements(); //  (if any) has been buffered

            if (fSeenBodyElement) {
            	notifyDiscardedStartElement(elem, attrs, augs);
                return;
            }
            fSeenBodyElement = true;
        }
        else if (elementCode == HTMLElements.FORM) {
        	if (fOpenedForm) {
            	notifyDiscardedStartElement(elem, attrs, augs);
        		return;
        	}
        	fOpenedForm = true;
        }
        else if (elementCode == HTMLElements.UNKNOWN) {
        	consumeBufferedEndElements();
        }

        // check proper parent
        if (element.parent != null) {
        	if (!fSeenRootElement && !fDocumentFragment) {
                String pname = element.parent[0].name;
                pname = modifyName(pname, fNamesElems);
                if (fReportErrors) {
                    String ename = elem.rawname;
                    fErrorReporter.reportWarning("HTML2002", new Object[]{ename,pname});
                }
                final QName qname = new QName(null, pname, pname, null);
                final boolean parentCreated = forceStartElement(qname, null, synthesizedAugs());
                if (!parentCreated) {
                	if (!isForcedCreation) {
                		notifyDiscardedStartElement(elem, attrs, augs);
                	}
            		return;
                }
            }
        	else {
                HTMLElements.Element preferedParent = element.parent[0];
                if (preferedParent.code != HTMLElements.HEAD || (!fSeenBodyElement && !fDocumentFragment)) {
                    int depth = getParentDepth(element.parent, element.bounds);
                    if (depth == -1) { // no parent found
                        final String pname = modifyName(preferedParent.name, fNamesElems);
                        final QName qname = new QName(null, pname, pname, null);
                        if (fReportErrors) {
                            String ename = elem.rawname;
                            fErrorReporter.reportWarning("HTML2004", new Object[]{ename,pname});
                        }
                        final boolean parentCreated = forceStartElement(qname, null, synthesizedAugs());
                        if (!parentCreated) {
                        	if (!isForcedCreation) {
                        		notifyDiscardedStartElement(elem, attrs, augs);
                        	}
                    		return;
                        }
                    }
                }
            }
        }

        // if block element, save immediate parent inline elements
        int depth = 0;
        if (element.flags == 0) {
            int length = fElementStack.top;
            fInlineStack.top = 0;
            for (int i = length - 1; i >= 0; i--) {
                Info info = fElementStack.data[i];
                if (!info.element.isInline()) {
                    break;
                }
                fInlineStack.push(info);
                endElement(info.qname, synthesizedAugs());
            }
            depth = fInlineStack.top;
        }

        // close previous elements
        // all elements close a


text:
<!doctype html>

    <meta charset="utf-8">
    <meta name="description" content="Welcome to my page/cv - take a look at my profile. I hope it's interesting for you.">
    <meta name="keywords" content="React,EcmaScript2016,JavaScript,Docker,SASS,OpenSource">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
    <link href="https://fonts.googleapis.com/css?family=Roboto:300,400" rel="stylesheet">
    <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">

    <title>Hello World, I am Piotr Wojtkowiak</title>

redpajama_set_name: RedPajamaGithub


text:
<?php
/*
 * Autor       : Juan Carlos Ludeña Montesinos
 * Año         : Abril 2016
 * Descripción :
 *
 */

namespace Cms\Model\Service;

class ContenidoService
{
    protected $_repository = null;
    protected $_sl         = null;

    const TIPO_PAGINA         = 1;
    const TIPO_SECCION        = 2;
    const TIPO_NAME_PAGINA  = 'página';
    const TIPO_NAME_SECCION = 'sección';

    const SECCION_INICIO_REGISTRO = 'INICIO_REGISTRO';
    const SECCION_INICIO_LOGIN = 'INICIO_LOGIN';
    const SECCION_BENEFICIOS = 'BENEFICIOS';
    const SECCION_TERMINOS_CONDICIONES = 'TERMINOS_CONDICIONES';
    const SECCION_POLITICAS_PRIVACIDAD = 'POLITICAS_PRIVACIDAD';

    public function __construct($repository, $serviceLocator)
    {
        $this->_repository = $repository;
        $this->_sl         = $serviceLocator;
    }

    public function getContenido($codigo)
    {
        $criteria = array('where' => array('codigo' => $codigo));
        $row = $this->_repository->findOne($criteria);
        if (isset($row['contenido'])) {
            return $row['contenido'];
        }
        return null;
    }

    public function getRepository()
    {
        return $this->_repository;
    }

    public function getTipos()
    {
        return array(
            self::TIPO_PAGINA  => 'Página',
            self::TIPO_SECCION => 'Sección',
        );
    }

    public static function getNameTipo($tipoPagina)
    {
        $result = self::TIPO_NAME_SECCION;

        if (!empty($tipoPagina) && self::TIPO_PAGINA == $tipoPagina) {
            return self::TIPO_NAME_PAGINA;
        }

        return $result;
    }

    public static function getAllTipos()
    {
        return array(
            'tipoPagina'        => self::TIPO_PAGINA,
            'tipoSeccion'       => self::TIPO_SECCION,
            'nombreTipoPagina'  => ucfirst(self::TIPO_NAME_PAGINA),
            'nombreTipoSeccion' => ucfirst(self::TIPO_NAME_SECCION),
        );
    }

    /**
     * Retorna un array que se utilizar en la busqueda
     * @return array
     * @author Diómedes Pablo A. <diomedex10@gmail.com>
     */
    public function getFiltrosBuscar()
    {
        return array(
            'codigo'    => 'Código',
            'titulo'    => 'Título',
        );
    }
}


text:
#ifndef GRPCPP_IMPL_CODEGEN_CLIENT_CALLBACK_H
#define GRPCPP_IMPL_CODEGEN_CLIENT_CALLBACK_H

#include <functional>

#include <grpcpp/impl/codegen/call.h>
#include <grpcpp/impl/codegen/call_op_set.h>
#include <grpcpp/impl/codegen/callback_common.h>
#include <grpcpp/impl/codegen/channel_interface.h>
#include <grpcpp/impl/codegen/config.h>
#include <grpcpp/impl/codegen/core_codegen_interface.h>
#include <grpcpp/impl/codegen/status.h>

namespace grpc_impl {
class Channel;
}

namespace grpc {

class ClientContext;

namespace internal {
class RpcMethod;

/// Perform a callback-based unary call
/// TODO(vjpai): Combine as much as possible with the blocking unary call code
template <class InputMessage, class OutputMessage>
void CallbackUnaryCall(ChannelInterface* channel, const RpcMethod& method,
                       ClientContext* context, const InputMessage* request,
                       OutputMessage* result,
                       std::function<void(Status)> on_completion) {
  CallbackUnaryCallImpl<InputMessage, OutputMessage> x(
      channel, method, context, request, result, on_completion);
}

template <class InputMessage, class OutputMessage>
class CallbackUnaryCallImpl {
 public:
  CallbackUnaryCallImpl(ChannelInterface* channel, const RpcMethod& method,
                        ClientContext* context, const InputMessage* request,
                        OutputMessage* result,
                        std::function<void(Status)> on_completion) {
    CompletionQueue* cq = channel->CallbackCQ();
    GPR_CODEGEN_ASSERT(cq != nullptr);
    Call call(channel->CreateCall(method, context, cq));

    using FullCallOpSet =
        CallOpSet<CallOpSendInitialMetadata, CallOpSendMessage,
                  CallOpRecvInitialMetadata, CallOpRecvMessage<OutputMessage>,
                  CallOpClientSendClose, CallOpClientRecvStatus>;

    auto* ops = new (g_core_codegen_interface->grpc_call_arena_alloc(
        call.call(), sizeof(FullCallOpSet))) FullCallOpSet;

    auto* tag = new (g_core_codegen_interface->grpc_call_arena_alloc(
        call.call(), sizeof(CallbackWithStatusTag)))
        CallbackWithStatusTag(call.call(), on_completion, ops);

    // TODO(vjpai): Unify code with sync API as much as possible
    Status s = ops->SendMessagePtr(request);
    if (!s.ok()) {
      tag->force_run(s);
      return;
    }
    ops->SendInitialMetadata(&context->send_initial_metadata_,
                             context->initial_metadata_flags());
    ops->RecvInitialMetadata(context);
    ops->RecvMessage(result);
    ops->AllowNoMessage();
    ops->ClientSendClose();
    ops->ClientRecvStatus(context, tag->status_ptr());
    ops->set_core_cq_tag(tag);
    call.PerformOps(ops);
  }
};
}  // namespace internal

namespace experimental {

// Forward declarations
template <class Request, class Response>
class ClientBidiReactor;
template <class Response>
class ClientReadReactor;
template <class Request>
class ClientWriteReactor;
class ClientUnaryReactor;

// NOTE: The streaming objects are not actually implemented in the public API.
//       These interfaces are provided for mocking only. Typical applications
//       will interact exclusively with the reactors that they define.
template <class Request, class Response>
class ClientCallbackReaderWriter {
 public:
  virtual ~ClientCallbackReaderWriter() {}
  virtual void StartCall() = 0;
  virtual void Write(const Request* req, WriteOptions options) = 0;
  virtual void WritesDone() = 0;
  virtual void Read(Response* resp) = 0;
  virtual void AddHold(int holds) = 0;
  virtual void RemoveHold() = 0;

 protected:
  void BindReactor(ClientBidiReactor<Request, Response>* reactor) {
    reactor->BindStream(this);
  }
};

template <class Response>
class ClientCallbackReader {
 public:
  virtual ~ClientCallbackReader() {}
  virtual void StartCall() = 0;
  virtual void Read(Response* resp) = 0;
  virtual void AddHold(int holds) = 0;
  virtual void RemoveHold() = 0;

 protected:
  void BindReactor(ClientReadReactor<Response>* reactor) {
    reactor->BindReader(this);
  }
};

template <class Request>
class ClientCallbackWriter {
 public:
  virtual ~ClientCallbackWriter() {}
  virtual void StartCall() = 0;
  void Write(const Request* req) { Write(req, WriteOptions()); }
  virtual void Write(const Request* req, WriteOptions options) = 0;
  void WriteLast(const Request* req, WriteOptions options) {
    Write(req, options.set_last_message());
  }
  virtual void WritesDone() = 0;

  virtual void AddHold(int holds) = 0;
  virtual void RemoveHold() = 0;

 protected:
  void BindReactor(ClientWriteReactor<Request>* reactor) {
    reactor->BindWriter(this);
  }
};

class ClientCallbackUnary {
 public:
  virtual ~ClientCallbackUnary() {}
  virtual void StartCall() = 0;

 protected:
  void BindReactor(ClientUnaryReactor* reactor);
};

// The following classes are the reactor interfaces that are to be implemented
// by the user. They are passed in to the library as an argument to a call on a
// stub (either a codegen-ed call or a generic call). The streaming RPC is
// activated by calling StartCall, possibly after initiating StartRead,
// StartWrite, or AddHold operations on the streaming object. Note that none of
// the classes are pure; all reactions have a default empty reaction so that the
// user class only needs to override those classes that it cares about.
// The reactor must be passed to the stub invocation before any of the below
// operations can be called.

/// \a ClientBidiReactor is the interface for a bidirectional streaming RPC.
template <class Request, class Response>
class ClientBidiReactor {
 public:
  virtual ~ClientBidiReactor() {}

  /// Activate the RPC and initiate any reads or writes that have been Start'ed
  /// before this call. All streaming RPCs issued by the client MUST have
  /// StartCall invoked on them (even if they are canceled) as this call is the
  /// activation of their lifecycle.
  void StartCall() { stream_->StartCall(); }

  /// Initiate a read operation (or post it for later initiation if StartCall
  /// has not yet been invoked).
  ///
  /// \param[out] resp Where to eventually store the read message. Valid when
  ///                  the library calls OnReadDone
  void StartRead(Response* resp) { stream_->Read(resp); }

  /// Initiate a write operation (or post it for later initiation if StartCall
  /// has not yet been invoked).
  ///
  /// \param[in] req The message to be written. The library takes temporary
  ///                ownership until OnWriteDone, at which point the application
  ///                regains ownership of msg.
  void StartWrite(const Request* req) { StartWrite(req, WriteOptions()); }

  /// Initiate/post a write operation with specified options.
  ///
  /// \param[in] req The message to be written. The library takes temporary
  ///                ownership until OnWriteDone, at which point the application
  ///                regains ownership of msg.
  /// \param[in] options The WriteOptions to use for writing this message
  void StartWrite(const Request* req, WriteOptions options) {
    stream_->Write(req, std::move(options));
  }

  /// Initiate/post a write operation with specified options and an indication
  /// that this is the last write (like StartWrite and StartWritesDone, merged).
  /// Note that calling this means that no more calls to StartWrite,
  /// StartWriteLast, or StartWritesDone are allowed.
  ///
  /// \param[in] req The message to be written. The library takes temporary
  ///                ownership until OnWriteDone, at which point the application
  ///                regains ownership of msg.
  /// \param[in] options The WriteOptions to use for writing this message
  void StartWriteLast(const Request* req, WriteOptions options) {
    StartWrite(req, std::move(options.set_last_message()));
  }

  /// Indicate that the RPC will have no more write operations. This can only be
  /// issued once for a given RPC. This is not required or allowed if
  /// StartWriteLast is used since that already has the same implication.
  /// Note that calling this means that no more calls to StartWrite,
  /// StartWriteLast, or StartWritesDone are allowed.
  void StartWritesDone() { stream_->WritesDone(); }

  /// Holds are needed if (and only if) this stream has operations that take
  /// place on it after StartCall but from outside one of the reactions
  /// (OnReadDone, etc). This is _not_ a common use of the streaming API.
  ///
  /// Holds must be added before calling StartCall. If a stream still has a hold
  /// in place, its resources will not be destroyed even if the status has
  /// already come in from the wire and there are currently no active callbacks
  /// outstanding. Similarly, the stream will not call OnDone if there are still
  /// holds on it.
  ///
  /// For example, if a StartRead or StartWrite operation is going to be
  /// initiated from elsewhere in the application, the application should call
  /// AddHold or AddMultipleHolds before StartCall.  If there is going to be,
  /// for example, a read-flow and a write-flow taking place outside the
  /// reactions, then call AddMultipleHolds(2) before StartCall. When the
  /// application knows that it won't issue any more read operations (such as
  /// when a read comes back as not ok), it should issue a RemoveHold(). It
  /// should also call RemoveHold() again after it does StartWriteLast or
  /// StartWritesDone that indicates that there will be no more write ops.
  /// The number of RemoveHold calls must match the total number of AddHold
  /// calls plus the number of holds added by AddMultipleHolds.
  void AddHold() { AddMultipleHolds(1); }
  void AddMultipleHolds(int holds) { stream_->AddHold(holds); }
  void RemoveHold() { stream_->RemoveHold(); }

  /// Notifies the application that all operations associated with this RPC
  /// have completed and provides the RPC status outcome.
  ///
  /// \param[in] s The status outcome of this RPC
  virtual void OnDone(const Status& s) {}

  /// Notifies the application that a read of initial metadata from the
  /// server is done. If the application chooses not to implement this method,
  /// it can assume that the initial metadata has been read before the first
  /// call of OnReadDone or OnDone.
  ///
  /// \param[in] ok Was the initial metadata read successfully? If false, no
  ///               further read-side operation will succeed.
  virtual void OnReadInitialMetadataDone(bool ok) {}

  /// Notifies the application that a StartRead operation completed.
  ///
  /// \param[in] ok Was it successful? If false, no further read-side operation
  ///               will succeed.
  virtual void OnReadDone(bool ok) {}

  /// Notifies the application that a StartWrite operation completed.
  ///
  /// \param[in] ok Was it successful? If false, no further write-side operation
  ///               will succeed.
  virtual void OnWriteDone(bool ok) {}

  /// Notifies the application that a StartWritesDone operation completed. Note
  /// that this is only used on explicit StartWritesDone operations and not for
  /// those that are implicitly invoked as part of a StartWriteLast.
  ///
  /// \param[in] ok Was it successful? If false, the application will later see
  ///               the failure reflected as a bad status in OnDone.
  virtual void OnWritesDoneDone(bool ok) {}

 private:
  friend class ClientCallbackReaderWriter<Request, Response>;
  void BindStream(ClientCallbackReaderWriter<Request, Response>* stream) {
    stream_ = stream;
  }
  ClientCallbackReaderWriter<Request, Response>* stream_;
};

/// \a ClientReadReactor is the interface for a server-streaming RPC.
/// All public methods behave as in ClientBidiReactor.
template <class Response>
class ClientReadReactor {
 public:
  virtual ~ClientReadReactor() {}

  void StartCall() { reader_->StartCall(); }
  void StartRead(Response* resp) { reader_->Read(resp); }

  void AddHold() { AddMultipleHolds(1); }
  void AddMultipleHolds(int holds) { reader_->AddHold(holds); }
  void RemoveHold() { reader_->RemoveHold(); }

  virtual void OnDone(const Status& s) {}
  virtual void OnReadInitialMetadataDone(bool ok) {}
  virtual void OnReadDone(bool ok) {}

 private:
  friend class ClientCallbackReader<Response>;
  void BindReader(ClientCallbackReader<Response>* reader) { reader_ = reader; }
  ClientCallbackReader<Response>* reader_;
};

/// \a ClientWriteReactor is the interface for a client-streaming RPC.
/// All public methods behave as in ClientBidiReactor.
template <class Request>
class ClientWriteReactor {
 public:
  virtual ~ClientWriteReactor() {}

  void StartCall() { writer_->StartCall(); }
  void StartWrite(const Request* req) { StartWrite(req, WriteOptions()); }
  void StartWrite(const Request* req, WriteOptions options) {
    writer_->Write(req, std::move(options));
  }
  void StartWriteLast(const Request* req, WriteOptions options) {
    StartWrite(req, std::move(options.set_last_message()));
  }
  void StartWritesDone() { writer_->WritesDone(); }

  void AddHold() { AddMultipleHolds(1); }
  void AddMultipleHolds(int holds) { writer_->AddHold(holds); }
  void RemoveHold() { writer_->RemoveHold(); }

  virtual void OnDone(const Status& s) {}
  virtual void OnReadInitialMetadataDone(bool ok) {}
  virtual void OnWriteDone(bool ok) {}
  virtual void OnWritesDoneDone(bool ok) {}

 private:
  friend class ClientCallbackWriter<Request>;
  void BindWriter(ClientCallbackWriter<Request>* writer) { writer_ = writer; }
  ClientCallbackWriter<Request>* writer_;
};

/// \a ClientUnaryReactor is a reactor-style interface for a unary RPC.
/// This is _not_ a common way of invoking a unary RPC. In practice, this
/// option should be used only if the unary RPC wants to receive initial
/// metadata without waiting for the response to complete. Most deployments of
/// RPC systems do not use this option, but it is needed for generality.
/// All public methods behave as in ClientBidiReactor.
/// StartCall is included for consistency with the other reactor flavors: even
/// though there are no StartRead or StartWrite operations to queue before the
/// call (that is part of the unary call itself) and there is no reactor object
/// being created as a result of this call, we keep a consistent 2-phase
/// initiation API among all the reactor flavors.
class ClientUnaryReactor {
 public:
  virtual ~ClientUnaryReactor() {}

  void StartCall() { call_->StartCall(); }
  virtual void OnDone(const Status& s) {}
  virtual void OnReadInitialMetadataDone(bool ok) {}

 private:
  friend class ClientCallbackUnary;
  void BindCall(ClientCallbackUnary* call) { call_ = call; }
  ClientCallbackUnary* call_;
};

// Define function out-of-line from class to avoid forward declaration issue
inline void ClientCallbackUnary::BindReactor(ClientUnaryReactor* reactor) {
  reactor->BindCall(this);
}

}  // namespace experimental

namespace internal {

// Forward declare factory classes for friendship
template <class Request, class Response>
class ClientCallbackReaderWriterFactory;
template <class Response>
class ClientCallbackReaderFactory;
template <class Request>
class ClientCallbackWriterFactory;

template <class Request, class Response>
class ClientCallbackReaderWriterImpl
    : public ::grpc::experimental::ClientCallbackReaderWriter<Request,
                                                              Response> {
 public:
  // always allocated against a call arena, no memory free required
  static void operator delete(void* ptr, std::size_t size) {
    assert(size == sizeof(ClientCallbackReaderWriterImpl));
  }

  // This operator should never be called as the memory should be freed as part
  // of the arena destruction. It only exists to provide a matching operator
  // delete to the operator new so that some compilers will not complain (see
  // https://github.com/grpc/grpc/issues/11301) Note at the time of adding this
  // there are no tests catching the compiler warning.
  static void operator delete(void*, void*) { assert(0); }

  void MaybeFinish() {
    if (--callbacks_outstanding_ == 0) {
      Status s = std::move(finish_status_);
      auto* reactor = reactor_;
      auto* call = call_.call();
      this->~ClientCallbackReaderWriterImpl();
      g_core_codegen_interface->grpc_call_unref(call);
      reactor->OnDone(s);
    }
  }

  void StartCall() override {
    // This call initiates two batches, plus any backlog, each with a callback
    // 1. Send initial metadata (unless corked) + recv initial metadata
    // 2. Any read backlog
    // 3. Any write backlog
    // 4. Recv trailing metadata, on_completion callback
    started_ = true;

    start_tag_.Set(call_.call(),
                   [this](bool ok) {
                     reactor_->OnReadInitialMetadataDone(ok);
                     MaybeFinish();
                   },
                   &start_ops_);
    if (!start_corked_) {
      start_ops_.SendInitialMetadata(&context_->send_initial_metadata_,
                                     context_->initial_metadata_flags());
    }
    start_ops_.RecvInitialMetadata(context_);
    start_ops_.set_core_cq_tag(&start_tag_);
    call_.PerformOps(&start_ops_);

    // Also set up the read and write tags so that they don't have to be set up
    // each time
    write_tag_.Set(call_.call(),
                   [this](bool ok) {
                     reactor_->OnWriteDone(ok);
                     MaybeFinish();
                   },
                   &write_ops_);
    write_ops_.set_core_cq_tag(&write_tag_);

    read_tag_.Set(call_.call(),
                  [this](bool ok) {
                    reactor_->OnReadDone(ok);
                    MaybeFinish();
                  },
                  &read_ops_);
    read_ops_.set_core_cq_tag(&read_tag_);
    if (read_ops_at_start_) {
      call_.PerformOps(&read_ops_);
    }

    if (write_ops_at_start_) {
      call_.PerformOps(&write_ops_);
    }

    if (writes_done_ops_at_start_) {
      call_.PerformOps(&writes_done_ops_);
    }

    finish_tag_.Set(call_.call(), [this](bool ok) { MaybeFinish(); },
                    &finish_ops_);
    finish_ops_.ClientRecvStatus(context_, &finish_status_);
    finish_ops_.set_core_cq_tag(&finish_tag_);
    call_.PerformOps(&finish_ops_);
  }

  void Read(Response* msg) override {
    read_ops_.RecvMessage(msg);
    callbacks_outstanding_++;
    if (started_) {
      call_.PerformOps(&read_ops_);
    } else {
      read_ops_at_start_ = true;
    }
  }

  void Write(const Request* msg, WriteOptions options) override {
    if (start_corked_) {
      write_ops_.SendInitialMetadata(&context_->send_initial_metadata_,
                                     context_->initial_metadata_flags());
      start_corked_ = false;
    }

    if (options.is_last_message()) {
      options.set_buffer_hint();
      write_ops_.ClientSendClose();
    }
    // TODO(vjpai): don't assert
    GPR_CODEGEN_ASSERT(write_ops_.SendMessagePtr(msg, options).ok());
    callbacks_outstanding_++;
    if (started_) {
      call_.PerformOps(&write_ops_);
    } else {
      write_ops_at_start_ = true;
    }
  }
  void WritesDone() override {
    if (start_corked_) {
      writes_done_ops_.SendInitialMetadata(&context_->send_initial_metadata_,
                                           context_->initial_metadata_flags());
      start_corked_ = false;
    }
    writes_done_ops_.ClientSendClose();
    writes_done_tag_.Set(call_.call(),
                         [this](bool ok) {
                           reactor_->OnWritesDoneDone(ok);
                           MaybeFinish();
                         },
                         &writes_done_ops_);
    writes_done_ops_.set_core_cq_tag(&writes_done_tag_);
    callbacks_outstanding_++;
    if (started_) {
      call_.PerformOps(&writes_done_ops_);
    } else {
      writes_done_ops_at_start_ = true;
    }
  }

  virtual void AddHold(int holds) override { callbacks_outstanding_ += holds; }
  virtual void RemoveHold() override { MaybeFinish(); }

 private:
  friend class ClientCallbackReaderWriterFactory<Request, Response>;

  ClientCallbackReaderWriterImpl(
      Call call, ClientContext* context,
      ::grpc::experimental::ClientBidiReactor<Request, Response>* reactor)
      : context_(context),
        call_(call),
        reactor_(reactor),
        start_corked_(context_->initial_metadata_corked_) {
    this->BindReactor(reactor);
  }

  ClientContext* const context_;
  Call call_;
  ::grpc::experimental::ClientBidiReactor<Request, Response>* const reactor_;

  CallOpSet<CallOpSendInitialMetadata, CallOpRecvInitialMetadata> start_ops_;
  CallbackWithSuccessTag start_tag_;
  bool start_corked_;

  CallOpSet<CallOpClientRecvStatus> finish_ops_;
  CallbackWithSuccessTag finish_tag_;
  Status finish_status_;

  CallOpSet<CallOpSendInitialMetadata, CallOpSendMessage, CallOpClientSendClose>
      write_ops_;
  CallbackWithSuccessTag write_tag_;
  bool write_ops_at_start_{false};

  CallOpSet<CallOpSendInitialMetadata, CallOpClientSendClose> writes_done_ops_;
  CallbackWithSuccessTag writes_done_tag_;
  bool writes_done_ops_at_start_{false};

  CallOpSet<CallOpRecvMessage<Response>> read_ops_;
  CallbackWithSuccessTag read_tag_;
  bool read_ops_at_start_{false};

  // Minimum of 2 callbacks to pre-register for start and finish
  std::atomic_int callbacks_outstanding_{2};
  bool started_{false};
};

template <class Request, class Response>
class ClientCallbackReaderWriterFactory {
 public:
  static void Create(
      ChannelInterface* channel, const ::grpc::internal::RpcMethod& method,
      ClientContext* context,
      ::grpc::experimental::ClientBidiReactor<Request, Response>* reactor) {
    Call call = channel->CreateCall(method, context, channel->CallbackCQ());

    g_core_codegen_interface->grpc_call_ref(call.call());
    new (g_core_codegen_interface->grpc_call_arena_alloc(
        call.call(), sizeof(ClientCallbackReaderWriterImpl<Request, Response>)))
        ClientCallbackReaderWriterImpl<Request, Response>(call, context,
                                                          reactor);
  }
};

template <class Response>
class ClientCallbackReaderImpl
    : public ::grpc::experimental::ClientCallbackReader<Response> {
 public:
  // always allocated against a call arena, no memory free required
  static void operator delete(void* ptr, std::size_t size) {
    assert(size == sizeof(ClientCallbackReaderImpl));
  }

  // This operator should never be called as the memory should be freed as part
  // of the arena destruction. It only exists to provide a matching operator
  // delete to the operator new so that some compilers will not complain (see
  // https://github.com/grpc/grpc/issues/11301) Note at the time of adding this
  // there are no tests catching the compiler warning.
  static void operator delete(void*, void*) { assert(0); }

  void MaybeFinish() {
    if (--callbacks_outstanding_ == 0) {
      Status s = std::move(finish_status_);
      auto* reactor = reactor_;
      auto* call = call_.call();
      this->~ClientCallbackReaderImpl();
      g_core_codegen_interface->grpc_call_unref(call);
      reactor->OnDone(s);
    }
  }

  void StartCall() override {
    // This call initiates two batches, plus any backlog, each with a callback
    // 1. Send initial metadata (unless corked) + recv initial metadata
    // 2. Any backlog
    // 3. Recv trailing metadata, on_completion callback
    started_ = true;

    start_tag_.Set(call_.call(),
                   [this](bool ok) {
                     reactor_->OnReadInitialMetadataDone(ok);
                     MaybeFinish();
                   },
                   &start_ops_);
    start_ops_.SendInitialMetadata(&context_->send_initial_metadata_,
                                   context_->initial_metadata_flags());
    start_ops_.RecvInitialMetadata(context_);
    start_ops_.set_core_cq_tag(&start_tag_);
    call_.PerformOps(&start_ops_);

    // Also set up the read tag so it doesn't have to be set up each time
    read_tag_.Set(call_.call(),
                  [this](bool ok) {
                    reactor_->OnReadDone(ok);
                    MaybeFinish();
                  },
                  &read_ops_);
    read_ops_.set_core_cq_tag(&read_tag_);
    if (read_ops_at_start_) {
      call_.PerformOps(&read_ops_);
    }

    finish_tag_.Set(call_.call(), [this](bool ok) { MaybeFinish(); },
                    &finish_ops_);
    finish_ops_.ClientRecvStatus(context_, &finish_status_);
    finish_ops_.set_core_cq_tag(&finish_tag_);
    call_.PerformOps(&finish_ops_);
  }

  void Read(Response* msg) override {
    read_ops_.RecvMessage(msg);
    callbacks_outstanding_++;
    if (started_) {
      call_.PerformOps(&read_ops_);
    } else {
      read_ops_at_start_ = true;
    }
  }

  virtual void AddHold(int holds) override { callbacks_outstanding_ += holds; }
  virtual void RemoveHold() override { MaybeFinish(); }

 private:
  friend class ClientCallbackReaderFactory<Response>;

  template <class Request>
  ClientCallbackReaderImpl(
      Call call, ClientContext* context, Request* request,
      ::grpc::experimental::ClientReadReactor<Response>* reactor)
      : context_(context), call_(call), reactor_(reactor) {
    this->BindReactor(reactor);
    // TODO(vjpai): don't assert
    GPR_CODEGEN_ASSERT(start_ops_.SendMessagePtr(request).ok());
    start_ops_.ClientSendClose();
  }

  ClientContext* const context_;
  Call call_;
  ::grpc::experimental::ClientReadReactor<Response>* const reactor_;

  CallOpSet<CallOpSendInitialMetadata, CallOpSendMessage, CallOpClientSendClose,
            CallOpRecvInitialMetadata>
      start_ops_;
  CallbackWithSuccessTag start_tag_;

  CallOpSet<CallOpClientRecvStatus> finish_ops_;
  CallbackWithSuccessTag finish_tag_;
  Status finish_status_;

  CallOpSet<CallOpRecvMessage<Response>> read_ops_;
  CallbackWithSuccessTag read_tag_;
  bool read_ops_at_start_{false};

  // Minimum of 2 callbacks to pre-register for start and finish
  std::atomic_int callbacks_outstanding_{2};
  bool started_{false};
};

template <class Response>
class ClientCallbackReaderFactory {
 public:
  template <class Request>
  static void Create(
      ChannelInterface* channel, const ::grpc::internal::RpcMethod& method,
      ClientContext* context, const Request* request,
      ::grpc::experimental::ClientReadReactor<Response>* reactor) {
    Call call = channel->CreateCall(method, context, channel->CallbackCQ());

    g_core_codegen_interface->grpc_call_ref(call.call());
    new (g_core_codegen_interface->grpc_call_arena_alloc(
        call.call(), sizeof(ClientCallbackReaderImpl<Response>)))
        ClientCallbackReaderImpl<Response>(call, context, request, reactor);
  }
};

template <class Request>
class ClientCallbackWriterImpl
    : public ::grpc::experimental::ClientCallbackWriter<Request> {
 public:
  // always allocated against a call arena, no memory free required
  static void operator delete(void* ptr, std::size_t size) {
    assert(size == sizeof(ClientCallbackWriterImpl));
  }

  // This operator should never be called as the memory should be freed as part
  // of the arena destruction. It only exists to provide a matching operator
  // delete to the operator new so that some compilers will not complain (see
  // https://github.com/grpc/grpc/issues/11301) Note at the time of adding this
  // there are no tests catching the compiler warning.
  static void operator delete(void*, void*) { assert(0); }

  void MaybeFinish() {
    if (--callbacks_outstanding_ == 0) {
      Status s = std::move(finish_status_);
      auto* reactor = reactor_;
      auto* call = call_.call();
      this->~ClientCallbackWriterImpl();
      g_core_codegen_interface->grpc_call_unref(call);
      reactor->OnDone(s);
    }
  }

  void StartCall() override {
    // This call initiates two batches, plus any backlog, each with a callback
    // 1. Send initial metadata (unless corked) + recv initial metadata
    // 2. Any backlog
    // 3. Recv trailing metadata, on_completion callback
    started_ = true;

    start_tag_.Set(call_.call(),
                   [this](bool ok) {
                     reactor_->OnReadInitialMetadataDone(ok);
                     MaybeFinish();
                   },
                   &start_ops_);
    if (!start_corked_) {
      start_ops_.SendInitialMetadata(&context_->send_initial_metadata_,
                                     context_->initial_metadata_flags());
    }
    start_ops_.RecvInitialMetadata(context_);
    start_ops_.set_core_cq_tag(&start_tag_);
    call_.PerformOps(&start_ops_);

    // Also set up the read and write tags so that they don't have to be set up
    // each time
    write_tag_.Set(call_.call(),
                   [this](bool ok) {
                     reactor_->OnWriteDone(ok);
                     MaybeFinish();
                   },
                   &write_ops_);
    write_ops_.set_core_cq_tag(&write_tag_);

    if (write_ops_at_start_) {
      call_.PerformOps(&write_ops_);
    }

    if (writes_done_ops_at_start_) {
      call_.PerformOps(&writes_done_ops_);
    }

    finish_tag_.Set(call_.call(), [this](bool ok) { MaybeFinish(); },
                    &finish_ops_);
    finish_ops_.ClientRecvStatus(context_, &finish_status_);
    finish_ops_.set_core_cq_tag(&finish_tag_);
    call_.PerformOps(&finish_ops_);
  }

  void Write(const Request* msg, WriteOptions options) override {
    if (start_corked_) {
      write_ops_.SendInitialMetadata(&context_->send_initial_metadata_,
                                     context_->initial_metadata_flags());
      start_corked_ = false;
    }

    if (options.is_last_message()) {
      options.set_buffer_hint();
      write_ops_.ClientSendClose();
    }
    // TODO(vjpai): don't assert
    GPR_CODEGEN_ASSERT(write_ops_.SendMessagePtr(msg, options).ok());
    callbacks_outstanding_++;
    if (started_) {
      call_.PerformOps(&write_ops_);
    } else {
      write_ops_at_start_ = true;
    }
  }
  void WritesDone() override {
    if (start_corked_) {
      writes_done_ops_.SendInitialMetadata(&context_->send_initial_metadata_,
                                           context_->initial_metadata_flags());
      start_corked_ = false;
    }
    writes_done_ops_.ClientSendClose();
    writes_done_tag_.Set(call_.call(),
                         [this](bool ok) {
                           reactor_->OnWritesDoneDone(ok);
                           MaybeFinish();
                         },
                         &writes_done_ops_);
    writes_done_ops_.set_core_cq_tag(&writes_done_tag_);
    callbacks_outstanding_++;
    if (started_) {
      call_.PerformOps(&writes_done_ops_);
    } else {
      writes_done_ops_at_start_ = true;
    }
  }

  virtual void AddHold(int holds) override { callbacks_outstanding_ += holds; }
  virtual void RemoveHold() override { MaybeFinish(); }

 private:
  friend class ClientCallbackWriterFactory<Request>;

  template <class Response>
  ClientCallbackWriterImpl(
      Call call, ClientContext* context, Response* response,
      ::grpc::experimental::ClientWriteReactor<Request>* reactor)
      : context_(context),
        call_(call),
        reactor_(reactor),
        start_corked_(context_->initial_metadata_corked_) {
    this->BindReactor(reactor);
    finish_ops_.RecvMessage(response);
    finish_ops_.AllowNoMessage();
  }

  ClientContext* const context_;
  Call call_;
  ::grpc::experimental::ClientWriteReactor<Request>* const reactor_;

  CallOpSet<CallOpSendInitialMetadata, CallOpRecvInitialMetadata> start_ops_;
  CallbackWithSuccessTag start_tag_;
  bool start_corked_;

  CallOpSet<CallOpGenericRecvMessage, CallOpClientRecvStatus> finish_ops_;
  CallbackWithSuccessTag finish_tag_;
  Status finish_status_;

  CallOpSet<CallOpSendInitialMetadata, CallOpSendMessage, CallOpClientSendClose>
      write_ops_;
  CallbackWithSuccessTag write_tag_;
  bool write_ops_at_start_{false};

  CallOpSet<CallOpSendInitialMetadata, CallOpClientSendClose> writes_done_ops_;
  CallbackWithSuccessTag writes_done_tag_;
  bool writes_done_ops_at_start_{false};

  // Minimum of 2 callbacks to pre-register for start and finish
  std::atomic_int callbacks_outstanding_{2};
  bool started_{false};
};

template <class Request>
class ClientCallbackWriterFactory {
 public:
  template <class Response>
  static void Create(
      ChannelInterface* channel, const ::grpc::internal::RpcMethod& method,
      ClientContext* context, Response* response,
      ::grpc::experimental::ClientWriteReactor<Request>* reactor) {
    Call call = channel->CreateCall(method, context, channel->CallbackCQ());

    g_core_codegen_interface->grpc_call_ref(call.call());
    new (g_core_codegen_interface->grpc_call_arena_alloc(
        call.call(), sizeof(ClientCallbackWriterImpl<Request>)))
        ClientCallbackWriterImpl<Request>(call, context, response, reactor);
  }
};

class ClientCallbackUnaryImpl final
    : public ::grpc::experimental::ClientCallbackUnary {
 public:
  // always allocated against a call arena, no memory free required
  static void operator delete(void* ptr, std::size_t size) {
    assert(size == sizeof(ClientCallbackUnaryImpl));
  }

  // This operator should never be called as the memory should be freed as part
  // of the arena destruction. It only exists to provide a matching operator
  // delete to the operator new so that some compilers will not complain (see
  // https://github.com/grpc/grpc/issues/11301) Note at the time of adding this
  // there are no tests catching the compiler warning.
  static void operator delete(void*, void*) { assert(0); }

  void StartCall() override {
    // This call initiates two batches, each with a callback
    // 1. Send initial metadata + write + writes done + recv initial metadata
    // 2. Read message, recv trailing metadata
    started_ = true;

    start_tag_.Set(call_.call(),
                   [this](bool ok) {
                     reactor_->OnReadInitialMetadataDone(ok);
                     MaybeFinish();
                   },
                   &start_ops_);
    start_ops_.SendInitialMetadata(&context_->send_initial_metadata_,
                                   context_->initial_metadata_flags());
    start_ops_.RecvInitialMetadata(context_);
    start_ops_.set_core_cq_tag(&start_tag_);
    call_.PerformOps(&start_ops_);

    finish_tag_.Set(call_.call(), [this](bool ok) { MaybeFinish(); },
                    &finish_ops_);
    finish_ops_.ClientRecvStatus(context_, &finish_status_);
    finish_ops_.set_core_cq_tag(&finish_tag_);
    call_.PerformOps(&finish_ops_);
  }

  void MaybeFinish() {
    if (--callbacks_outstanding_ == 0) {
      Status s = std::move(finish_status_);
      auto* reactor = reactor_;
      auto* call = call_.call();
      this->~ClientCallbackUnaryImpl();
      g_core_codegen_interface->grpc_call_unref(call);
      reactor->OnDone(s);
    }
  }

 private:
  friend class ClientCallbackUnaryFactory;

  template <class Request, class Response>
  ClientCallbackUnaryImpl(Call call, ClientContext* context, Request* request,
                          Response* response,
                          ::grpc::experimental::ClientUnaryReactor* reactor)
      : context_(context), call_(call), reactor_(reactor) {
    this->BindReactor(reactor);
    // TODO(vjpai): don't assert
    GPR_CODEGEN_ASSERT(start_ops_.SendMessagePtr(request).ok());
    start_ops_.ClientSendClose();
    finish_ops_.RecvMessage(response);
    finish_ops_.AllowNoMessage();
  }

  ClientContext* const context_;
  Call call_;
  ::grpc::experimental::ClientUnaryReactor* const reactor_;

  CallOpSet<CallOpSendInitialMetadata, CallOpSendMessage, CallOpClientSendClose,
            CallOpRecvInitialMetadata>
      start_ops_;
  CallbackWithSuccessTag start_tag_;

  CallOpSet<CallOpGenericRecvMessage, CallOpClientRecvStatus> finish_ops_;
  CallbackWithSuccessTag finish_tag_;
  Status finish_status_;

  // This call will have 2 callbacks: start and finish
  std::atomic_int callbacks_outstanding_{2};
  bool started_{false};
};

class ClientCallbackUnaryFactory {
 public:
  template <class Request, class Response>
  static void Create(ChannelInterface* channel,
                     const ::grpc::internal::RpcMethod& method,
                     ClientContext* context, const Request* request,
                     Response* response,
                     ::grpc::experimental::ClientUnaryReactor* reactor) {
    Call call = channel->CreateCall(method, context, channel->CallbackCQ());

    g_core_codegen_interface->grpc_call_ref(call.call());

    new (g_core_codegen_interface->grpc_call_arena_alloc(
        call.call(), sizeof(ClientCallbackUnaryImpl)))
        ClientCallbackUnaryImpl(call, context, request, response, reactor);
  }
};

}  // namespace internal
}  // namespace grpc

#endif  // GRPCPP_IMPL_CODEGEN_CLIENT_CALLBACK_H


text:
package org.apache.sysml.runtime.matrix.data;

import java.util.ArrayList;

import org.apache.hadoop.io.WritableComparable;

import org.apache.sysml.runtime.DMLRuntimeException;
import org.apache.sysml.runtime.matrix.mapred.IndexedMatrixValue;
import org.apache.sysml.runtime.matrix.operators.AggregateBinaryOperator;
import org.apache.sysml.runtime.matrix.operators.AggregateOperator;
import org.apache.sysml.runtime.matrix.operators.AggregateUnaryOperator;
import org.apache.sysml.runtime.matrix.operators.BinaryOperator;
import org.apache.sysml.runtime.matrix.operators.Operator;
import org.apache.sysml.runtime.matrix.operators.QuaternaryOperator;
import org.apache.sysml.runtime.matrix.operators.ReorgOperator;
import org.apache.sysml.runtime.matrix.operators.ScalarOperator;
import org.apache.sysml.runtime.matrix.operators.UnaryOperator;
import org.apache.sysml.runtime.util.IndexRange;
import org.apache.sysml.runtime.util.UtilFunctions;

@SuppressWarnings("rawtypes")
public abstract class MatrixValue implements WritableComparable
{

	static public class CellIndex {
		public int row;
		public int column;

		public CellIndex(int r, int c) {
			row = r;
			column = c;
		}

		@Override
		public boolean equals(Object that)
		{
			if( !(that instanceof CellIndex) )
				return false;

			CellIndex cthat = (CellIndex) that;
			return (this.row == cthat.row && this.column == cthat.column);
		}

		public int hashCode() {
			return UtilFunctions.longHashCode((row << 16) + column);
		}

		public void set(int r, int c) {
			row = r;
			column = c;
		}
		public String toString()
		{
			return "("+row+","+column+")";
		}
	}

	public MatrixValue() {
		//do nothing
	}

	public MatrixValue(MatrixValue that) {
		copy(that);
	}

	public abstract int getNumRows();
	public abstract int getNumColumns();
	public abstract long getNonZeros();

	public abstract void setValue(int r, int c, double v);
	public abstract double getValue(int r, int c);

	public abstract boolean isInSparseFormat();
	public abstract boolean isEmpty();

	public abstract void reset();
	public abstract void reset(int rl, int cl);
	public abstract void reset(int rl, int cl, boolean sp);
	public abstract void reset(int rl, int cl, boolean sp, long nnzs);
	public abstract void reset(int rl, int cl, double v) throws DMLRuntimeException ;

	public abstract void copy(MatrixValue that);
	public abstract void copy(MatrixValue that, boolean sp);

	public abstract MatrixValue scalarOperations(ScalarOperator op, MatrixValue result)
	throws DMLRuntimeException;

	public abstract MatrixValue binaryOperations(BinaryOperator op, MatrixValue thatValue, MatrixValue result)
	throws DMLRuntimeException;

	public abstract void binaryOperationsInPlace(BinaryOperator op, MatrixValue thatValue)
	throws DMLRuntimeException;

	public abstract MatrixValue reorgOperations(ReorgOperator op, MatrixValue result,
			int startRow, int startColumn, int length)
	throws DMLRuntimeException;

	// tertiary where all three inputs are matrices
	public abstract void ternaryOperations(Operator op, MatrixValue that, MatrixValue that2, CTableMap resultMap, MatrixBlock resultBlock)
	throws DMLRuntimeException;

	// tertiary where first two inputs are matrices, and third input is a scalar (double)
	public abstract void ternaryOperations(Operator op, MatrixValue that, double scalar_that2, boolean ignoreZeros, CTableMap resultMap, MatrixBlock resultBlock)
	throws DMLRuntimeException;

	// tertiary where first input is a matrix, and second and third inputs are scalars (double)
	public abstract void ternaryOperations(Operator op, double scalar_that, double scalar_that2, CTableMap resultMap, MatrixBlock resultBlock)
	throws DMLRuntimeException;

	// tertiary where first input is a matrix, and second and third inputs are scalars (double)
	public abstract void ternaryOperations(Operator op, MatrixIndexes ix1, double scalar_that, boolean left, int brlen, CTableMap resultMap, MatrixBlock resultBlock)
	throws DMLRuntimeException;

	// tertiary where first and third inputs are matrices and second is a scalar
	public abstract void ternaryOperations(Operator op, double scalarThat, MatrixValue that2, CTableMap ctableResult, MatrixBlock ctableResultBlock)
	throws DMLRuntimeException;

	public abstract MatrixValue quaternaryOperations(QuaternaryOperator qop, MatrixValue um, MatrixValue vm, MatrixValue wm, MatrixValue out)
		throws DMLRuntimeException;

	public abstract MatrixValue aggregateUnaryOperations(AggregateUnaryOperator op, MatrixValue result,
			int brlen, int bclen, MatrixIndexes indexesIn) throws DMLRuntimeException;

	public abstract MatrixValue aggregateUnaryOperations(AggregateUnaryOperator op, MatrixValue result,
			int blockingFactorRow, int blockingFactorCol, MatrixIndexes indexesIn, boolean inCP)
	throws DMLRuntimeException;

	public abstract MatrixValue aggregateBinaryOperations(MatrixValue m1Value, MatrixValue m2Value,
			MatrixValue result, AggregateBinaryOperator op)
	throws DMLRuntimeException;

	public abstract MatrixValue aggregateBinaryOperations(MatrixIndexes m1Index, MatrixValue m1Value, MatrixIndexes m2Index, MatrixValue m2Value,
			MatrixValue result, AggregateBinaryOperator op)
	throws DMLRuntimeException;

	public abstract MatrixValue unaryOperations(UnaryOperator op, MatrixValue result)
	throws DMLRuntimeException;

	public abstract void unaryOperationsInPlace(UnaryOperator op) throws DMLRuntimeException;

	public abstract void incrementalAggregate(AggregateOperator aggOp, MatrixValue correction,
			MatrixValue newWithCorrection)	throws DMLRuntimeException;

	public abstract void incrementalAggregate(AggregateOperator aggOp, MatrixValue newWithCorrection)
	throws DMLRuntimeException;

	public abstract MatrixValue zeroOutOperations(MatrixValue result, IndexRange range, boolean complementary)
	throws DMLRuntimeException;

	public abstract void sliceOperations(ArrayList<IndexedMatrixValue> outlist, IndexRange range, int rowCut, int colCut,
			int blockRowFactor, int blockColFactor, int boundaryRlen, int boundaryClen)
	throws DMLRuntimeException;

	public abstract MatrixValue replaceOperations( MatrixValue result, double pattern, double replacement )
			throws DMLRuntimeException;

	public abstract void appendOperations(MatrixValue valueIn2, ArrayList<IndexedMatrixValue> outlist,
			int blockRowFactor, int blockColFactor, boolean cbind, boolean m2IsLast, int nextNCol)
			throws DMLRuntimeException ;
}


text:
def welcome(sunshine)
#   if state == sunshine
#     p sunshine
#   elsif state == other
#     p other
  if sunshine.include?("CA")
     p "Welcome to California"
  else
    p "You should move to California"

  end

end


text:
package tamaized.cosmicreality.client.render;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.EntityRenderer;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.RenderGlobal;
import net.minecraft.client.settings.GameSettings;
import net.minecraft.entity.Entity;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.TickEvent;
import net.minecraftforge.fml.relauncher.Side;
import org.lwjgl.opengl.GL11;
import tamaized.cosmicreality.CosmicReality;
import tamaized.cosmicreality.common.entity.EntityPortal;

import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

@Mod.EventBusSubscriber(modid = CosmicReality.modid, value = Side.CLIENT)
public class RenderMirror {

	private static Minecraft mc;
	private static Map<EntityPortal, Integer> portals = Maps.newHashMap();
	private static List<EntityPortal> remove = Lists.newArrayList();
	private static RenderGlobal globalRenderer;

	public static void registerPortal(EntityPortal portal, int newTextureId) {
		portals.put(portal, newTextureId);
	}

	public static void remove(EntityPortal portal) {
		remove.add(portal);
	}

	public static boolean hasPortal(EntityPortal entity) {
		return portals.containsKey(entity);
	}

	public static int getTextureID(EntityPortal portal) {
		return portals.get(portal);
	}

	@SubscribeEvent
	public static void onTick(TickEvent.RenderTickEvent event) {
		if (mc == null)
			mc = Minecraft.getMinecraft();
		if (globalRenderer == null)
			globalRenderer = new RenderGlobal(mc);
		if (event.phase.equals(TickEvent.Phase.END))
			return;

		if (!remove.isEmpty()) {
			for (EntityPortal portal : remove) {
				if (!portals.containsKey(portal))
					continue;
				GlStateManager.deleteTexture(portals.get(portal));
				portals.remove(portal);
			}
			remove.clear();
		}

		if (mc.inGameHasFocus) {
			for (Entry<EntityPortal, Integer> entry : portals.entrySet()) {
				EntityPortal entity = entry.getKey();
				int textureID = entry.getValue();

				if (entity.isDead) {
					remove(entity);
					continue;
				}

				// if (!entity.rendering) continue;

				if (!mc.player.canEntityBeSeen(entity))
					continue;

				if (entity.getDistanceToEntity(mc.player) < 25) {
					GameSettings settings = mc.gameSettings;
					//					RenderGlobal renderBackup = mc.renderGlobal;
					Entity entityBackup = mc.getRenderViewEntity();
					int thirdPersonBackup = settings.thirdPersonView;
					boolean hideGuiBackup = settings.hideGUI;
					int mipmapBackup = settings.mipmapLevels;
					float fovBackup = settings.fovSetting;
					int widthBackup = mc.displayWidth;
					int heightBackup = mc.displayHeight;
					int quality = 512;

					//					 globalRenderer.setWorldAndLoadRenderers(mc.world);
					//					mc.renderGlobal = globalRenderer;
					mc.setRenderViewEntity(entity);
					settings.thirdPersonView = 0;
					settings.hideGUI = true;
					settings.mipmapLevels = 0;
					mc.displayWidth = quality;
					mc.displayHeight = quality * 2;

					int fps = Math.max(30, settings.limitFramerate);
					EntityRenderer entityRenderer = mc.entityRenderer;
					entityRenderer.renderWorld(event.renderTickTime, System.nanoTime() + (1000000000 / fps));

					GlStateManager.bindTexture(textureID);
					GL11.glCopyTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGB, 0, 0, quality, quality * 2, 0);

					//					mc.renderGlobal = renderBackup;
					//noinspection ConstantConditions
					mc.setRenderViewEntity(entityBackup);
					settings.fovSetting = fovBackup;
					settings.thirdPersonView = thirdPersonBackup;
					settings.hideGUI = hideGuiBackup;
					settings.mipmapLevels = mipmapBackup;
					mc.displayWidth = widthBackup;
					mc.displayHeight = heightBackup;
				}

			}
		}
	}

}


text:
package cache

import (
	"fmt"

	v1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/util/sets"
	framework "k8s.io/kubernetes/pkg/scheduler/framework/v1alpha1"
)

// Snapshot is a snapshot of cache NodeInfo and NodeTree order. The scheduler takes a
// snapshot at the beginning of each scheduling cycle and uses it for its operations in that cycle.
type Snapshot struct {
	// nodeInfoMap a map of node name to a snapshot of its NodeInfo.
	nodeInfoMap map[string]*framework.NodeInfo
	// nodeInfoList is the list of nodes as ordered in the cache's nodeTree.
	nodeInfoList []*framework.NodeInfo
	// havePodsWithAffinityNodeInfoList is the list of nodes with at least one pod declaring affinity terms.
	havePodsWithAffinityNodeInfoList []*framework.NodeInfo
	generation                       int64
}

var _ framework.SharedLister = &Snapshot{}

// NewEmptySnapshot initializes a Snapshot struct and returns it.
func NewEmptySnapshot() *Snapshot {
	return &Snapshot{
		nodeInfoMap: make(map[string]*framework.NodeInfo),
	}
}

// NewSnapshot initializes a Snapshot struct and returns it.
func NewSnapshot(pods []*v1.Pod, nodes []*v1.Node) *Snapshot {
	nodeInfoMap := createNodeInfoMap(pods, nodes)
	nodeInfoList := make([]*framework.NodeInfo, 0, len(nodeInfoMap))
	havePodsWithAffinityNodeInfoList := make([]*framework.NodeInfo, 0, len(nodeInfoMap))
	for _, v := range nodeInfoMap {
		nodeInfoList = append(nodeInfoList, v)
		if len(v.PodsWithAffinity) > 0 {
			havePodsWithAffinityNodeInfoList = append(havePodsWithAffinityNodeInfoList, v)
		}
	}

	s := NewEmptySnapshot()
	s.nodeInfoMap = nodeInfoMap
	s.nodeInfoList = nodeInfoList
	s.havePodsWithAffinityNodeInfoList = havePodsWithAffinityNodeInfoList

	return s
}

// createNodeInfoMap obtains a list of pods and pivots that list into a map
// where the keys are node names and the values are the aggregated information
// for that node.
func createNodeInfoMap(pods []*v1.Pod, nodes []*v1.Node) map[string]*framework.NodeInfo {
	nodeNameToInfo := make(map[string]*framework.NodeInfo)
	for _, pod := range pods {
		nodeName := pod.Spec.NodeName
		if _, ok := nodeNameToInfo[nodeName]; !ok {
			nodeNameToInfo[nodeName] = framework.NewNodeInfo()
		}
		nodeNameToInfo[nodeName].AddPod(pod)
	}
	imageExistenceMap := createImageExistenceMap(nodes)

	for _, node := range nodes {
		if _, ok := nodeNameToInfo[node.Name]; !ok {
			nodeNameToInfo[node.Name] = framework.NewNodeInfo()
		}
		nodeInfo := nodeNameToInfo[node.Name]
		nodeInfo.SetNode(node)
		nodeInfo.ImageStates = getNodeImageStates(node, imageExistenceMap)
	}
	return nodeNameToInfo
}

// getNodeImageStates returns the given node's image states based on the given imageExistence map.
func getNodeImageStates(node *v1.Node, imageExistenceMap map[string]sets.String) map[string]*framework.ImageStateSummary {
	imageStates := make(map[string]*framework.ImageStateSummary)

	for _, image := range node.Status.Images {
		for _, name := range image.Names {
			imageStates[name] = &framework.ImageStateSummary{
				Size:     image.SizeBytes,
				NumNodes: len(imageExistenceMap[name]),
			}
		}
	}
	return imageStates
}

// createImageExistenceMap returns a map recording on which nodes the images exist, keyed by the images' names.
func createImageExistenceMap(nodes []*v1.Node) map[string]sets.String {
	imageExistenceMap := make(map[string]sets.String)
	for _, node := range nodes {
		for _, image := range node.Status.Images {
			for _, name := range image.Names {
				if _, ok := imageExistenceMap[name]; !ok {
					imageExistenceMap[name] = sets.NewString(node.Name)
				} else {
					imageExistenceMap[name].Insert(node.Name)
				}
			}
		}
	}
	return imageExistenceMap
}

// NodeInfos returns a NodeInfoLister.
func (s *Snapshot) NodeInfos() framework.NodeInfoLister {
	return s
}

// NumNodes returns the number of nodes in the snapshot.
func (s *Snapshot) NumNodes() int {
	return len(s.nodeInfoList)
}

// List returns the list of nodes in the snapshot.
func (s *Snapshot) List() ([]*framework.NodeInfo, error) {
	return s.nodeInfoList, nil
}

// HavePodsWithAffinityList returns the list of nodes with at least one pods with inter-pod affinity
func (s *Snapshot) HavePodsWithAffinityList() ([]*framework.NodeInfo, error) {
	return s.havePodsWithAffinityNodeInfoList, nil
}

// Get returns the NodeInfo of the given node name.
func (s *Snapshot) Get(nodeName string) (*framework.NodeInfo, error) {
	if v, ok := s.nodeInfoMap[nodeName]; ok && v.Node() != nil {
		return v, nil
	}
	return nil, fmt.Errorf("nodeinfo not found for node name %q", nodeName)
}


text:
package com.qualogy.qafe.mgwt.client.activities.searchbox;

import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.FormPanel.SubmitEvent;
import com.google.gwt.user.client.ui.FormPanel.SubmitHandler;
import com.googlecode.mgwt.ui.client.widget.MSearchBox;
import com.qualogy.qafe.mgwt.client.DetailViewGwtImpl;

/**
 * @author Daniel Kurka
 *
 */
public class SearchBoxViewGwtImpl extends DetailViewGwtImpl implements SearchBoxView {

	public SearchBoxViewGwtImpl() {

		FormPanel formPanel = new FormPanel("");
		formPanel.addSubmitHandler(new SubmitHandler() {

			@Override
			public void onSubmit(SubmitEvent event) {
				event.cancel();

			}
		});
		MSearchBox searchBox = new MSearchBox();
		formPanel.setWidget(searchBox);
		scrollPanel.setWidget(formPanel);
	}

}


text:
package org.apache.geode.internal.cache;

import org.apache.geode.StatisticDescriptor;
import org.apache.geode.Statistics;
import org.apache.geode.StatisticsFactory;
import org.apache.geode.StatisticsType;
import org.apache.geode.StatisticsTypeFactory;
import org.apache.geode.annotations.Immutable;
import org.apache.geode.internal.statistics.StatisticsTypeFactoryImpl;

/**
 * GemFire statistics about Disk Directories
 *
 *
 * @since GemFire 3.2
 */
public class DiskDirectoryStats {

  @Immutable
  private static final StatisticsType type;

  //////////////////// Statistic "Id" Fields ////////////////////

  private static final int diskSpaceId;
  private static final int maxSpaceId;
  private static final int volumeSizeId;
  private static final int volumeFreeSpaceId;
  private static final int volumeFreeSpaceChecksId;
  private static final int volumeFreeSpaceTimeId;

  static {
    String statName = "DiskDirStatistics";
    String statDescription = "Statistics about a single disk directory for a region";

    final String diskSpaceDesc =
        "The total number of bytes currently being used on disk in this directory for oplog files.";
    final String maxSpaceDesc =
        "The configured maximum number of bytes allowed in this directory for oplog files. Note that some product configurations allow this maximum to be exceeded.";
    StatisticsTypeFactory f = StatisticsTypeFactoryImpl.singleton();

    type = f.createType(statName, statDescription,
        new StatisticDescriptor[] {f.createLongGauge("diskSpace", diskSpaceDesc, "bytes"),
            f.createLongGauge("maximumSpace", maxSpaceDesc, "bytes"),
            f.createLongGauge("volumeSize", "The total size in bytes of the disk volume", "bytes"),
            f.createLongGauge("volumeFreeSpace", "The total free space in bytes on the disk volume",
                "bytes"),
            f.createLongCounter("volumeFreeSpaceChecks", "The total number of disk space checks",
                "checks"),
            f.createLongCounter("volumeFreeSpaceTime", "The total time spent checking disk usage",
                "nanoseconds")});

    // Initialize id fields
    diskSpaceId = type.nameToId("diskSpace");
    maxSpaceId = type.nameToId("maximumSpace");
    volumeSizeId = type.nameToId("volumeSize");
    volumeFreeSpaceId = type.nameToId("volumeFreeSpace");
    volumeFreeSpaceChecksId = type.nameToId("volumeFreeSpaceChecks");
    volumeFreeSpaceTimeId = type.nameToId("volumeFreeSpaceTime");
  }

  ////////////////////// Instance Fields //////////////////////

  /** The Statistics object that we delegate most behavior to */
  private final Statistics stats;

  /////////////////////// Constructors ///////////////////////

  /**
   * Creates a new DiskRegionStatistics for the given region.
   */
  public DiskDirectoryStats(StatisticsFactory f, String name) {
    this.stats = f.createStatistics(type, name);
  }

  ///////////////////// Instance Methods /////////////////////

  public void close() {
    this.stats.close();
  }

  /**
   * Returns the current value of the "diskSpace" stat.
   */
  public long getDiskSpace() {
    return this.stats.getLong(diskSpaceId);
  }

  public void incDiskSpace(long delta) {
    this.stats.incLong(diskSpaceId, delta);
  }

  public void setMaxSpace(long v) {
    this.stats.setLong(maxSpaceId, v);
  }

  public void addVolumeCheck(long total, long free, long time) {
    stats.setLong(volumeSizeId, total);
    stats.setLong(volumeFreeSpaceId, free);
    stats.incLong(volumeFreeSpaceChecksId, 1);
    stats.incLong(volumeFreeSpaceTimeId, time);
  }

  public Statistics getStats() {
    return stats;
  }

}


text:
package com.cardpay.pccredit.dimensional.dao;

import java.util.List;

import org.apache.ibatis.annotations.Param;

import com.cardpay.pccredit.dimensional.model.Dimensional;
import com.wicresoft.jrad.base.database.dao.query.QueryContext;
import com.wicresoft.util.annotation.Mapper;

/**
 * Description of DimensionalDao
 *
 * @author 王海东
 * @created on 2014-10-20
 *
 * @version $Id:$
 */
@Mapper
public interface DimensionalDao {
	//根据Filter查询四维评估表
	public List<Dimensional> findDimensionalByFilter(QueryContext qc);
	//根据customerId修改四维评估表
	public void updateDimensionalByCustomerId(Dimensional dimensional);
	//根据customerId 查询四维评估表
	public Dimensional  findDimensionalByCustomerId(String customerId);

	/**
	 * 根据进件申请Id查询思维评估信息
	 * @param applicationId
	 * @return
	 */
	public Dimensional findDimensionalByAppId(@Param("applicationId") String applicationId);

}


text:
/*
 * asm-generic/mutex-xchg.h
 *
 * Generic implementation of the mutex fastpath, based on xchg().
 *
 * NOTE: An xchg based implementation might be less optimal than an atomic
 *       decrement/increment based implementation. If your architecture
 *       has a reasonable atomic dec/inc then you should probably use
 *	 asm-generic/mutex-dec.h instead, or you could open-code an
 *	 optimized version in asm/mutex.h.
 */
#ifndef _ASM_GENERIC_MUTEX_XCHG_H
#define _ASM_GENERIC_MUTEX_XCHG_H

/**
 *  __mutex_fastpath_lock - try to take the lock by moving the count
 *                          from 1 to a 0 value
 *  @count: pointer of type atomic_t
 *  @fail_fn: function to call if the original value was not 1
 *
 * Change the count from 1 to a value lower than 1, and call <fail_fn> if it
 * wasn't 1 originally. This function MUST leave the value lower than 1
 * even when the "1" assertion wasn't true.
 */
static inline void
__mutex_fastpath_lock(atomic_t *count, fastcall void (*fail_fn)(atomic_t *))
{
	if (unlikely(atomic_xchg(count, 0) != 1))
		fail_fn(count);
	else
		smp_mb();
}

/**
 *  __mutex_fastpath_lock_retval - try to take the lock by moving the count
 *                                 from 1 to a 0 value
 *  @count: pointer of type atomic_t
 *  @fail_fn: function to call if the original value was not 1
 *
 * Change the count from 1 to a value lower than 1, and call <fail_fn> if it
 * wasn't 1 originally. This function returns 0 if the fastpath succeeds,
 * or anything the slow path function returns
 */
static inline int
__mutex_fastpath_lock_retval(atomic_t *count, fastcall int (*fail_fn)(atomic_t *))
{
	if (unlikely(atomic_xchg(count, 0) != 1))
		return fail_fn(count);
	else {
		smp_mb();
		return 0;
	}
}

/**
 *  __mutex_fastpath_unlock - try to promote the mutex from 0 to 1
 *  @count: pointer of type atomic_t
 *  @fail_fn: function to call if the original value was not 0
 *
 * try to promote the mutex from 0 to 1. if it wasn't 0, call <function>
 * In the failure case, this function is allowed to either set the value to
 * 1, or to set it to a value lower than one.
 * If the implementation sets it to a value of lower than one, the
 * __mutex_slowpath_needs_to_unlock() macro needs to return 1, it needs
 * to return 0 otherwise.
 */
static inline void
__mutex_fastpath_unlock(atomic_t *count, fastcall void (*fail_fn)(atomic_t *))
{
	smp_mb();
	if (unlikely(atomic_xchg(count, 1) != 0))
		fail_fn(count);
}

#define __mutex_slowpath_needs_to_unlock()		0

/**
 * __mutex_fastpath_trylock - try to acquire the mutex, without waiting
 *
 *  @count: pointer of type atomic_t
 *  @fail_fn: spinlock based trylock implementation
 *
 * Change the count from 1 to a value lower than 1, and return 0 (failure)
 * if it wasn't 1 originally, or return 1 (success) otherwise. This function
 * MUST leave the value lower than 1 even when the "1" assertion wasn't true.
 * Additionally, if the value was < 0 originally, this function must not leave
 * it to 0 on failure.
 *
 * If the architecture has no effective trylock variant, it should call the
 * <fail_fn> spinlock-based trylock variant unconditionally.
 */
static inline int
__mutex_fastpath_trylock(atomic_t *count, int (*fail_fn)(atomic_t *))
{
	int prev = atomic_xchg(count, 0);

	if (unlikely(prev < 0)) {
		/*
		 * The lock was marked contended so we must restore that
		 * state. If while doing so we get back a prev value of 1
		 * then we just own it.
		 *
		 * [ In the rare case of the mutex going to 1, to 0, to -1
		 *   and then back to 0 in this few-instructions window,
		 *   this has the potential to trigger the slowpath for the
		 *   owner's unlock path needlessly, but that's not a problem
		 *   in practice. ]
		 */
		prev = atomic_xchg(count, prev);
		if (prev < 0)
			prev = 0;
	}
	smp_mb();

	return prev;
}

#endif


text:
<?php

declare(strict_types = 1);

namespace KoolKode\Async\Concurrent\Pool;

use KoolKode\Async\Context;

/**
 * Factory that creates workers to be used by a worker pool instance.
 *
 * @author Martin Schröder
 */
interface WorkerFactory
{
    /**
     * Create a new worker to be used by a pool.
     *
     * @param Context $context Async execution context.
     * @param int $id Numeric worker identifier.
     * @return Worker A new worker instance.
     */
    public function createWorker(Context $context, int $id): \Generator;
}


text:
package org.ops4j.pax.cdi.extension.impl.compat;

import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;

public class Osgi5ServiceObjectsWrapper<S> implements ServiceObjectsWrapper<S> {

    private BundleContext bundleContext;
    private ServiceReference<S> serviceReference;

    @Override
    public S getService() {
        return bundleContext.getService(serviceReference);
    }

    @Override
    public void ungetService(S service) {
        bundleContext.ungetService(serviceReference);
    }

    @Override
    public ServiceReference<S> getServiceReference() {
        return serviceReference;
    }

    @Override
    public void init(BundleContext bc, ServiceReference<S> serviceRef) {
        this.bundleContext = bc;
        this.serviceReference = serviceRef;
    }
}


text:
<?php

namespace Magento\Backup\Helper;

use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\App\MaintenanceMode;
use Magento\Framework\Filesystem;

/**
 * Backup data helper
 */
class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
    /**
     * @var Filesystem
     */
    protected $_filesystem;

    /**
     * @var \Magento\Framework\AuthorizationInterface
     */
    protected $_authorization;

    /**
     * @var \Magento\Framework\App\Cache\TypeListInterface
     */
    protected $_cacheTypeList;

    /**
     * Construct
     *
     * @param \Magento\Framework\App\Helper\Context $context
     * @param Filesystem $filesystem
     * @param \Magento\Framework\AuthorizationInterface $authorization
     * @param \Magento\Framework\App\Cache\TypeListInterface $cacheTypeList
     */
    public function __construct(
        \Magento\Framework\App\Helper\Context $context,
        Filesystem $filesystem,
        \Magento\Framework\AuthorizationInterface $authorization,
        \Magento\Framework\App\Cache\TypeListInterface $cacheTypeList
    ) {
        parent::__construct($context);
        $this->_authorization = $authorization;
        $this->_filesystem = $filesystem;
        $this->_cacheTypeList = $cacheTypeList;
    }

    /**
     * Get all possible backup type values with descriptive title
     *
     * @return array
     */
    public function getBackupTypes()
    {
        return [
            \Magento\Framework\Backup\Factory::TYPE_DB => __('Database'),
            \Magento\Framework\Backup\Factory::TYPE_MEDIA => __('Database and Media'),
            \Magento\Framework\Backup\Factory::TYPE_SYSTEM_SNAPSHOT => __('System'),
            \Magento\Framework\Backup\Factory::TYPE_SNAPSHOT_WITHOUT_MEDIA => __('System (excluding Media)')
        ];
    }

    /**
     * Get all possible backup type values
     *
     * @return string[]
     */
    public function getBackupTypesList()
    {
        return [
            \Magento\Framework\Backup\Factory::TYPE_DB,
            \Magento\Framework\Backup\Factory::TYPE_SYSTEM_SNAPSHOT,
            \Magento\Framework\Backup\Factory::TYPE_SNAPSHOT_WITHOUT_MEDIA,
            \Magento\Framework\Backup\Factory::TYPE_MEDIA
        ];
    }

    /**
     * Get default backup type value
     *
     * @return string
     */
    public function getDefaultBackupType()
    {
        return \Magento\Framework\Backup\Factory::TYPE_DB;
    }

    /**
     * Get directory path where backups stored
     *
     * @return string
     */
    public function getBackupsDir()
    {
        return $this->_filesystem->getDirectoryWrite(DirectoryList::VAR_DIR)->getAbsolutePath('backups');
    }

    /**
     * Get backup file extension by backup type
     *
     * @param string $type
     * @return string
     */
    public function getExtensionByType($type)
    {
        $extensions = $this->getExtensions();
        return isset($extensions[$type]) ? $extensions[$type] : '';
    }

    /**
     * Get all types to extensions map
     *
     * @return array
     */
    public function getExtensions()
    {
        return [
            \Magento\Framework\Backup\Factory::TYPE_SYSTEM_SNAPSHOT => 'tgz',
            \Magento\Framework\Backup\Factory::TYPE_SNAPSHOT_WITHOUT_MEDIA => 'tgz',
            \Magento\Framework\Backup\Factory::TYPE_MEDIA => 'tgz',
            \Magento\Framework\Backup\Factory::TYPE_DB => 'gz'
        ];
    }

    /**
     * Generate backup download name
     *
     * @param \Magento\Backup\Model\Backup $backup
     * @return string
     */
    public function generateBackupDownloadName(\Magento\Backup\Model\Backup $backup)
    {
        $additionalExtension = $backup->getType() == \Magento\Framework\Backup\Factory::TYPE_DB ? '.sql' : '';
        return $backup->getTime() .
            '_' .
            $backup->getType() .
            '_' .
            $backup->getName() .
            $additionalExtension .
            '.' .
            $this->getExtensionByType(
                $backup->getType()
            );
    }

    /**
     * Check Permission for Rollback
     *
     * @return bool
     */
    public function isRollbackAllowed()
    {
        return $this->_authorization->isAllowed('Magento_Backup::rollback');
    }

    /**
     * Get paths that should be ignored when creating system snapshots
     *
     * @return string[]
     */
    public function getBackupIgnorePaths()
    {
        return [
            '.git',
            '.svn',
            $this->_filesystem->getDirectoryRead(MaintenanceMode::FLAG_DIR)
                ->getAbsolutePath(MaintenanceMode::FLAG_FILENAME),
            $this->_filesystem->getDirectoryRead(DirectoryList::SESSION)->getAbsolutePath(),
            $this->_filesystem->getDirectoryRead(DirectoryList::CACHE)->getAbsolutePath(),
            $this->_filesystem->getDirectoryRead(DirectoryList::LOG)->getAbsolutePath(),
            $this->_filesystem->getDirectoryRead(DirectoryList::VAR_DIR)->getAbsolutePath('full_page_cache'),
            $this->_filesystem->getDirectoryRead(DirectoryList::VAR_DIR)->getAbsolutePath('locks'),
            $this->_filesystem->getDirectoryRead(DirectoryList::VAR_DIR)->getAbsolutePath('report'),
        ];
    }

    /**
     * Get paths that should be ignored when rolling back system snapshots
     *
     * @return string[]
     */
    public function getRollbackIgnorePaths()
    {
        return [
            '.svn',
            '.git',
            $this->_filesystem->getDirectoryRead(MaintenanceMode::FLAG_DIR)
                ->getAbsolutePath(MaintenanceMode::FLAG_FILENAME),
            $this->_filesystem->getDirectoryRead(DirectoryList::SESSION)->getAbsolutePath(),
            $this->_filesystem->getDirectoryRead(DirectoryList::LOG)->getAbsolutePath(),
            $this->_filesystem->getDirectoryRead(DirectoryList::VAR_DIR)->getAbsolutePath('locks'),
            $this->_filesystem->getDirectoryRead(DirectoryList::VAR_DIR)->getAbsolutePath('report'),
            $this->_filesystem->getDirectoryRead(DirectoryList::ROOT)->getAbsolutePath('errors'),
            $this->_filesystem->getDirectoryRead(DirectoryList::ROOT)->getAbsolutePath('index.php'),
        ];
    }

    /**
     * Get backup create success message by backup type
     *
     * @param string $type
     * @return void|string
     */
    public function getCreateSuccessMessageByType($type)
    {
        $messagesMap = [
            \Magento\Framework\Backup\Factory::TYPE_SYSTEM_SNAPSHOT => __('You created the system backup.'),
            \Magento\Framework\Backup\Factory::TYPE_SNAPSHOT_WITHOUT_MEDIA => __(
                'You created the system backup (excluding media).'
            ),
            \Magento\Framework\Backup\Factory::TYPE_MEDIA => __('You created the database and media backup.'),
            \Magento\Framework\Backup\Factory::TYPE_DB => __('You created the database backup.'),
        ];

        if (!isset($messagesMap[$type])) {
            return;
        }

        return $messagesMap[$type];
    }

    /**
     * Invalidate Cache
     *
     * @return $this
     */
    public function invalidateCache()
    {
        if ($cacheTypes = $this->_cacheConfig->getTypes()) {
            $cacheTypesList = array_keys($cacheTypes);
            $this->_cacheTypeList->invalidate($cacheTypesList);
        }
        return $this;
    }

    /**
     * Creates backup's display name from it's name
     *
     * @param string $name
     * @return string
     */
    public function nameToDisplayName($name)
    {
        return str_replace('_', ' ', $name);
    }

    /**
     * Extracts information from backup's filename
     *
     * @param string $filename
     * @return \Magento\Framework\DataObject
     */
    public function extractDataFromFilename($filename)
    {
        $extensions = $this->getExtensions();

        $filenameWithoutExtension = $filename;

        foreach ($extensions as $extension) {
            $filenameWithoutExtension = preg_replace(
                '/' . preg_quote($extension, '/') . '$/',
                '',
                $filenameWithoutExtension
            );
        }

        $filenameWithoutExtension = substr($filenameWithoutExtension, 0, strrpos($filenameWithoutExtension, "."));

        list($time, $type) = explode("_", $filenameWithoutExtension);

        $name = str_replace($time . '_' . $type, '', $filenameWithoutExtension);

        if (!empty($name)) {
            $name = substr($name, 1);
        }

        $result = new \Magento\Framework\DataObject();
        $result->addData(['name' => $name, 'type' => $type, 'time' => $time]);

        return $result;
    }
}


text:
require 'ec2_metadata'

module GCEMetadata
  class Root < Base
    def initialize(path = '/')
      @path = path
      @default_child_key = 'v1'
    end

    def new_child(child_key)
      logging("new_child(#{child_key.inspect})") do
        Revision.new("#{path}#{child_key}/")
      end
    end

    def is_struct?(child_key)
      true
    end

  end
end


text:
'use strict';

require('../qunit_extensions');

var documentStoreSeed = require('../../fixtures/collab/documentStoreSeed');
var changeStoreSeed = require('../../fixtures/collab/changeStoreSeed');
var snapshotStoreSeed = require('../../fixtures/collab/snapshotStoreSeed');
var DocumentStore = require('../../../collab/DocumentStore');
var SnapshotStore = require('../../../collab/SnapshotStore');
var ChangeStore = require('../../../collab/ChangeStore');
var SnapshotEngine = require('../../../collab/SnapshotEngine');
var testSnapshotEngine = require('../../collab/testSnapshotEngine');
var testSnapshotEngineWithStore = require('../../collab/testSnapshotEngineWithStore');
var twoParagraphs = require('../../fixtures/collab/two-paragraphs');

// Setup store instances

var documentStore = new DocumentStore();
var changeStore = new ChangeStore();
var snapshotEngine = new SnapshotEngine({
  documentStore: documentStore,
  changeStore: changeStore,
  schemas: {
    'prose-article': {
      name: 'prose-article',
      version: '1.0.0',
      documentFactory: twoParagraphs
    }
  }
});
var snapshotStore = new SnapshotStore();
var snapshotEngineWithStore = new SnapshotEngine({
  documentStore: documentStore,
  changeStore: changeStore,
  snapshotStore: snapshotStore,
  schemas: {
    'prose-article': {
      name: 'prose-article',
      version: '1.0.0',
      documentFactory: twoParagraphs
    }
  }
});

QUnit.module('collab/SnapshotEngine', {
  beforeEach: function(assert) {
    var done = assert.async();
    var newDocumentStoreSeed = JSON.parse(JSON.stringify(documentStoreSeed));
    var newChangeStoreSeed = JSON.parse(JSON.stringify(changeStoreSeed));
    var newSnapshotStoreSeed = JSON.parse(JSON.stringify(snapshotStoreSeed));

    documentStore.seed(newDocumentStoreSeed, function(err) {
      if (err) return console.error(err);
      changeStore.seed(newChangeStoreSeed, function(err) {
        if (err) return console.error(err);
        snapshotStore.seed(newSnapshotStoreSeed, function(err) {
          if (err) return console.error(err);
          done();
        });
      });
    });
  }
});

// Run the generic testsuite with an engine that does not have a store attached
testSnapshotEngine(snapshotEngine, twoParagraphs, QUnit);
// Run the same testsuite but this time with a store
testSnapshotEngine(snapshotEngineWithStore, twoParagraphs, QUnit);

// Run tests that are only relevant when a snapshot store is provided to the engine
testSnapshotEngineWithStore(snapshotEngineWithStore, twoParagraphs, QUnit);


text:
import { entityTreeDropResolvers } from '../../lib/configuration.js'

export default function acceptDrop () {
  const valid = []

  entityTreeDropResolvers.forEach((resolver) => {
    if (valid.indexOf(resolver.type) === -1) {
      valid.push(resolver.type)
    }
  })

  return valid
}