text:
package org.openhubframework.openhub.core.common.asynch;

import static org.openhubframework.openhub.api.asynch.AsynchConstants.*;
import static org.openhubframework.openhub.api.configuration.CoreProps.ASYNCH_CONCURRENT_CONSUMERS;
import static org.openhubframework.openhub.api.configuration.CoreProps.ASYNCH_COUNT_PARTLY_FAILS_BEFORE_FAILED;

import java.util.Map;
import javax.annotation.Nullable;

import org.apache.camel.*;
import org.apache.camel.component.spring.ws.SpringWebserviceConstants;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

import org.openhubframework.openhub.api.asynch.AsynchConstants;
import org.openhubframework.openhub.api.asynch.confirm.ConfirmationCallback;
import org.openhubframework.openhub.api.common.EmailService;
import org.openhubframework.openhub.api.configuration.ConfigurableValue;
import org.openhubframework.openhub.api.configuration.ConfigurationItem;
import org.openhubframework.openhub.api.entity.ExternalCall;
import org.openhubframework.openhub.api.entity.Message;
import org.openhubframework.openhub.api.entity.MsgStateEnum;
import org.openhubframework.openhub.api.exception.LockFailureException;
import org.openhubframework.openhub.api.exception.StoppingException;
import org.openhubframework.openhub.api.extcall.ExtCallComponentParams;
import org.openhubframework.openhub.api.route.AbstractBasicRoute;
import org.openhubframework.openhub.api.route.CamelConfiguration;
import org.openhubframework.openhub.common.log.LogContextFilter;
import org.openhubframework.openhub.core.common.asynch.confirm.ConfirmationService;
import org.openhubframework.openhub.core.common.event.AsynchEventHelper;
import org.openhubframework.openhub.spi.msg.MessageService;
import org.openhubframework.openhub.spi.node.NodeService;

/**
 * Route definition that processes asynchronous message taken from message queue.
 *

 * Some "well-known" URIs:
 *

 *
{@link AsynchConstants#URI_ERROR_FATAL}
 *
{@link AsynchConstants#URI_ASYNC_MSG}
 *
{@link AsynchConstants#URI_ERROR_HANDLING}
 *

 *
 * @author Petr Juza
 */
@CamelConfiguration(value = AsynchMessageRoute.ROUTE_BEAN)
public class AsynchMessageRoute extends AbstractBasicRoute {

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

    public static final String ROUTE_BEAN = "msgRouteBean";

    /**
     * The main route for processing message from the queue.
     */
    public static final String ROUTE_ID_SYNC = "syncProcessOut" + ROUTE_SUFFIX;

    /**
     * The route that polls the message queue for processing a new message.
     */
    public static final String ROUTE_ID_ASYNC = "asyncProcess" + ROUTE_SUFFIX;

    /**
     * The route that gets message from SEDA and processing it.
     */
    private static final String ROUTE_ID_ASYNC_OUT = "asyncProcessOut" + ROUTE_SUFFIX;

    /**
     * Route for error handling.
     */
    public static final String ROUTE_ID_ASYNCH_ERROR_HANDLING = "asynchProcessOutErrHandling" + ROUTE_SUFFIX;

    /**
     * Route for processing FATAL error.
     */
    public static final String ROUTE_ID_ERROR_FATAL = "asynchProcessOutErrFatal" + ROUTE_SUFFIX;

    /**
     * Route for post-processing when FATAL error occurs.
     */
    public static final String ROUTE_ID_POST_PROCESS_AFTER_FAILED = "postProcessAfterFatal" + ROUTE_SUFFIX;

    /**
     * Route for post-processing when FATAL error occurs.
     */
    public static final String ROUTE_ID_POST_PROCESS_AFTER_OK = "postProcessAfterOK" + ROUTE_SUFFIX;

    /**
     * Route for ensuring the provided message status confirmation to the source system.
     */
    public static final String ROUTE_ID_CONFIRM_MESSAGE = "asynchConfirm" + ROUTE_SUFFIX;

    /**
     * URI for asynchronous message processing (with SEDA).
     */
    public static final String URI_ASYNC_PROCESSING_MSG = "seda:asynch_message_route"
            + "?concurrentConsumers={{" + ASYNCH_CONCURRENT_CONSUMERS + "}}&waitForTaskToComplete=Never"
            + "&blockWhenFull=true&queueFactory=#" + PRIORITY_QUEUE_FACTORY;

    /**
     * URI for synchronous message processing.
     */
    public static final String URI_SYNC_MSG = "direct:sync_message_route";

    /**
     * Count of partly fails before message will be marked as completely FAILED.
     */
    @ConfigurableValue(key = ASYNCH_COUNT_PARTLY_FAILS_BEFORE_FAILED)
    private ConfigurationItem<Integer> countPartlyFailsBeforeFailed;

    /**
     * Route for processing {@link Message messages} from the queue.
     *

     * Prerequisite: Message in the body in the state {@link MsgStateEnum#PROCESSING}
     *

     * Output: correctly processed message
     */
    @Override
    @SuppressWarnings("unchecked")
    protected void doConfigure() throws Exception {

        // handle WS faults as exceptions
        getContext().setHandleFault(true);

        // log every exception at ERROR level
        // note: logging handler extends DefaultErrorHandler
        getContext().setErrorHandlerBuilder(loggingErrorHandler("org.openhubframework.openhub"));

        onException(Exception.class)
            .handled(true)
            .log(LoggingLevel.DEBUG, "Asynch. routes - unspecified exception caught: ${property."
                    + Exchange.EXCEPTION_CAUGHT + ".message}.")
            // forcefully mark current external call as unsuccessful
            .setProperty(ExtCallComponentParams.EXTERNAL_CALL_SUCCESS, constant(false))
            .to(URI_ERROR_HANDLING);

        // route for input asynchronous processing
        from(AsynchConstants.URI_ASYNC_MSG)
                .routeId(ROUTE_ID_ASYNC)
                .bean(ROUTE_BEAN, "changeStateMessageToInQueue")
                .to(URI_ASYNC_PROCESSING_MSG);

        // route for output asynchronous processing from SEDA
        from(URI_ASYNC_PROCESSING_MSG)
                .routeId(ROUTE_ID_ASYNC_OUT)
                .bean(ROUTE_BEAN, "setLogContextParams")
                .to(URI_SYNC_MSG);

        // route for synchronous processing
        from(URI_SYNC_MSG)
                .routeId(ROUTE_ID_SYNC)

                // set flag that it's asynchronous processing
                .setHeader(ASYNCH_MSG_HEADER, constant(Boolean.TRUE))

                // check Message
                .validate(body().isInstanceOf(Message.class))
                .validate((Predicate) simple(
                        "${body.state} == ${type:org.openhubframework.openhub.api.entity.MsgStateEnum.IN_QUEUE}"))

                .bean(this, "logStartProcessing")

                // check if node process existing message
                .bean(ROUTE_BEAN, "isAbleToHandleExistingMessage")

                .choice()
                    .when().method(ROUTE_BEAN, "isMessageObsolete")
                        .log(LoggingLevel.WARN,
                                "Message ${body.toHumanString} was obsolete, stopped further processing.")
                        .stop()
                .end()

                // set objectId and objectType (it's set in first message processing but no for next ones)
                .bean(this, "setEntityInfo")

                // save Message into header and change body into payload
                .setHeader(MSG_HEADER, body())
                .transform(simple("${body.payload}"))

                // reset TRACE_HEADER for all cases because it's available for first try only
                .removeHeader(TraceHeaderProcessor.TRACE_HEADER)
                // also remove inbound Spring WS SOAP header
                .removeHeader(SpringWebserviceConstants.SPRING_WS_SOAP_HEADER)

                // notify that message is being processed
                .process(new Processor() {
                    @Override
                    public void process(Exchange exchange) throws Exception {
                        AsynchEventHelper.notifyMsgProcessing(exchange);
                    }
                })

                // redirect message to next route
                .routingSlip(method(ROUTE_BEAN, "nextRoute"))

                .choice()
                    .when(header(NO_EFFECT_PROCESS_HEADER).isEqualTo(Boolean.TRUE))
                         // mark message as PARTLY_FAILED but without increasing error count
                        .bean(MessageService.BEAN, "setStatePartlyFailedWithoutError")

                    .when().method(ROUTE_BEAN, "checkParentMessage")
                        // it's a parent message
                        .bean(MessageService.BEAN, "setStateWaiting")

                        .process(new Processor() {
                            @Override
                            public void process(Exchange exchange) throws Exception {
                                Message msg = (Message) exchange.getIn().getHeader(MSG_HEADER);

                                // check current state (it's possible that parent message has been already finished)
                                if (msg.getState() == MsgStateEnum.WAITING) {
                                    AsynchEventHelper.notifyMsgWaiting(exchange);
                                }
                            }
                        })

                    .otherwise()
                        // everything OK => mark processing as successful
                        .bean(MessageService.BEAN, "setStateOk")

                        .process(new Processor() {
                            @Override
                            public void process(Exchange exchange) throws Exception {
                                AsynchEventHelper.notifyMsgCompleted(exchange);
                            }
                        })
                        .bean(ROUTE_BEAN, "notifyCompletedGuaranteedOrderMsg")

                        .to(AsynchConstants.URI_POST_PROCESS_AFTER_OK)
                    .end()
                .end();

        // route for error handling
        from(URI_ERROR_HANDLING)
            .routeId(ROUTE_ID_ASYNCH_ERROR_HANDLING)

            .onException(Exception.class)
                .handled(true)
                .log(LoggingLevel.ERROR, "Error while handling error: ${exception.stacktrace}")
            .end()

            .validate(exchangeProperty(Exchange.EXCEPTION_CAUGHT).isNotNull())

            .log(LoggingLevel.WARN,
                    "Error occurred during route processing: ${property." + Exchange.EXCEPTION_CAUGHT + "}")

            .to("log:" + AsynchMessageRoute.class.getPackage().getName()
                    + "?level=WARN&showCaughtException=true&showStackTrace=true&multiline=true")

            .choice()
                // note: I don't know why but the same version with simple and spel language doesn't work
                // .when(simple("${header[" + MSG_HEADER + "].failedCount} == " + countPartlyFailsBeforeFailed))
                // .when().spel("#{request.headers['" + MSG_HEADER + "'].failedCount} >= " + countPartlyFailsBeforeFailed)

                .when().method(ROUTE_BEAN, "checkMessageFailed")
                    .to(URI_ERROR_FATAL)

                .otherwise()
                    // => mark as PARTLY FAILED
                    .bean(MessageService.BEAN, "setStatePartlyFailed")

                    .process(new Processor() {
                        @Override
                        public void process(Exchange exchange) throws Exception {
                            AsynchEventHelper.notifyMsgPartlyFailed(exchange);
                        }
                    })
            .end()

            // stop next processing - update message state and stop
            .stop();

        // route for FATAL result
        from(URI_ERROR_FATAL)
            .routeId(ROUTE_ID_ERROR_FATAL)

            .onException(Exception.class)
                .handled(true)
                .log(LoggingLevel.ERROR, "Error while handling error: ${exception.stacktrace}")
            .end()

            // => completely FAILED
            .bean(MessageService.BEAN, "setStateFailed")

            .process(new Processor() {
                @Override
                public void process(Exchange exchange) throws Exception {
                    AsynchEventHelper.notifyMsgFailed(exchange);
                }
            })

            .to(AsynchConstants.URI_POST_PROCESS_AFTER_FAILED)
            // stop next processing - update message state and stop
            .stop();

        from(AsynchConstants.URI_POST_PROCESS_AFTER_OK)
            .routeId(ROUTE_ID_POST_PROCESS_AFTER_OK)
            .validate(header(MSG_HEADER).isNotNull())
            .to(AsynchConstants.URI_CONFIRM_MESSAGE);

        from(AsynchConstants.URI_POST_PROCESS_AFTER_FAILED)
            .routeId(ROUTE_ID_POST_PROCESS_AFTER_FAILED)
            .validate(header(MSG_HEADER).isNotNull())
            .to(AsynchConstants.URI_CONFIRM_MESSAGE)
            .bean(ROUTE_BEAN, "sendMailToAdmin").id("sendEmail");

        // confirmation route
        from(AsynchConstants.URI_CONFIRM_MESSAGE)
            .routeId(ROUTE_ID_CONFIRM_MESSAGE)

            .onException(Exception.class)
                .handled(true)
                .log(LoggingLevel.ERROR, "exception during confirmation caught "
                        + "- '${property." + Exchange.EXCEPTION_CAUGHT + ".message}'")
                .choice()
                    .when(body().isInstanceOf(ExternalCall.class))
                        // existing confirmation external call - just update it to failed state
                        .bean(ConfirmationService.BEAN, "confirmationFailed")
                    .otherwise()
                        // no existing confirmation external call - record a new one with failed state
                        .bean(ConfirmationService.BEAN, "insertFailedConfirmation")
                .end()
            .end()

            .choice()
                .when(header(MSG_HEADER).isNull())
                    // confirmation route can be called from scheduler => load message
                    .validate(body().isInstanceOf(ExternalCall.class))
                    .setHeader(MSG_HEADER).mvel("request.body.message")
                .endChoice()
            .end()

            // note: if there it's child message then it's without confirmation (need to do it)
            .bean(ConfirmationCallback.BEAN, "confirm")

            .filter(body().isInstanceOf(ExternalCall.class))
                // for successful confirmations only record if it's a repeating attempt
                .bean(ConfirmationService.BEAN, "confirmationComplete")
            .end();
    }

    /**
     * Set log context parameters.
     *
     * @param message the message
     * @param requestId the request ID
     * @see LogContextHelper#setLogContextParams(Message, String)
     */
    @Handler
    public void setLogContextParams(@Body Message message,
            @Header(LogContextFilter.CTX_REQUEST_ID) @Nullable String requestId) {
        LogContextHelper.setLogContextParams(message, requestId);
    }

    /**
     * Checks if current message wasn't converted to other state.
     * It can happen when message is long time in queue that repairing process converts message back
     * to PARTLY_FAILED state and evenly message can start with duplicate processing.
     *
     * @param msg the message
     * @return {@code true} when message is in wrong state {@code false} otherwise
     */
    @Handler
    public boolean isMessageObsolete(@Body Message msg) {
        Assert.notNull(msg, "the msg must not be null");
        MessageService messageService = getBean(MessageService.class);

        return !messageService.setStateProcessingForLock(msg);
    }

    @Handler
    public void logStartProcessing(@Body Message msg,
            @Nullable @Header(AsynchConstants.MSG_QUEUE_INSERT_HEADER) Long msgInsertTime) {

        LOG.debug("Starts processing of the message {}, waited in queue for {} ms", msg.toHumanString(),
                msgInsertTime != null ? (System.currentTimeMillis() - msgInsertTime) : "-");
    }

    /**
     * Sets {@link AsynchConstants#OBJECT_ID_HEADER} and {@link AsynchConstants#ENTITY_TYPE_HEADER}
     * headers if there are available corresponding values in message.
     *
     * @param msg the message
     * @param headers the headers
     */
    @Handler
    public void setEntityInfo(@Body Message msg, @Headers Map<String, Object> headers) {
        Assert.notNull(msg, "the msg must not be null");

        if (msg.getObjectId() != null) {
            headers.put(OBJECT_ID_HEADER, msg.getObjectId());
        }
        if (msg.getEntityType() != null) {
            headers.put(ENTITY_TYPE_HEADER, msg.getEntityType());
        }
    }

    /**
     * Returns {@code true} if failed count exceeds limit for failing.
     *
     * @param msg the message
     * @param ex  error in processing {@link Message}, {@code NULL} - no error
     * @return {@code true} when limit was exceeded, otherwise {@code false}
     */
    @Handler
    public boolean checkMessageFailed(@Header(MSG_HEADER) Message msg, @Nullable Exception ex) {
        Assert.notNull(msg, "the msg must not be null");

        boolean result = msg.getFailedCount() >= countPartlyFailsBeforeFailed.getValue();
        if (!result && ex != null && ExceptionUtils.indexOfThrowable(ex, StoppingException.class) >= 0) {
            LOG.warn("ESB not processing existing message. Message " + ex.getMessage()
                    + " is changed to failed state.");
            result = true;
        }
        return result;
    }

    @Handler
    public boolean checkParentMessage(@Header(MSG_HEADER) Message msg) {
        Assert.notNull(msg, "the msg must not be null");

        return msg.isParentMessage();
    }

    /**
     * Sends notification mail to admin(s).
     *
     * @param msg as context of process
     */
    @Handler
    public void sendMailToAdmin(@Header(MSG_HEADER) Message msg) {
        Assert.notNull(msg, "the msg must not be null");

        EmailService emailService = lookup(EmailService.BEAN, EmailService.class);

        String body = "The following message " + msg.toHumanString() + " FAILED.\n\nBody:\n" + msg.getEnvelope();

        emailService.sendEmailToAdmins("Notification about FAILED message", body);
   }

    /**
     * Gets URI of the next route.
     * The URI is in the following format: "direct:SERVICE_operationName{@link AbstractBasicRoute#OUT_ROUTE_SUFFIX}"
     *
     * @param msg the message
     * @return URI of next route
     */
    @Handler
    public String nextRoute(@Header(MSG_HEADER) Message msg) {
        Assert.notNull(msg, "the msg must not be null");

        return "direct:" + msg.getService().getServiceName() + "_" + msg.getOperationName() + OUT_ROUTE_SUFFIX;
    }

    /**
     * Change state of message into {@link MsgStateEnum#IN_QUEUE}.
     *
     * @param msg message in which will be changed state
     * @throws LockFailureException if change state into {@link MsgStateEnum#IN_QUEUE} fails
     */
    @Handler
    public void changeStateMessageToInQueue(@Body Message msg) throws LockFailureException {
        Assert.notNull(msg, "msg must not be null");

        LOG.debug("Change state of message '{}' into '{}.'", msg.toHumanString(), MsgStateEnum.IN_QUEUE);

        if (!getBean(MessageService.class).setStateInQueueForLock(msg)) {
            throw new LockFailureException("Failed to lock message for change state to '" + MsgStateEnum.IN_QUEUE
                    + "': " + msg.toHumanString());
        }
    }

    /**
     * Checks if actual node handles existing message.
     *
     * @throws StoppingException if node not handles existing message
     */
    @Handler
    public void isAbleToHandleExistingMessage() throws StoppingException {
        NodeService nodeService = getApplicationContext().getBean(NodeService.class);

        if (!nodeService.getActualNode().isAbleToHandleExistingMessages()) {
            throw new StoppingException("ESB has been stopped...");
        }
    }

    /**
     * Sends notifications event when message in guaranteed order completes successfully
     *
     * @param msg message which is completed
     * @param exchange exchange of completed message
     */
    @Handler
    public void notifyCompletedGuaranteedOrderMsg(@Header(MSG_HEADER) Message msg, Exchange exchange) {
        Assert.notNull(msg, "the msg must not be null");

        if (msg.isGuaranteedOrder()) {
            AsynchEventHelper.notifyGuaranteedOrderMsgCompleted(exchange);
        }
    }
}


text:
package org.tud.inf.st.mbt.emf.graphicaleditor.focus;

import java.util.Collection;

public interface IFocusableListener {
	void focus(Collection<Object> on);
}

redpajama_set_name: RedPajamaGithub


text:
define(["exports", "module"], function (exports, module) {
    "use strict";

    module.exports = function () {
        return function (max, input) {
            return Math.max(max, input);
        };
    };

    ;
});


text:
package org.jadira.usertype.dateandtime.shared.dbunit;

import java.io.IOException;

import org.dbunit.DatabaseUnitException;

public class RuntimeDatabaseUnitException extends RuntimeException {

    private static final long serialVersionUID = -7283266706065074477L;

    public RuntimeDatabaseUnitException(DatabaseUnitException e) {
        super(e.getMessage(), e);
    }

    public RuntimeDatabaseUnitException(IOException e) {
        super(e.getMessage(), e);
    }
}


text:
{% extends "base.html" %}
{% block sideBarContent %}

{{ neues_fenster|safe }}

{{ input_error_message|safe }}

<form action="/schluesselerzeugen" method="post" accept-charset="utf-8">
<input type="hidden" name="mobile" value="{{ mobile|safe }}">

<input name="keyname" type="text" size="25" maxlength="25">

<input type="submit" value="create new keypair">

</form>

{{ new_keypair_secretkey_download_link|safe }}

{{ new_keypair_secretkey|safe }}

Your keypairs

{{ keytabelle|safe }}

{{ secretkey_memcache|safe }}

{% endblock %}


text:
'use strict';

// Declare app level module which depends on views, and components
angular.module('myApp', [
  'ngRoute',
  'myApp.view1',
  'myApp.view2',
  'myApp.version'
]).
config(['$routeProvider', '$locationProvider', '$sceProvider', 'tplProvider', function ($routeProvider, $locationProvider, $sceProvider, tplProvider) {
    $routeProvider.when('/customerImage', { templateUrl: 'welcome.html' })
        .otherwise({ redirectTo: 'index.html' });

    $locationProvider.html5Mode(true);
}]);


text:
package code

import (
	"strings"

	"github.com/jcelliott/lumber"
	"github.com/nanobox-io/golang-docker-client"

	container_generator "github.com/nanobox-io/nanobox/generators/containers"
	"github.com/nanobox-io/nanobox/generators/hooks/build"
	"github.com/nanobox-io/nanobox/models"
	"github.com/nanobox-io/nanobox/processors/provider"
	"github.com/nanobox-io/nanobox/util"
	"github.com/nanobox-io/nanobox/util/display"
	"github.com/nanobox-io/nanobox/util/hookit"
)

// Publish ...
func Publish(envModel *models.Env, WarehouseConfig WarehouseConfig) error {
	display.OpenContext("Deploying app")
	defer display.CloseContext()

	// initialize the docker client
	// init docker client
	if err := provider.Init(); err != nil {
		return util.ErrorAppend(err, "failed to init docker client")
	}

	// pull the latest build image
	buildImage, err := pullBuildImage()
	if err != nil {
		return util.ErrorAppend(err, "failed to pull the build image")
	}

	display.StartTask("Starting docker container")

	// if a publish container was leftover from a previous publish, let's remove it
	docker.ContainerRemove(container_generator.PublishName())

	// start the container
	config := container_generator.PublishConfig(buildImage)
	container, err := docker.CreateContainer(config)
	if err != nil {
		lumber.Error("code:Build:docker.CreateContainer(%+v): %s", config, err.Error())
		display.ErrorTask()
		return util.ErrorAppend(err, "failed to start docker container")
	}
	// ensure we stop the container when we're done
	defer docker.ContainerRemove(container.ID)

	display.StopTask()

	lumber.Prefix("code:Publish")
	defer lumber.Prefix("")

	display.StartTask("Uploading")

	// run user hook
	// TODO: display output from hooks
	payload := build.UserPayload()
	// todo: should this be if payload == ""
	if err != nil {
		lumber.Error("code:Publish:build.UserPayload()")
		return util.ErrorAppend(err, "unable to retrieve user payload")
	}
	if out, err := hookit.DebugExec(container.ID, "user", payload, "info"); err != nil {
		// handle 'exec failed: argument list too long' error
		if strings.Contains(out, "argument list too long") {
			if err2, ok := err.(util.Err); ok {
				err2.Suggest = "You may have too many ssh keys, please specify the one you need with `nanobox config set ssh-key ~/.ssh/id_rsa`"
				err2.Output = out
				err2.Code = "1001"
				return util.ErrorAppend(err2, "failed to run the (publish)user hook")
			}
		}
		return util.ErrorAppend(err, "failed to run the (publish)user hook")
	}

	buildWarehouseConfig := build.WarehouseConfig{
		BuildID:        WarehouseConfig.BuildID,
		WarehouseURL:   WarehouseConfig.WarehouseURL,
		WarehouseToken: WarehouseConfig.WarehouseToken,
		PreviousBuild:  WarehouseConfig.PreviousBuild,
	}

	payload = build.PublishPayload(envModel, buildWarehouseConfig)
	if err != nil {
		lumber.Error("code:Publish:build.UserPayload()")
		display.ErrorTask()
		return util.ErrorAppend(err, "unable to retrieve user payload")
	}
	if out, err := hookit.DebugExec(container.ID, "publish", payload, "info"); err != nil {
		if err2, ok := err.(util.Err); ok {
			err2.Output = out
			return util.ErrorAppend(err2, "failed to run the (publish)publish hook")
		}
		return util.ErrorAppend(err, "failed to run the (publish)publish hook")
	}

	display.StopTask()

	return nil
}


text:
class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
  before_action :authenticate_user!

  def permit_if_admin
    redirect_to root_path unless current_user.admin?
  end
end


text:
#ifndef TARANTOOL_LIB_BITSET_BITSET_H_INCLUDED
#define TARANTOOL_LIB_BITSET_BITSET_H_INCLUDED

/**
 * @file
 * @brief Module to work with arrays of bits (bitsets)
 *
 * Bitset is an array of bits where each bit can be set or unset
 * independently.  The bits of a @link bitset @endlink are indexed
 * by \a size_t position number.  Initially all bits are set to
 * false. You can use any values in range [0,SIZE_MAX).  The
 * container grows automatically.
 */

#include "bit/bit.h"

#include <stddef.h>
#include <stdint.h>
#include <stdbool.h>
#include <limits.h>
#if defined(DEBUG)
#include <stdio.h> /* for dumping debug output to FILE */
#endif /* defined(DEBUG) */

/** @cond false */
#define RB_COMPACT 1
#include <third_party/rb.h>
/** @endcond */

#if defined(__cplusplus)
extern "C" {
#endif /* defined(__cplusplus) */

/** @cond false */
struct bitset_page {
	size_t first_pos;
	rb_node(struct bitset_page) node;
	size_t cardinality;
	uint8_t data[0];
};

typedef rb_tree(struct bitset_page) bitset_pages_t;
/** @endcond */

/**
 * Bitset
 */
struct bitset {
	/** @cond false */
	bitset_pages_t pages;
	size_t cardinality;
	void *(*realloc)(void *ptr, size_t size);
	/** @endcond */
};

/**
 * @brief Construct \a bitset
 * @param bitset bitset
 * @param realloc memory allocator to use
 */
void
bitset_create(struct bitset *bitset, void *(*realloc)(void *ptr, size_t size));

/**
 * @brief Destruct \a bitset
 * @param bitset bitset
 */
void
bitset_destroy(struct bitset *bitset);

/**
 * @brief Test bit \a pos in \a bitset
 * @param bitset bitset
 * @param pos bit number
 * @retval true if \a pos is set in \a bitset
 * @retval false if \a pos is not set in \a bitset
 */
bool
bitset_test(struct bitset *bitset, size_t pos);

/**
 * @brief Set bit \a pos in \a bitset
 * @param bitset bitset
 * @param pos bit number
 * @retval 1 on success if previous value of \a pos was true
 * @retval 0 on success if previous value of \a pos was false
 * @retval -1 on memory error
 */
int
bitset_set(struct bitset *bitset, size_t pos);

/**
 * @brief Clear bit \a pos in \a bitset
 * @param bitset bitset
 * @param pos bit number
 * @retval 1 on success if previous value of \a pos was true
 * @retval 0 on success if previous value of \a pos was false
 * @retval -1 on memory error
 */
int
bitset_clear(struct bitset *bitset, size_t pos);

/**
 * @brief Return the number of bits set to \a true in \a bitset.
 * @param bitset bitset
 * @return returns the number of bits set to \a true in \a bitset.
 */
inline size_t
bitset_cardinality(const struct bitset *bitset) {
	return bitset->cardinality;
}

/**
 * @brief Bitset Information structure
 * @see bitset_info
 */
struct bitset_info {
	/** Number of allocated pages */
	size_t pages;
	/** Data (payload) size of one page (in bytes) */
	size_t page_data_size;
	/** Full size of one page (in bytes, including padding and tree data) */
	size_t page_total_size;
	/** A multiplier by which an address of page data is aligned **/
	size_t page_data_alignment;
};

/**
 * @brief Fill information about \a bitset
 * @param bitset bitset
 * @param stat structure to fill
 */
void
bitset_info(struct bitset *bitset, struct bitset_info *info);

#if defined(DEBUG)
void
bitset_dump(struct bitset *bitset, int verbose, FILE *stream);
#endif /* defined(DEBUG) */

#if defined(__cplusplus)
} /* extern "C" */
#endif /* defined(__cplusplus) */

#endif /* TARANTOOL_LIB_BITSET_BITSET_H_INCLUDED */


text:
FROM alpine
MAINTAINER Christian Gatzlaff "cgatzlaff@gmail.com"

RUN apk add --no-cache rsync bash

ENV RSYNC_TIMEOUT 300
ENV RSYNC_MAX_CONNECTIONS 10
ENV RSYNC_PORT 873
ENV VOL /vol

EXPOSE ${RSYNC_PORT}

COPY server.sh /server.sh
RUN chmod 755 /server.sh && \
    mkdir ${VOL} && \
    chmod 755 ${VOL}

VOLUME ${VOL}

ENTRYPOINT ["/server.sh"]


text:
package org.apache.gearpump.examples.kafka_hbase_pipeline

import com.typesafe.config.ConfigFactory
import org.apache.gearpump.cluster.UserConfig
import org.apache.gearpump.cluster.client.ClientContext
import org.apache.gearpump.cluster.main.{ArgumentsParser, CLIOption, ParseResult}
import org.apache.gearpump.streaming.kafka.{KafkaSource, KafkaStorageFactory}
import org.apache.gearpump.streaming.source.DataSourceProcessor
import org.apache.gearpump.streaming.{Processor, StreamApplication}
import org.apache.gearpump.util.Graph._
import org.apache.gearpump.util.{Graph, LogUtil}
import org.slf4j.Logger

object PipeLine extends App with ArgumentsParser {
  private val LOG: Logger = LogUtil.getLogger(getClass)
  val PROCESSORS = "pipeline.processors"
  val PERSISTORS = "pipeline.persistors"

  override val options: Array[(String, CLIOption[Any])] = Array(
    "processors"-> CLIOption[Int]("<processor number>", required = false, defaultValue = Some(1)),
    "persistors"-> CLIOption[Int]("<persistor number>", required = false, defaultValue = Some(1)),
    "topic" -> CLIOption[String]("<topic>", required = false, defaultValue = Some("gptest")),
    "brokers" -> CLIOption[String]("<brokers>", required = false, defaultValue = Some("10.10.10.46:9092,10.10.10.164:9092,10.10.10.236:9092")),
    "zookeepers" -> CLIOption[String]("<zookeepers>", required = false, defaultValue = Some("10.10.10.46:2181,10.10.10.236:2181,10.10.10.164:2181/kafka"))
  )

  def application(config: ParseResult): StreamApplication = {
    import Messages._
    val pipelineString =
      """
        |pipeline {
        |  cpu.interval = 20
        |  memory.interval = 20
        |  processors = 1
        |  persistors = 1
        |}
        |hbase {
        |  table {
        |    name = "pipeline"
        |    column {
        |      family = "metrics"
        |      name = "average"
        |    }
        |  }
        |}
      """.stripMargin
    val pipelineConfig = PipeLineConfig(ConfigFactory.parseFile(new java.io.File(pipelineString)))
    val processors = config.getInt("processors")
    val persistors = config.getInt("persistors")
    val topic = config.getString("topic")
    val brokers = config.getString("brokers")
    val zookeepers = config.getString("zookeepers")

    val appConfig = UserConfig.empty.withValue[PipeLineConfig](PIPELINE, pipelineConfig)

    val offsetStorageFactory = new KafkaStorageFactory(zookeepers, brokers)
    val source = new KafkaSource(topic, zookeepers, offsetStorageFactory)
    val kafka = DataSourceProcessor(source, 1)
    val cpuProcessor = Processor[CpuProcessor](processors, "CpuProcessor")
    val memoryProcessor = Processor[MemoryProcessor](processors, "MemoryProcessor")
    val cpuPersistor = Processor[CpuPersistor](persistors, "CpuPersistor")
    val memoryPersistor = Processor[MemoryPersistor](persistors, "MemoryPersistor")
    val app = StreamApplication("KafkaHbasePipeLine", Graph(
      kafka ~> cpuProcessor ~> cpuPersistor,
      kafka ~> memoryProcessor ~> memoryPersistor
    ), appConfig)
    app
  }

  val config = parse(args)
  val context = ClientContext()
  implicit val system = context.system
  val appId = context.submit(application(config))
  context.close()

}


text:
namespace Cake.Web.Docs.Reflection
{
    /// <summary>
    /// Represents a type classification.
    /// </summary>
    public enum TypeClassification
    {
        /// <summary>
        /// Represents an unknown classification.
        /// </summary>
        Unknown = 0,

        /// <summary>
        /// Represents a struct.
        /// </summary>
        Struct,

        /// <summary>
        /// Represents a class.
        /// </summary>
        Class,

        /// <summary>
        /// Represents an interface.
        /// </summary>
        Interface,

        /// <summary>
        /// Represents an enum.
        /// </summary>
        Enum
    }
}


text:
ACCEPTED

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

#### Published in
null

#### Original name
Montamans panamensis Dwyer

### Remarks
null


text:
package com.github.mitchjmac.extinction.locations;

interface Residence {

}


text:
extern void emxEnsureCapacity(emxArray__common *emxArray, int oldNumel, int
  elementSize);
extern void emxFree_boolean_T(emxArray_boolean_T **pEmxArray);
extern void emxFree_int32_T(emxArray_int32_T **pEmxArray);
extern void emxFree_real_T(emxArray_real_T **pEmxArray);
extern void emxInit_boolean_T(emxArray_boolean_T **pEmxArray, int numDimensions);
extern void emxInit_int32_T(emxArray_int32_T **pEmxArray, int numDimensions);
extern void emxInit_int32_T1(emxArray_int32_T **pEmxArray, int numDimensions);
extern void emxInit_real_T(emxArray_real_T **pEmxArray, int numDimensions);
extern void emxInit_real_T1(emxArray_real_T **pEmxArray, int numDimensions);

#endif

//
// File trailer for artificial_pancreas_emxutil.h
//
// [EOF]
//


text:
<?php
namespace ThreeSeventyApi\Helpers;

/* Helper to construct url for request. */
class Url {
    public function url_ ($args = array()){
        global $account_id;

        foreach($args as $key => $arg){
            if($key == 0){
                $base_path = "/account/{$account_id}/{$arg}";
            } else {
                $base_path .= "/{$arg}";
            }
        }
        return print_r($base_path, true);
    }
}


text:
require 'rails_helper'

describe ThumbnailHelper do
  subject { helper }

  before do
    allow(subject).to receive(:thumbnail_url).and_return('thumbnail.jpg')
  end

  context 'when document is a geo FileSet' do
    let(:file_set) { FactoryGirl.create(:file_set, geo_mime_type: 'application/vnd.geo+json') }
    let(:document) do
      FileSetPresenter.new(
        SolrDocument.new(
          file_set.to_solr
        ), nil
      )
    end

    it 'returns a path to the thumbnail image' do
      expect(subject).to receive(:link_to_document).with(document, /<img src=\"\/images\/thumbnail.jpg/)
      subject.plum_thumbnail_path(document)
    end
  end

  context 'when document is a VectorWork' do
    let(:vector_work) { FactoryGirl.create(:vector_work) }
    let(:document) do
      GeoWorks::VectorWorkShowPresenter.new(
        SolrDocument.new(
          vector_work.to_solr
        ), nil
      )
    end

    it 'returns a path to the thumbnail image' do
      expect(subject).to receive(:link_to_document).with(document, /<img src=\"\/images\/thumbnail.jpg/)
      subject.plum_thumbnail_path(document)
    end
  end

  context 'when document is a ScannedResource' do
    let(:scanned_resource) { FactoryGirl.create(:scanned_resource) }
    let(:document) do
      ScannedResourceShowPresenter.new(
        SolrDocument.new(
          scanned_resource.to_solr
        ), nil
      )
    end

    before do
      allow(document).to receive(:thumbnail_id).and_return('abcdefg')
    end

    it 'returns a path to the iiif thumbnail' do
      expect(subject).to receive(:link_to_document).with(document, /ab%2Fcd%2Fef%2Fg-intermediate_file.jp2/)
      subject.plum_thumbnail_path(document)
    end
  end

  context 'when document is a MapSet' do
    let(:map_set) { FactoryGirl.create(:map_set) }
    let(:document) do
      MapSetShowPresenter.new(
        SolrDocument.new(
          map_set.to_solr
        ), nil
      )
    end

    it 'returns a path to the thumbnail image' do
      expect(subject).to receive(:link_to_document).with(document, /<img src=\"\/images\/thumbnail.jpg/)
      subject.plum_thumbnail_path(document)
    end
  end
end


text:
// key: compiler.err.types.incompatible.unrelated.defaults

class TypesIncompatibleUnrelatedDefaults {
    interface A {
        default void m() { }
    }

    interface B {
        default void m() { }
    }

    interface AB extends A, B { }
}


text:
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Chatbots on // inspire, create, hack, enjoy</title>
    <link>http://kslhacks.com/tags/chatbots/</link>
    <description>Recent content in Chatbots on // inspire, create, hack, enjoy</description>
    <generator>Hugo -- gohugo.io</generator>
    <language>en-us</language>
    <lastBuildDate>Mon, 06 Nov 2017 00:00:00 +0000</lastBuildDate>

	<atom:link href="http://kslhacks.com/tags/chatbots/index.xml" rel="self" type="application/rss+xml" />

    <item>
      <title>Botbuilder middleware package for custom analytics and telemetry</title>
      <link>http://kslhacks.com/2017/11/botbuilder-middleware-package-for-custom-analytics-and-telemetry/</link>
      <pubDate>Mon, 06 Nov 2017 00:00:00 +0000</pubDate>

      <guid>http://kslhacks.com/2017/11/botbuilder-middleware-package-for-custom-analytics-and-telemetry/</guid>
      <description>
Microsoft Botbuilder telemetry package for analytics.
</description>
    </item>

    <item>
      <title>Chatbots: Button Dialogs</title>
      <link>http://kslhacks.com/2017/05/chatbots-button-dialogs/</link>
      <pubDate>Tue, 30 May 2017 00:00:00 +0000</pubDate>

      <guid>http://kslhacks.com/2017/05/chatbots-button-dialogs/</guid>
      <description>
Quick steps to start new dialogs with a click of a button. Demo with code provided. Take your chatbot to the next level!
</description>
    </item>

  </channel>
</rss>


text:
import json

from django.core.exceptions import ValidationError
from django.core import serializers
from django.forms.models import modelform_factory
from django.views.generic import FormView

from djangular.views.mixins import JSONBaseMixin, JSONResponseException

class NgMissingParameterError(ValueError):
    pass

class NgCRUDView(JSONBaseMixin, FormView):
    """
    Basic view to support default angular $resource CRUD actions on server side
    Subclass and override ``model`` with your model

    Optional 'pk' GET parameter must be passed when object identification is required (save to update and delete)

    If fields != None the serialized data will only contain field names from fields array
    """
    model = None
    fields = None
    form_class = None
    slug_field = 'slug'
    serializer_name = 'python'
    serialize_natural_keys = False

    allowed_methods = ['GET', 'POST', 'DELETE']
    exclude_methods = []

    def get_allowed_methods(self):
        return [method for method in self.allowed_methods if method not in self.exclude_methods]

    def dispatch(self, request, *args, **kwargs):
        """
        Override dispatch to call appropriate methods:
        * $query - ng_query
        * $get - ng_get
        * $save - ng_save
        * $delete and $remove - ng_delete
        """
        allowed_methods = self.get_allowed_methods()
        try:
            if request.method == 'GET' and 'GET' in allowed_methods:
                if 'pk' in request.GET or self.slug_field in request.GET:
                    return self.ng_get(request, *args, **kwargs)
                return self.ng_query(request, *args, **kwargs)
            elif request.method == 'POST' and 'POST' in allowed_methods:
                return self.ng_save(request, *args, **kwargs)
            elif request.method == 'DELETE' and 'DELETE' in allowed_methods:
                return self.ng_delete(request, *args, **kwargs)
        except self.model.DoesNotExist as e:
            return self.error_json_response(e.args[0], 404)
        except NgMissingParameterError as e:
            return self.error_json_response(e.args[0])
        except JSONResponseException as e:
            return self.error_json_response(e.args[0], e.status_code)
        except ValidationError as e:
            if hasattr(e, 'error_dict'):
                return self.error_json_response('Form not valid', detail=e.message_dict)
            else:
                return self.error_json_response(e.message)

        return self.error_json_response('This view can not handle method {0}'.format(request.method), 405)

    def get_form_class(self):
        """
        Build ModelForm from model
        """
        return self.form_class or modelform_factory(self.model, exclude=[])

    def build_json_response(self, data, **kwargs):
        return self.json_response(self.serialize_queryset(data), separators=(',', ':'), **kwargs)

    def error_json_response(self, message, status_code=400, detail=None):
        response_data = {
            "message": message,
            "detail": detail,
        }
        return self.json_response(response_data, status=status_code, separators=(',', ':'))

    def serialize_queryset(self, queryset):
        """
        Return serialized queryset or single object as python dictionary
        serialize() only works on iterables, so to serialize a single object we put it in a list
        """
        object_data = []
        is_queryset = False
        query_fields = self.get_fields()
        try:
            iter(queryset)
            is_queryset = True
            raw_data = serializers.serialize(self.serializer_name, queryset, fields=query_fields,
                                             use_natural_keys=self.serialize_natural_keys)
        except TypeError:  # Not iterable
            raw_data = serializers.serialize(self.serializer_name, [queryset, ], fields=query_fields,
                                             use_natural_keys=self.serialize_natural_keys)

        for obj in raw_data:  # Add pk to fields
            obj['fields']['pk'] = obj['pk']
            object_data.append(obj['fields'])

        if is_queryset:
            return object_data
        return object_data[0]  # If there's only one object

    def get_form_kwargs(self):
        kwargs = super(NgCRUDView, self).get_form_kwargs()
        # Since angular sends data in JSON rather than as POST parameters, the default data (request.POST)
        # is replaced with request.body that contains JSON encoded data
        kwargs['data'] = json.loads(self.request.body.decode('utf-8'))

        # Add instance if object identifier present
        if 'pk' in self.request.GET or self.slug_field in self.request.GET:
            kwargs['instance'] = self.get_object()
        return kwargs

    def get_object(self):
        if 'pk' in self.request.GET:
            return self.model.objects.get(pk=self.request.GET['pk'])
        elif self.slug_field in self.request.GET:
            return self.model.objects.get(**{self.slug_field: self.request.GET[self.slug_field]})
        raise NgMissingParameterError(
            "Attempted to get an object by 'pk' or slug field, but no identifier is present. Missing GET parameter?")

    def get_fields(self):
        """
        Get fields to return from a query.
        Can be overridden (e.g. to use a query parameter).
        """
        return self.fields

    def get_queryset(self):
        """
        Get query to use in ng_query
        Allows for easier overriding
        """
        return self.model.objects.all()

    def ng_query(self, request, *args, **kwargs):
        """
        Used when angular's query() method is called
        Build an array of all objects, return json response
        """
        return self.build_json_response(self.get_queryset())

    def ng_get(self, request, *args, **kwargs):
        """
        Used when angular's get() method is called
        Returns a JSON response of a single object dictionary
        """
        return self.build_json_response(self.get_object())

    def ng_save(self, request, *args, **kwargs):
        """
        Called on $save()
        Use modelform to save new object or modify an existing one
        """
        form = self.get_form(self.get_form_class())
        if form.is_valid():
            obj = form.save()
            return self.build_json_response(obj)

        raise ValidationError(form.errors)

    def ng_delete(self, request, *args, **kwargs):
        """
        Delete object and return it's data in JSON encoding
        The response is build before the object is actually deleted
        so that we can still retrieve a serialization in the response
        even with a m2m relationship
        """
        if 'pk' not in request.GET:
            raise NgMissingParameterError("Object id is required to delete.")

        obj = self.get_object()
        response = self.build_json_response(obj)
        obj.delete()
        return response


text:
.. aiohttp documentation master file, created by
   sphinx-quickstart on Wed Mar  5 12:35:35 2014.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

aiohttp
=======

HTTP client/server for :term:`asyncio` (:pep:`3156`).

.. _GitHub: https://github.com/KeepSafe/aiohttp
.. _Freenode: http://freenode.net

Features
--------

- Supports both :ref:`aiohttp-client` and :ref:`HTTP Server <aiohttp-web>`.
- Supports both :ref:`Server WebSockets <aiohttp-web-websockets>` and
  :ref:`Client WebSockets <aiohttp-client-websockets>` out-of-the-box.
- Web-server has :ref:`aiohttp-web-middlewares`,
  :ref:`aiohttp-web-signals` and pluggable routing.

Library Installation
--------------------

.. code-block:: bash

   $ pip install aiohttp

You may want to install *optional* :term:`cchardet` library as faster
replacement for :term:`chardet`:

.. code-block:: bash

   $ pip install cchardet

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

Client example::

    import aiohttp
    import asyncio

    async def fetch(session, url):
        with aiohttp.Timeout(10):
            async with session.get(url) as response:
                return await response.text()

    async def main(loop):
        async with aiohttp.ClientSession(loop=loop) as session:
            html = await fetch(session, 'http://python.org')
            print(html)

    loop = asyncio.get_event_loop()
    loop.run_until_complete(main(loop))

Server example::

    from aiohttp import web

    async def handle(request):
        name = request.match_info.get('name', "Anonymous")
        text = "Hello, " + name
        return web.Response(body=text.encode('utf-8'))

    app = web.Application()
    app.router.add_get('/{name}', handle)

    web.run_app(app)

.. note::

   Throughout this documentation, examples utilize the `async/await` syntax
   introduced by :pep:`492` that is only valid for Python 3.5+.

   If you are using Python 3.4, please replace ``await`` with
   ``yield from`` and ``async def`` with a ``@coroutine`` decorator.
   For example, this::

       async def coro(...):
           ret = await f()

   should be replaced by::

       @asyncio.coroutine
       def coro(...):
           ret = yield from f()

Tutorial
--------

:ref:`Polls tutorial <aiohttp-tutorial>`

Source code
-----------

The project is hosted on GitHub_

Please feel free to file an issue on the `bug tracker
<https://github.com/KeepSafe/aiohttp/issues>`_ if you have found a bug
or have some suggestion in order to improve the library.

The library uses `Travis <https://travis-ci.org/KeepSafe/aiohttp>`_ for
Continuous Integration.

Dependencies
------------

- Python Python 3.4.1+
- *chardet* library
- *multidict* library
- *Optional* :term:`cchardet` library as faster replacement for
  :term:`chardet`.

  Install it explicitly via:

  .. code-block:: bash

     $ pip install cchardet

Discussion list
---------------

*aio-libs* google group: https://groups.google.com/forum/#!forum/aio-libs

Feel free to post your questions and ideas here.

Contributing
------------

Please read the :ref:`instructions for contributors<aiohttp-contributing>`
before making a Pull Request.

Authors and License
-------------------

The ``aiohttp`` package is written mostly by Nikolay Kim and Andrew Svetlov.

It's *Apache 2* licensed and freely available.

Feel free to improve this package and send a pull request to GitHub_.

Contents
--------

.. toctree::

   client
   client_reference
   tutorial
   web
   web_reference
   abc
   server
   multipart
   api
   logging
   testing
   gunicorn
   faq
   new_router
   contributing
   changes
   glossary

Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`

.. disqus::


text:
#include "intel_context.h"
#include "intel_buffers.h"
#include "intel_fbo.h"
#include "intel_mipmap_tree.h"

#include "main/fbobject.h"
#include "main/framebuffer.h"
#include "main/renderbuffer.h"

/**
 * Check if we're about to draw into the front color buffer.
 * If so, set the intel->front_buffer_dirty field to true.
 */
void
intel_check_front_buffer_rendering(struct intel_context *intel)
{
   const struct gl_framebuffer *fb = intel->ctx.DrawBuffer;
   if (_mesa_is_winsys_fbo(fb)) {
      /* drawing to window system buffer */
      if (fb->_NumColorDrawBuffers > 0) {
         if (fb->_ColorDrawBufferIndexes[0] == BUFFER_FRONT_LEFT) {
	    intel->front_buffer_dirty = true;
	 }
      }
   }
}

static void
intelDrawBuffer(struct gl_context * ctx, GLenum mode)
{
   if (ctx->DrawBuffer && _mesa_is_winsys_fbo(ctx->DrawBuffer)) {
      struct intel_context *const intel = intel_context(ctx);
      const bool was_front_buffer_rendering =
	intel->is_front_buffer_rendering;

      intel->is_front_buffer_rendering = (mode == GL_FRONT_LEFT)
	|| (mode == GL_FRONT) || (mode == GL_FRONT_AND_BACK);

      /* If we weren't front-buffer rendering before but we are now,
       * invalidate our DRI drawable so we'll ask for new buffers
       * (including the fake front) before we start rendering again.
       */
      if (!was_front_buffer_rendering && intel->is_front_buffer_rendering)
	 dri2InvalidateDrawable(intel->driContext->driDrawablePriv);
   }

   intel_draw_buffer(ctx);
}

static void
intelReadBuffer(struct gl_context * ctx, GLenum mode)
{
   if (ctx->ReadBuffer && _mesa_is_winsys_fbo(ctx->ReadBuffer)) {
      struct intel_context *const intel = intel_context(ctx);
      const bool was_front_buffer_reading =
	intel->is_front_buffer_reading;

      intel->is_front_buffer_reading = (mode == GL_FRONT_LEFT)
	|| (mode == GL_FRONT);

      /* If we weren't front-buffer reading before but we are now,
       * invalidate our DRI drawable so we'll ask for new buffers
       * (including the fake front) before we start reading again.
       */
      if (!was_front_buffer_reading && intel->is_front_buffer_reading)
	 dri2InvalidateDrawable(intel->driContext->driReadablePriv);
   }
}

void
intelInitBufferFuncs(struct dd_function_table *functions)
{
   functions->DrawBuffer = intelDrawBuffer;
   functions->ReadBuffer = intelReadBuffer;
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.12"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Application Server: rocksdb::CompactionFilter Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Application Server

Classes |
Public Member Functions |
List of all members

rocksdb::CompactionFilter Class Referenceabstract

Classes

struct  	Context

Public Member Functions

virtual bool 	Filter (int level, const Slice &key, const Slice &existing_value, std::string *new_value, bool *value_changed) const =0

virtual bool 	FilterMergeOperand (int level, const Slice &key, const Slice &operand) const

virtual bool 	IgnoreSnapshots () const

virtual const char * 	Name () const =0

The documentation for this class was generated from the following file:

Appserver/src/external/rocksdb/compaction_filter.h

rocksdb

CompactionFilter

Generated by

     1.8.12


text:
function getDay(d) {

    var weekday = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];
    return  weekday[d.getDay()];

}

function getMonthAbb(d) {

    var month = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
    return month[d.getMonth()];
}

function convertDateToOurString(date)
{
    if (date && date instanceof Date)
        d = date;
    else
    {
        var d = new Date();
        if (date !== null && date !== "") {
            d = new Date(date);
        }
    }
    var thisDate;
    if (moment(d).isSame(moment(),"day"))
        thisDate="Today";
    else if (moment(d).isSame(moment().subtract('days', 1),"day"))
        thisDate="Yesterday";
    else if (moment(d).isSame(moment().add('days', 1),"day"))
        thisDate="Tomorrow";
    else
        thisDate = getDay(d) + ", " + d.getDate() + " " + getMonthAbb(d) + " " + d.getFullYear();
    return (thisDate);
}

function pad0Number(number)
{
    var numWith0Padding;
    if (number < 10)
        numWith0Padding = "0" + number.toString();
    else
        numWith0Padding = number.toString();
    return numWith0Padding;
}

var dateFormat = {
    dmmmyyyy: function(date) {
       var currDt = date;

    var curr_date = currDt.getDate();
    var curr_year = currDt.getFullYear();

    return  curr_date + " " + getMonthAbb(currDt) + " " + curr_year;
    }
}

function formatAMPM(date) {
    var hours = date.getHours();
    var minutes = date.getMinutes();
    var ampm = hours >= 12 ? 'pm' : 'am';
    hours = hours % 12;
    hours = hours ? hours : 12; // the hour '0' should be '12'
    minutes = minutes < 10 ? '0' + minutes : minutes;
    var strTime = hours + ':' + minutes + ' ' + ampm;
    return strTime;
}

/*** Utilities functions object ***/
//Extending standard Date class with our need
Date.prototype.alxtoTimeString = function()
{
    var hours = pad0Number(this.getHours());
    var minutes = pad0Number(this.getMinutes());
    var seconds = pad0Number(this.getSeconds());
    return(hours + ":" + minutes + ":" + seconds);
};
Date.prototype.alxtoDateString = function()
{
    return(this.getFullYear() + "-" + pad0Number(this.getMonth() + 1) + "-" + pad0Number(this.getDate()));
};
Date.prototype.alxGetTimeZone = function()
{
    var timeString=this.toTimeString();
    var timeZone;
    if(timeString.indexOf("GMT") > -1)
    {
        timeZone=timeString.split("GMT")[1].substring(0, 5);
    }
    else if(timeString.indexOf("UTC") > -1)
    {
        timeZone=timeString.split("UTC")[1].substring(0, 5);
    }
    else
    {
        DBS && console.log("Timezone does not fit into either GMT ot UTC");
        DBS && console.log(timeString);
        timeZone = "+0000";
    }
    return timeZone;
};

//Get week number of this using moment.js (caution this is not always iso8601 week number depending on local
Date.prototype.getWeek = function (dowOffset) {
    var m=moment(this);
    return m.week();
};

function DurationObject(msec)
{
    this.totalmsec = msec;
    //convert totalmsec into hour, min, sec, msec
    this.hour = Math.floor(msec / 1000 / 60 / 60);
    msec -= this.hour * 1000 * 60 * 60;
    this.min = Math.floor(msec / 1000 / 60);
    msec -= this.min * 1000 * 60;
    this.sec = Math.floor(msec / 1000);
    msec -= this.sec * 1000;
    this.msec = msec;

    this.toString=function(format)
    {
        var strDuration;
        var h = this.hour + "h ";
        var m = this.min + "min ";
        var s = this.sec + "s";
        if(h==="0h "){h = "";}
        if(m==="0min "){m = "";}
        if(s==="0s"){s = "";}
        switch(format)
        {
            case "HH:MM":
                strDuration=pad0Number(this.hour) + ":" + pad0Number(this.min);
                break;
            case "HH:MM:SS":
                strDuration=pad0Number(this.hour) + ":" + pad0Number(this.min)+ ":" + pad0Number(this.sec);
                break;
            case "HM":
                if(h==="0h "&& m==="0min "){
                    strDuration="0h";
                }else{
                    strDuration = h + "" + m;
                    if (strDuration==="")
                        strDuration="0h";
                }
               break;
            case "hms":
            default:
                strDuration= h + "" + m + "" + s + "";
                if(strDuration==="")
                    strDuration="0h";
        }
        return(strDuration);
    };
}

function getFirstDayOfWeek(date) {
    var beginNewD = moment(date);

    return  beginNewD.startOf('week').format('YYYY-MM-DD');
}

function getFirstDayOfMonth(date) {

    var beginNewD = moment(date);
    var obj = beginNewD.endOf('month');
    var year = obj.format('YYYY');
    var month = obj.format('MM');

    return  "01-" + month + "-" + year;
}

function getCurrentDayOfWeek(date, id){

       var mfirstDayOfWeek = moment(date).weekday(id);

     return mfirstDayOfWeek.format("YYYY-MM-DD");

}


text:
//-----------------------------------------------------------------------
// <copyright file="DisplayInformation.macOS.cs" company="In The Hand Ltd">
//     Copyright © 2017 In The Hand Ltd. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------

using AppKit;

namespace InTheHand.Graphics.Display
{
    partial class DisplayInformation
    {
        private NSScreen _screen;

        public static implicit operator NSScreen(DisplayInformation d)
        {
            return d._screen;
        }

        private static DisplayInformation DoGetForCurrentView()
        {
            DisplayInformation di = new DisplayInformation();
            di._screen = NSApplication.SharedApplication.MainWindow.Screen;

            return di;
        }

        private DisplayOrientations GetCurrentOrientation()
        {
            return _screen.Frame.Width > _screen.Frame.Height ? DisplayOrientations.Landscape : DisplayOrientations.Portrait;
        }

    }
}


text:
<!DOCTYPE html>

<title>View transitions: computed style on pseudo-element stays in sync with the DOM element</title>
<link rel="help" href="https://www.w3.org/TR/css-view-transitions-1/">
<link rel="author" href="mailto:khushalsagar@chromium.org">


text:
package org.specsy;

import fi.jumi.api.drivers.TestId;
import fi.jumi.core.api.TestFile;
import fi.jumi.core.results.SuiteEventDemuxer;
import fi.jumi.core.testbench.TestBench;
import org.junit.*;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;

public abstract class SpecsyContract {

    private SuiteEventDemuxer results;

    @Before
    public void resetSpy() {
        GlobalSpy.reset();
        results = new TestBench().run(testClass());
    }

    public abstract Class<?> testClass();

    @Test
    public void executes_specs() {
        GlobalSpy.assertContains("spec executed");
    }

    @Test
    public void reports_spec_names() {
        String name = results.getTestName(TestFile.fromClass(testClass()), TestId.of(0));
        assertThat(name, is("name of a spec"));
    }

    @Test
    public void executes_defer_blocks_in_reverse_order() {
        GlobalSpy.assertContainsInPartialOrder("defer 2", "defer 1");
    }

    @Test
    public void can_use_isolated_execution_mode() {
        GlobalSpy.assertContains("isolated: 1");
    }

    @Test
    public void can_use_non_isolated_execution_mode() {
        GlobalSpy.assertContains("non-isolated: 2");
    }
}


text:
<?php

defined('AJXP_EXEC') or die( 'Access not allowed');

/**
 * Test cookie
 * @package AjaXplorer_Plugins
 * @subpackage Editor
 */
class LightGuiPlugin extends AJXP_Plugin {

    public function performChecks(){
        if(!isSet($_COOKIE["AJXP_GUI"]) || $_COOKIE["AJXP_GUI"] != "light") throw new Exception("no");
    }

}


text:
<?php

namespace li3_bot\tests\mocks\models;

class MockLog extends \li3_bot\models\LogMessages {}

?>


text:
class DVAPI TCanvas : public TWidget
{
protected:
public:
	TCanvas(TWidget *parent, string name = "canvas");
	~TCanvas();

	virtual void draw();
};

#endif


text:
.btn2 {
  display: inline-block;
  padding: 6px 12px;
  margin: 50px;
  font-weight: bold;
  line-height: 68px;
  text-align: center;
  white-space: nowrap;
  vertical-align: middle;
  cursor: pointer;
  background-image: none;
  border: 1px solid transparent;
  border-radius: 4px;
  -webkit-user-select: none;
     -moz-user-select: none;
      -ms-user-select: none;
       -o-user-select: none;
          user-select: none;
}

.btn2:focus {
  outline: thin dotted #333;
  outline: 5px auto -webkit-focus-ring-color;
  outline-offset: -2px;
}

.btn2:hover,
.btn2:focus {
  color: #333333;
  text-decoration: none;
}

.btn2:active,
.btn2.active {
  background-image: none;
  outline: 0;
  -webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);
          box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);
}

.btn-lg2 {
  padding: 10px 16px;
  font-size: 18px;
  border-radius: 6px;
  width: 200px;
  height: 100px;
}

.btn-primary2 {
  color: #ffffff;
  background-color: #349434;
  border-color: #349434;
}

.btn-primary2:hover,
.btn-primary2:focus,
.btn-primary2:active,
.btn-primary2.active,
.open .dropdown-toggle.btn-primary2 {
  color: #eeeeee;
  background-color: #3c9e3c;
  border-color: #3c9e3c;
}

.btn-primary2:active,
.btn-primary2.active,
.open .dropdown-toggle.btn-primary2 {
  background-image: none;
}

.btn-primary2.disabled,
.btn-primary2[disabled],
fieldset[disabled] .btn-primary2,
.btn-primary2.disabled:hover,
.btn-primary2[disabled]:hover,
fieldset[disabled] .btn-primary2:hover,
.btn-primary2.disabled:focus,
.btn-primary2[disabled]:focus,
fieldset[disabled] .btn-primary2:focus,
.btn-primary2.disabled:active,
.btn-primary2[disabled]:active,
fieldset[disabled] .btn-primary2:active,
.btn-primary2.disabled.active,
.btn-primary2[disabled].active,
fieldset[disabled] .btn-primary2.active {
  background-color: #428bca;
  border-color: #357ebd;
}

.bodystyle {
  background-color: #5fb05f;
  text-align: center;
  padding-top: 15%;
}


text:
using System.Collections.Immutable;
using DFWin.Core.Models;
using Microsoft.Xna.Framework.Input;
using Keyboard = Microsoft.Xna.Framework.Input.Keyboard;

namespace DFWin.Core.Inputs
{
    public class KeyboardInput
    {
        /// <summary>
        /// Represents keys that are being pressed right now. Note that this will remain true every frame of the game
        /// the key is pressed, so if the user is trying to perform a precise action with a specific number of presses,
        /// you should use RecentlyPressedKeys instead.
        /// </summary>
        public ImmutableHashSet<Keys> CurrentlyPressedKeys { get; }

        /// <summary>
        /// Represents keys that have "just" been pressed. If a key is held down, this should only indicate the key once
        /// until after a short period of time after which it starts to repeat at an increasing rate.
        /// </summary>
        public ImmutableHashSet<Keys> RecentlyPressedKeys { get; }

        public KeyboardInput(ImmutableHashSet<Keys> currentlyPressedKeys, ImmutableHashSet<Keys> recentlyPressedKeys)
        {
            CurrentlyPressedKeys = currentlyPressedKeys;
            RecentlyPressedKeys = recentlyPressedKeys;
        }

        public static KeyboardInput InitialInput => new KeyboardInput(ImmutableHashSet<Keys>.Empty, ImmutableHashSet<Keys>.Empty);
    }
}


text:
import re
import copy

from parser_exception import ParserException
import utils
import xml_utils

VALID_UNDERLYING_TYPES_FOR_ENUMS = [
	'int8_t', 'uint8_t', 'int16_t', 'uint16_t', 'int32_t', 'uint32_t', 'int64_t', 'uint64_t' ]

# Not allowed are 'float' and 'char'

class BaseType(object):
	""" Abstract base class for all types

	Attributes:
	name		--	Type name. Must be unique.
	reference	--	True if the type is only used as reference for other
					types and should not be included in the output.
	description	--	Description of the type
	string		--  Short description for enum members
	isEnum		--	True if the type is an enum type
	isStruct	--	analog
	isTypedef	--	analog
	isBuiltIn	--	analog
	level		--	hierarchy level. Built-in types have level -1, the level
					of a type is the highest level of a subtype plus one.
	size		--	Size
	"""
	def __init__(self, node):
		self.node = node

		self.name = node.get('name')
		self._check_name()
		self.description = None
		self.string = None

		self.isEnum = False
		self.isStruct = False
		self.isTypedef = False
		self.isBuiltIn = False

		self.level = None
		self.size = None

	def _check_name(self):
		utils.check_name(self.name)

	def evaluate(self, tree):
		""" Load the state of the class from the corresponding XML node

		Keyword arguments:
		tree	--	current tree of the communcation structure. Must contain
					every available type, but some types may not be fully
					evaluated
		"""
		pass

	def create_hierarchy(self):
		"""	Create the type hierarchy

		This method calculates the values for self.size and self.level. Must
		not be called before all types are fully created.
		"""
		pass

	def flattened(self):
		""" Access the version with the flattened hierarchy """
		return self

	def __cmp__(self, other):
		""" Compare two types

		If types are sorted they are sorted first by level and then by name.
		"""
		if isinstance(other, BaseType):
			return cmp(self.level, other.level) or cmp(self.name, other.name)
		else:
			return 1

class BuiltIn(BaseType):
	""" Built-in types

	These types correspond directly to types available by default in the
	target environment. The hierarchy level will always be -1 (lowest level).
	"""
	def __init__(self, node):
		BaseType.__init__(self, node)

		self.isBuiltIn = True
		self.level = -1

	def evaluate(self, tree):
		if self.node is None:
			return

		self.description = xml_utils.get_description(self.node)
		self.string = xml_utils.get_string(self.node)
		self.size = int(self.node.get('size'))

		self.node = None

	def _check_name(self):
		""" Built-in types need no check """
		pass

	def dump(self):
		return "%s : built-in|%i [%i]" % (self.name, self.level, self.size)

	def __str__(self):
		return "%s : built-in" % self.name

class Enum(BaseType):

	class Element(object):
		""" Sub-element of an enum-type """
		def __init__(self, node, stronglyTyped):
			""" Constructor

			The name of the element has to be all upper case with underscores.
			"""
			self.name = node.get('name')

			if not stronglyTyped:
				if not re.match("^[0-9A-Z_]*$", self.name):
					raise ParserException("Attribute name of element in enum has to be `UPPER_UNDERSCORE_STYLE` (found: '%s')" % (self.name))
			else:
				utils.check_name(self.name)

			self.string = node.get('string')
			if self.string is None:
				self.string = self.name

			self.description = xml_utils.get_description(node)
			self.string = xml_utils.get_string(node)

			value = node.get('value')
			self.value = None if (value is None) else int(value, 0)

		def __str__(self):
			return "%s = %s" % (self.name, self.value)

	def __init__(self, node):
		BaseType.__init__(self, node)

		self._last_value = 0
		self.elements = []

		self.isEnum = True
		self.isStronglyTyped = False

		typed = node.get('typed')
		if typed is not None:
			if typed in ["strong", "weak"]:
				self.isStronglyTyped = (typed == "strong")
			else:
				raise ParserException("Attribute typed of element in enum has to be either `strong` or `weak` (found: '%s')" % (self.typed))

		self.underlyingType = node.get('underlyingType')

		if self.underlyingType is None:
			self.underlyingType = "uint8_t"

		if self.underlyingType is not None and self.underlyingType not in VALID_UNDERLYING_TYPES_FOR_ENUMS:
			raise ParserException("Attribute underlyingType of element in enum has to be a built in value (found: '%s')" % (self.underlyingType))

		# an enum does not depend on other types
		self.level = 0
		self.size = 1
		# FIXME calculate actual size depending on the value for the enum elements
		if '8' in self.underlyingType:
			self.size = 1
		elif '16' in self.underlyingType:
			self.size = 2
		elif '32' in self.underlyingType:
			self.size = 4
		elif '64' in self.underlyingType:
			self.size = 8

		self.numberOfElements = None

	def iter(self):
		""" Iterate over all sub-elements of the enum """
		for element in self.elements:
			yield element

	def evaluate(self, tree):
		if self.node is None:
			return

		self.description = xml_utils.get_description(self.node)
		self.string = xml_utils.get_string(self.node)
		for node in self.node.findall('element'):
			self.__add(self.Element(node, self.isStronglyTyped))

		self.node = None
		self.numberOfElements = len(self.elements)

	def __add(self, element):
		""" Add an element to the enum.

		This has to be done in the order the elements should appear later.
		"""
		if element.value == None:
			element.value = self._last_value
			self._last_value += 1
		else:
			try:
				self._last_value = element.value + 1
			except ValueError:
				pass

		self.elements.append(element)

	def create_hierarchy(self):
		pass

	def dump(self):
		str = "%s : enum|%i [%i]\n" % (self.name, self.level, self.size)
		for element in self.iter():
			str += "  + %s\n" % element
		return str[:-1]

	def __str__(self):
		return "%s : enum|%i" % (self.name, self.level)

class SubType:
	""" Subordinate type for struct and typedefs.

	Used to distinguish between normal and array types for the subtype of
	struct elements and typedefs.

	Attributes:
	raw		--	raw typename.
	name	--	type without a possible array definition.
	count	--	Number of array elements. Defaults to 1 if the type is no array.
	isArray	--	Subtype is an array

	Example:
	type = SubType("uint8_t")
	=> .raw = "uint8_t"
	   .name = "uint8_t"
	   .isArray = False
	   .count = 1
	   .type = BuiltIn("uint8_t")

	type = SubType("char[8])
	=> .raw = "char[8]"
	   .name = "char"
	   .isArray = True
	   .count = 8
	   .type = BuiltIn("char")

	"""
	def __init__(self, value, types):
		""" Constructor

		Keyword Arguments:
		value	-- type name
		types	-- list of all available types
		"""
		self.raw = value
		if value.endswith(']'):
			self.isArray = True
			self.name, number = value.split('[')
			self.count = number[:-1]
		else:
			self.isArray = False
			self.count = 1
			self.name = value

		try:
			self.type = types[self.name]
		except KeyError:
			raise ParserException("Unknown type '%s'" % self.name)
		self.size = None

	def __str__(self):
		return self.raw

class Struct(BaseType):
	""" Representation of a Struct

	Attributes:
	size	--	Size of the struct in bytes. Will always return the total size
				of the flattened struct if the struct is part of inheritence
				structure.
	"""
	class Element(object):

		def __init__(self, node, tree):
			self.name = node.get('name')

			self.description = xml_utils.get_description(node)
			self.string = xml_utils.get_string(node)
			self.subtype = SubType(node.get('type'), tree.types)
			self.unit = node.get('unit')
			self.value = node.get('value')

			self.level = None
			self.size = None

		def create_hierarchy(self):
			subtype = self.subtype.type
			if subtype.level is None:
				subtype.create_hierarchy()

			self.level = subtype.level
			self.size = subtype.size

		def __str__(self):
			return "%s : %s" % (self.name, self.subtype)

	def __init__(self, node):
		BaseType.__init__(self, node)

		self.isStruct = True
		self.elements = []
		self.extends = None
		self.extending = []
		self.typeIdentifier = None

		self.__flattened = None
		self.__typeIdentifierName = None

	def iter(self):
		""" Iterate over all sub-elements of the enum """
		for element in self.elements:
			yield element

	def evaluate(self, tree):
		if self.node is None:
			return

		self.description = xml_utils.get_description(self.node)
		self.string = xml_utils.get_string(self.node)
		for node in self.node.findall('element'):
			try:
				self.elements.append(self.Element(node, tree))
			except ParserException as e:
				raise ParserException("Error in definition of struct '%s': %s!" % (self.name, e))

		basetype = self.node.get('extends')
		if basetype is not None:
			try:
				self.extends = tree.types[basetype]
				if not self.extends.isStruct:
					raise ParserException("Struct '%s' is derived from non struct '%s'!" % (self.name, self.extends.name))
				if self.extends.extends:
					raise ParserException("Struct '%s' extends struct '%s'. Structs are only allowed to extend from those Structs, which do not extend anything!" % (self.name, self.extends.name))
				self.__typeIdentifierName = self.node.get('typeIdentifier')
				if self.__typeIdentifierName is None:
					raise ParserException("Struct '%s' does extend '%s', but does not provide the attribute 'typeIdentifier'!" % (self.name, self.extends.name))

			except KeyError:
				raise ParserException("Unknown super type '%s' in struct '%s'!" % (basetype, self.name))
		self.node = None

	def create_hierarchy(self):
		""" Create hierarchy

		For this method self.size = 0 is used as sepecial value to detect
		loops in the definition of types. In normal operation size will never be
		zero, only during hierarchy creation.
		"""
		if self.level is not None:
			return

		self.size = 0
		size = 0
		self.level = 0
		for element in self.elements:
			if element.size == 0:
				raise ParserException("Loop in the definition of '%s' and '%s' detected!" % (self.name, self.element.name))
			element.create_hierarchy()

			size += element.size
			self.level = max(self.level, element.level)

		if self.extends is not None:
			if self.extends.size == 0:
				raise ParserException("Loop in the definition of '%s' and '%s' detected!" % (self.name, self.extends.name))
			self.extends.create_hierarchy()
			typeIdentifierStructElement = self.extends.elements[0]
			if not typeIdentifierStructElement.subtype.type.isEnum:
				raise ParserException("Struct '%s' is extended by Struct '%s'. "  \
					"Structs which are extended by other must have an element named " \
					"'type' of any enum type as their first element! It is used for " \
					"type distinguishing at runtime." \
						% (self.extends.name, self.name))
			if not typeIdentifierStructElement.name == 'type':
				raise ParserException("Struct '%s' is extended by Struct '%s'. Structs" \
					"which are extended by other must have an element named 'type' as" \
					"their first element! It is used for type distinguishing at runtime." \
						% (self.extends.name, self.name))

			for enumElement in typeIdentifierStructElement.subtype.type.elements:
				if enumElement.name == self.__typeIdentifierName:
					self.typeIdentifier = enumElement
					break
			if not self.typeIdentifier:
				raise ParserException("Struct '%s' extends Struct '%s', but it's " \
					"typeIdentifier '%s' is not member of enum '%s' which is the " \
					"type of '%s.type'."
						% (self.name, self.extends.name, self.__typeIdentifierName,
							typeIdentifierStructElement.subtype.type.name, self.extends.name))

			self.extends.__addExtending(self)
			size += self.extends.size
			self.level = max(self.level, self.extends.level)

		if size > 48:
			raise ParserException("Struct '%s' is with %i Byte too big. The maximum " \
				"packet size is 48 Byte!" % (self.name, size))

		self.size = size
		self.level += 1

	def flattened(self):
		if self.__flattened is None:
			if self.extends is None:
				self.__flattened = self
			else:
				self.__flattened = copy.copy(self)
				self.__flattened.elements = self.elements[:]

				# prepend all elements for the super type
				self.__flattened.elements[0:0] = self.extends.flattened().elements

		return self.__flattened

	def dump(self):
		str = "%s : struct|%i [%i]\n" % \
			(self.name, self.level, self.size)
		for element in self.iter():
			str += "  + %s\n" % element
		return str[:-1]

	def __str__(self):
		return "%s : struct|%i" % (self.name, self.level)

	def __addExtending(self, extending):
		for struct in self.extending:
			if struct.typeIdentifier == extending.typeIdentifier:
				raise ParserException("Duplicate TypeIdentifier '%s' in Struct group extending '%s'. ('%s' and '%s')" % (extending.typeIdentifier.name, self.name, struct.name, extending.name))
		self.extending.append(extending)

class Typedef(BaseType):

	def __init__(self, node):
		BaseType.__init__(self, node)

		self.subtype = None
		self.unit = None

		self.isTypedef = True

	def evaluate(self, tree):
		self.description = xml_utils.get_description(self.node)
		self.string = xml_utils.get_string(self.node)
		self.unit = self.node.get('unit')
		try:
			self.subtype = SubType(self.node.get('type'), tree.types)
		except ParserException as e:
			raise ParserException("Error in definition of typedef '%s': %s" % (self.name, e))

	def create_hierarchy(self):
		""" Create hierarchy

		See Struct.create_hierarchy() for a detailed description of this
		method.
		"""
		if self.level is not None:
			return

		self.size = 0
		subtype = self.subtype.type
		if subtype.level is None:
			if self.subtype.size == 0:
				raise ParserException("Loop in the definition of '%s' and '%s' detected!" % (self.name, self.subtype.name))
			subtype.create_hierarchy()

		self.level = subtype.level + 1
		self.size = subtype.size

	def dump(self):
		return "%s : typedef|%i [%i]\n  -> %s" % (self.name, self.level, self.size, self.subtype)

	def __str__(self):
		return "%s : typedef|%i" % (self.name, self.level)


text:
<?php
/** @var yii\web\View $this  */
use devgroup\JsTreeWidget\widgets\TreeInputAssetBundle;
use devgroup\JsTreeWidget\widgets\TreeWidget;
use yii\helpers\Html;

/**
 * @var string $input
 * @var string $id
 * @var string $selectIcon
 * @var string $selectText
 * @var bool   $multiple
 * @var bool   $search
 * @var bool   $clickToOpen
 * @var array  $treeConfig
 */

TreeInputAssetBundle::register($this);
?>

    <?= $input ?>
    <?php if ($clickToOpen): ?>

            <i class="fa-fw <?= $selectIcon ?>">
            <?= $selectText ?>

    <?php endif; ?>
    <div class="tree-input__tree-container <?= $clickToOpen === false ? 'tree-input__tree-container_opened_always' : '' ?>">
        <?php if ($multiple === false && $clickToOpen): ?>

            <?= Yii::t('jstw', 'Double click needed tree node to select it') ?>

        <?php endif;?>

        <?php if ($search): ?>

                <input type="text" class="form-control tree-input__search" placeholder="<?= Html::encode(Yii::t('jstw', 'Type to search'))?>">

                    <?= Yii::t('jstw', 'Clear') ?>

        <?php endif; ?>

        <?=
        TreeWidget::widget($treeConfig)
        ?>
        <?php if ($multiple && $clickToOpen): ?>

                <?= Yii::t('jstw', 'OK') ?>

        <?php endif;?>

<?php
$clickToOpenJson = $clickToOpen ? 'true' : 'false';
$js = <<<js
  var treeInput = $('#{$id}').parent();
  var jstree = $('#{$id}__tree');
  var treeContainer = treeInput.find('.tree-input__tree-container');
  var search = treeContainer.find('.tree-input__search');
  if (search.length) {
    var to = false;
    search.keyup(function() {
      if(to) { clearTimeout(to); }
      to = setTimeout(function () {
        var v = search.val();
        jstree.jstree(true).search(v);
      }, 1000);
    });

    treeContainer.find('.tree-input__search-clear').click(function(){
      search.val('');
      jstree.jstree('clear_search');
      return false;
    });
  }
  var clickToOpen = $clickToOpenJson;
  if (clickToOpen) {
      var buttonArrow = treeInput.find('.tree-input__arrow');
      var selectButton = treeInput.find('.tree-input__button');
      var selected = treeInput.find('.tree-input__selected-values');
      selectButton.click(function() {
        treeContainer.toggleClass('tree-input__tree-container_active');
        buttonArrow.toggleClass('fa-angle-down');
        return false;
      });
  }
  var emptySelected = function() {
    if (clickToOpen) {
      selected.empty()
    }
    $('#{$id}').val('').trigger('change');
  };
  var selectNode = function(node) {
    if (clickToOpen) {
        var path = jstree.jstree('get_path', node, ' > ');
        selected.append('
' + path + '
');
    }

    const val = $('#{$id}').val();
    const selectedNow = val.length > 0 ? val.split(',') : [];
    selectedNow.push(node);
    $('#{$id}').val(selectedNow.join(',')).trigger('change');
  };
js;

if ($multiple === false) {
    $js .= <<<js
  if (clickToOpen) {
      $('#{$id}__tree')
        .on("dblclick.jstree", function (event) {
          var node = $(event.target).closest('.jstree-anchor').data("id");
          emptySelected();
          selectNode(node);
          selectButton.click();
        });
  } else {
      $('#{$id}__tree')
        .on('select_node.jstree', function(event, data) {
          emptySelected();
          selectNode(data.node.id);
        });
  }
  const selectedVal = $('#{$id}').val();
  if (selectedVal > 0) {
    $('#{$id}__tree').on('ready.jstree', function(e, data) {
      emptySelected();
      selectNode(selectedVal);

    });
  }
js;
} else {
    $js .= <<<js
    var selectedValues = $('#{$id}').val().split(',');
    $('#{$id}__tree').on('ready.jstree', function(e, data) {
      emptySelected();
      selectedValues.forEach(function(value) {
        selectNode(value);

      });
    });
    var applySelected = function() {
      emptySelected();
      $("#{$id}__tree").jstree("get_checked",null,true).forEach(function (id) {
        selectNode(id);

      });
      if (clickToOpen) {
        selectButton.click();
      }
    };
    if (clickToOpen) {
        treeContainer.find('.tree-input__select').click(function() {
          applySelected();
          return false;
        });
    } else {
      $('#{$id}__tree')
        .on('changed.jstree', function() {
          applySelected();
        });
    }
js;

}

$js .= <<<js

js;

$this->registerJs(
    <<<js
(function(){
$js
})();

js

);


text:
package com.lfkdsk.justel.token;

/**
 * String Token.
 * used in lexer => will be add to spec Literal.
 *
 * @author liufengkai
 *         Created by liufengkai on 2017/7/24.
 * @see com.lfkdsk.justel.token.Token
 * @see com.lfkdsk.justel.lexer.Lexer
 * @see com.lfkdsk.justel.literal.StringLiteral
 */
public class StringToken extends Token implements Comparable<StringToken> {
    private String text;

    public StringToken(int lineNumber, String text) {
        super(lineNumber, Token.STRING);
        this.text = text;
    }

    @Override
    public String getText() {
        return text;
    }

    @Override
    public boolean isString() {
        return true;
    }

    @Override
    public String toString() {
        return "StringToken{" +
                "text='" + text + '\'' +
                ", lineNumber=" + lineNumber +
                ", tag=" + tag +
                '}';
    }

    @Override
    public int compareTo(StringToken o) {
        return getText().compareTo(o.getText());
    }
}


text:
<?php

namespace DCarbone\PHPFHIRGenerated\DSTU2\PHPFHIRTests\FHIRElement\FHIRBackboneElement\FHIRClaimResponse;

use PHPUnit\Framework\TestCase;
use DCarbone\PHPFHIRGenerated\DSTU2\FHIRElement\FHIRBackboneElement\FHIRClaimResponse\FHIRClaimResponseItem;

/**
 * Class FHIRClaimResponseItemTest
 * @package \DCarbone\PHPFHIRGenerated\DSTU2\PHPFHIRTests\FHIRElement\FHIRBackboneElement\FHIRClaimResponse
 */
class FHIRClaimResponseItemTest extends TestCase
{
    public function testCanConstructTypeNoArgs()
    {
        $type = new FHIRClaimResponseItem();
        $this->assertInstanceOf('\DCarbone\PHPFHIRGenerated\DSTU2\FHIRElement\FHIRBackboneElement\FHIRClaimResponse\FHIRClaimResponseItem', $type);
    }
}


text:
// Template Source: BaseEntityCollectionPage.java.tt
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All Rights Reserved.  Licensed under the MIT License.  See License in the project root for license information.
// ------------------------------------------------------------------------------

package com.microsoft.graph.requests;
import com.microsoft.graph.models.PinnedChatMessageInfo;
import com.microsoft.graph.requests.PinnedChatMessageInfoCollectionRequestBuilder;
import javax.annotation.Nullable;
import javax.annotation.Nonnull;
import com.microsoft.graph.requests.PinnedChatMessageInfoCollectionResponse;
import com.microsoft.graph.http.BaseCollectionPage;

// **NOTE** This file was generated by a tool and any changes will be overwritten.

/**
 * The class for the Pinned Chat Message Info Collection Page.
 */
public class PinnedChatMessageInfoCollectionPage extends BaseCollectionPage<PinnedChatMessageInfo, PinnedChatMessageInfoCollectionRequestBuilder> {

    /**
     * A collection page for PinnedChatMessageInfo
     *
     * @param response the serialized PinnedChatMessageInfoCollectionResponse from the service
     * @param builder  the request builder for the next collection page
     */
    public PinnedChatMessageInfoCollectionPage(@Nonnull final PinnedChatMessageInfoCollectionResponse response, @Nonnull final PinnedChatMessageInfoCollectionRequestBuilder builder) {
        super(response, builder);
    }

    /**
     * Creates the collection page for PinnedChatMessageInfo
     *
     * @param pageContents       the contents of this page
     * @param nextRequestBuilder the request builder for the next page
     */
    public PinnedChatMessageInfoCollectionPage(@Nonnull final java.util.List<PinnedChatMessageInfo> pageContents, @Nullable final PinnedChatMessageInfoCollectionRequestBuilder nextRequestBuilder) {
        super(pageContents, nextRequestBuilder);
    }
}


text:
describe('Ms-read component testing',function () {
    //fakes...
    var singleMessage = {
        "_id": 1,
        "title": "Quod voluptas impedit sit ex quidem.",
        "content": "Vero voluptas ratione sunt amet tempore.\nPorro perspiciatis rem.\nEt laudantium et non quae.",
        "email": "Ricky.Rohan68@hotmail.com",
        "box": "Important",
        "date": "2015-10-03T06:05:08.640Z",
        "read": true,
        "important": true,
        "withAttachment": false
    };

    var MessageService,$controller,msReadController;
    // Before each test load our core module
    beforeEach(angular.mock.module('core'));
    beforeEach(angular.mock.module('messages'));

    beforeEach(inject(function(_Message_,_$componentController_) {
        MessageService = _Message_;
        $controller=_$componentController_;
        msReadController = $controller('msRead');
    }));

    it('should be defined', function() {
        expect(msReadController).toBeDefined();
    });
});


text:
/**
 * CRC16 is a class containing an implementation of the
 * Cyclic-Redundency-Check (CRC) CRC16.  The CRC16 is used in
 * iButton memory packet structure.
 *

 * CRC16 is based on the polynomial = X^16 + X^15 + X^2 + 1.
 *
 * @version    0.00, 28 Aug 2000
 * @author     DS
 */
public class CRC16
{

   //--------
   //-------- Variables
   //--------

   /**
    * used in CRC16 calculation
    */
   private static final int[] ODD_PARITY =
   {
      0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0
   };

   //--------
   //-------- Constructor
   //--------

   /**
    * Private constructor to prevent instantiation.
    */
   private CRC16 ()
   {
   }

   //--------
   //-------- Methods
   //--------

   /**
    * Perform the CRC16 on the data element based on a zero seed.
    *

    * CRC16 is based on the polynomial = X^16 + X^15 + X^2 + 1.
    *
    * @param  dataToCrc     data element on which to perform the CRC16
    * @return  CRC16 value
    */
   public static int compute (int dataToCrc)
   {
      return compute(dataToCrc, 0);
   }

   /**
    * Perform the CRC16 on the data element based on the provided seed.
    *

    * CRC16 is based on the polynomial = X^16 + X^15 + X^2 + 1.
    *
    * @param  dataToCrc     data element on which to perform the CRC16
    * @return  CRC16 value
    */
   public static int compute (int dataToCrc, int seed)
   {
      int dat = ((dataToCrc ^ (seed & 0xFF)) & 0xFF);

      seed = (seed&0xFFFF) >>> 8;

      int indx1 = (dat & 0x0F);
      int indx2 = (dat >>> 4);

      if ((ODD_PARITY [indx1] ^ ODD_PARITY [indx2]) == 1)
         seed = seed ^ 0xC001;

      dat  = (dat << 6);
      seed = seed ^ dat;
      dat  = (dat << 1);
      seed = seed ^ dat;

      return seed;
   }

   /**
    * Perform the CRC16 on an array of data elements based on a
    * zero seed.
    *

    * CRC16 is based on the polynomial = X^16 + X^15 + X^2 + 1.
    *
    * @param   dataToCrc   array of data elements on which to perform the CRC16
    *
    * @return  CRC16 value
    */
   public static int compute (byte dataToCrc [])
   {
      return compute(dataToCrc, 0, dataToCrc.length, 0);
   }

   /**
    * Perform the CRC16 on an array of data elements based on a
    * zero seed.
    *

    * CRC16 is based on the polynomial = X^16 + X^15 + X^2 + 1.
    *
    * @param   dataToCrc   array of data elements on which to perform the CRC16
    * @param   off         offset into the data array
    * @param   len         length of data to CRC16
    *
    * @return  CRC16 value
    */
   public static int compute (byte dataToCrc [], int off, int len)
   {
      return compute(dataToCrc, off, len, 0);
   }

   /**
    * Perform the CRC16 on an array of data elements based on the
    * provided seed.
    *

    * CRC16 is based on the polynomial = X^16 + X^15 + X^2 + 1.
    *
    * @param   dataToCrc   array of data elements on which to perform the CRC16
    * @param   off         offset into the data array
    * @param   len         length of data to CRC16
    * @param   seed        seed to use for CRC16
    *
    * @return  CRC16 value
    */
   public static int compute (byte dataToCrc [], int off, int len, int seed)
   {

      // loop to do the crc on each data element
      for (int i = 0; i < len; i++)
         seed = compute(dataToCrc [i + off], seed);

      return seed;
   }

   /**
    * Perform the CRC16 on an array of data elements based on the
    * provided seed.
    *

    * CRC16 is based on the polynomial = X^16 + X^15 + X^2 + 1.
    *
    * @param   dataToCrc   array of data elements on which to perform the CRC16
    * @param   seed        seed to use for CRC16
    * @return  CRC16 value
    */
   public static int compute (byte dataToCrc [], int seed)
   {
      return compute(dataToCrc, 0, dataToCrc.length, seed);
   }
}


text:
<?php

namespace ntentan\middleware\auth;

use ntentan\Parameters;

class AuthMethodFactory
{
    private $authMethods = [
        'http_request' => HttpRequestAuthMethod::class,
        'http_basic' => HttpBasicAuthMethod::class
    ];

    public function createAuthMethod(Parameters $parameters) : AbstractAuthMethod
    {
        $authMethodType = $parameters->get('auth_method', 'http_request');
        if (!isset($this->authMethods[$authMethodType])) {
            throw new \Exception("Auth method $authMethodType not found");
        }
        $class = $this->authMethods[$authMethodType];
        return new $class();
    }

    public function registerAuthMethod(string $name, string $class) : void
    {
        $this->authMethods[$name] = $class;
    }
}