text:
package org.apache.logging.log4j.spi;

import java.io.Serializable;

import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.MarkerManager;
import org.apache.logging.log4j.message.Message;
import org.apache.logging.log4j.message.MessageFactory;
import org.apache.logging.log4j.message.ParameterizedMessageFactory;
import org.apache.logging.log4j.message.StringFormattedMessage;
import org.apache.logging.log4j.status.StatusLogger;
import org.apache.logging.log4j.util.LambdaUtil;
import org.apache.logging.log4j.util.MessageSupplier;
import org.apache.logging.log4j.util.Supplier;

/**
 * Base implementation of a Logger. It is highly recommended that any Logger implementation extend this class.
 */
public abstract class AbstractLogger implements ExtendedLogger, Serializable {

    /**
     * Marker for flow tracing.
     */
    public static final Marker FLOW_MARKER = MarkerManager.getMarker("FLOW");

    /**
     * Marker for method entry tracing.
     */
    public static final Marker ENTRY_MARKER = MarkerManager.getMarker("ENTRY").setParents(FLOW_MARKER);

    /**
     * Marker for method exit tracing.
     */
    public static final Marker EXIT_MARKER = MarkerManager.getMarker("EXIT").setParents(FLOW_MARKER);

    /**
     * Marker for exception tracing.
     */
    public static final Marker EXCEPTION_MARKER = MarkerManager.getMarker("EXCEPTION");

    /**
     * Marker for throwing exceptions.
     */
    public static final Marker THROWING_MARKER = MarkerManager.getMarker("THROWING").setParents(EXCEPTION_MARKER);

    /**
     * Marker for catching exceptions.
     */
    public static final Marker CATCHING_MARKER = MarkerManager.getMarker("CATCHING").setParents(EXCEPTION_MARKER);

    /**
     * The default MessageFactory class.
     */
    public static final Class<? extends MessageFactory> DEFAULT_MESSAGE_FACTORY_CLASS =
            ParameterizedMessageFactory.class;

    private static final long serialVersionUID = 2L;

    private static final String FQCN = AbstractLogger.class.getName();
    private static final String THROWING = "throwing";
    private static final String CATCHING = "catching";

    private final String name;
    private final MessageFactory messageFactory;

    /**
     * Creates a new logger named after this class (or subclass).
     */
    public AbstractLogger() {
        this.name = getClass().getName();
        this.messageFactory = createDefaultMessageFactory();
    }

    /**
     * Creates a new named logger.
     *
     * @param name the logger name
     */
    public AbstractLogger(final String name) {
        this.name = name;
        this.messageFactory = createDefaultMessageFactory();
    }

    /**
     * Creates a new named logger with a particular {@link MessageFactory}.
     *
     * @param name the logger name
     * @param messageFactory the message factory, if null then use the default message factory.
     */
    public AbstractLogger(final String name, final MessageFactory messageFactory) {
        this.name = name;
        this.messageFactory = messageFactory == null ? createDefaultMessageFactory() : messageFactory;
    }

    /**
     * Checks that the message factory a logger was created with is the same as the given messageFactory. If they are
     * different log a warning to the {@linkplain StatusLogger}. A null MessageFactory translates to the default
     * MessageFactory {@link #DEFAULT_MESSAGE_FACTORY_CLASS}.
     *
     * @param logger The logger to check
     * @param messageFactory The message factory to check.
     */
    public static void checkMessageFactory(final ExtendedLogger logger, final MessageFactory messageFactory) {
        final String name = logger.getName();
        final MessageFactory loggerMessageFactory = logger.getMessageFactory();
        if (messageFactory != null && !loggerMessageFactory.equals(messageFactory)) {
            StatusLogger.getLogger().warn(
                    "The Logger {} was created with the message factory {} and is now requested with the "
                            + "message factory {}, which may create log events with unexpected formatting.", name,
                    loggerMessageFactory, messageFactory);
        } else if (messageFactory == null && !loggerMessageFactory.getClass().equals(DEFAULT_MESSAGE_FACTORY_CLASS)) {
            StatusLogger
                    .getLogger()
                    .warn("The Logger {} was created with the message factory {} and is now requested with a null "
                            + "message factory (defaults to {}), which may create log events with unexpected "
                            + "formatting.",
                            name, loggerMessageFactory, DEFAULT_MESSAGE_FACTORY_CLASS.getName());
        }
    }

    @Override
    public void catching(final Level level, final Throwable t) {
        catching(FQCN, level, t);
    }

    /**
     * Logs a Throwable that has been caught with location information.
     *
     * @param fqcn The fully qualified class name of the caller.
     * @param level The logging level.
     * @param t The Throwable.
     */
    protected void catching(final String fqcn, final Level level, final Throwable t) {
        if (isEnabled(level, CATCHING_MARKER, (Object) null, null)) {
            logMessage(fqcn, level, CATCHING_MARKER, catchingMsg(t), t);
        }
    }

    @Override
    public void catching(final Throwable t) {
        if (isEnabled(Level.ERROR, CATCHING_MARKER, (Object) null, null)) {
            logMessage(FQCN, Level.ERROR, CATCHING_MARKER, catchingMsg(t), t);
        }
    }

    protected Message catchingMsg(final Throwable t) {
        return messageFactory.newMessage(CATCHING);
    }

    private MessageFactory createDefaultMessageFactory() {
        try {
            return DEFAULT_MESSAGE_FACTORY_CLASS.newInstance();
        } catch (final InstantiationException e) {
            throw new IllegalStateException(e);
        } catch (final IllegalAccessException e) {
            throw new IllegalStateException(e);
        }
    }

    @Override
    public void debug(final Marker marker, final Message msg) {
        logIfEnabled(FQCN, Level.DEBUG, marker, msg, null);
    }

    @Override
    public void debug(final Marker marker, final Message msg, final Throwable t) {
        logIfEnabled(FQCN, Level.DEBUG, marker, msg, t);
    }

    @Override
    public void debug(final Marker marker, final Object message) {
        logIfEnabled(FQCN, Level.DEBUG, marker, message, null);
    }

    @Override
    public void debug(final Marker marker, final Object message, final Throwable t) {
        logIfEnabled(FQCN, Level.DEBUG, marker, message, t);
    }

    @Override
    public void debug(final Marker marker, final String message) {
        logIfEnabled(FQCN, Level.DEBUG, marker, message, (Throwable) null);
    }

    @Override
    public void debug(final Marker marker, final String message, final Object... params) {
        logIfEnabled(FQCN, Level.DEBUG, marker, message, params);
    }

    @Override
    public void debug(final Marker marker, final String message, final Throwable t) {
        logIfEnabled(FQCN, Level.DEBUG, marker, message, t);
    }

    @Override
    public void debug(final Message msg) {
        logIfEnabled(FQCN, Level.DEBUG, null, msg, null);
    }

    @Override
    public void debug(final Message msg, final Throwable t) {
        logIfEnabled(FQCN, Level.DEBUG, null, msg, t);
    }

    @Override
    public void debug(final Object message) {
        logIfEnabled(FQCN, Level.DEBUG, null, message, null);
    }

    @Override
    public void debug(final Object message, final Throwable t) {
        logIfEnabled(FQCN, Level.DEBUG, null, message, t);
    }

    @Override
    public void debug(final String message) {
        logIfEnabled(FQCN, Level.DEBUG, null, message, (Throwable) null);
    }

    @Override
    public void debug(final String message, final Object... params) {
        logIfEnabled(FQCN, Level.DEBUG, null, message, params);
    }

    @Override
    public void debug(final String message, final Throwable t) {
        logIfEnabled(FQCN, Level.DEBUG, null, message, t);
    }

    @Override
    public void debug(final Supplier<?> msgSupplier) {
        logIfEnabled(FQCN, Level.DEBUG, null, msgSupplier, (Throwable) null);
    }

    @Override
    public void debug(final Supplier<?> msgSupplier, final Throwable t) {
        logIfEnabled(FQCN, Level.DEBUG, null, msgSupplier, t);
    }

    @Override
    public void debug(final Marker marker, final Supplier<?> msgSupplier) {
        logIfEnabled(FQCN, Level.DEBUG, marker, msgSupplier, (Throwable) null);
    }

    @Override
    public void debug(final Marker marker, final String message, final Supplier<?>... paramSuppliers) {
        logIfEnabled(FQCN, Level.DEBUG, marker, message, paramSuppliers);
    }

    @Override
    public void debug(final Marker marker, final Supplier<?> msgSupplier, final Throwable t) {
        logIfEnabled(FQCN, Level.DEBUG, marker, msgSupplier, t);
    }

    @Override
    public void debug(final String message, final Supplier<?>... paramSuppliers) {
        logIfEnabled(FQCN, Level.DEBUG, null, message, paramSuppliers);
    }

    @Override
    public void debug(final Marker marker, final MessageSupplier msgSupplier) {
        logIfEnabled(FQCN, Level.DEBUG, marker, msgSupplier, (Throwable) null);
    }

    @Override
    public void debug(final Marker marker, final MessageSupplier msgSupplier, final Throwable t) {
        logIfEnabled(FQCN, Level.DEBUG, marker, msgSupplier, t);
    }

    @Override
    public void debug(final MessageSupplier msgSupplier) {
        logIfEnabled(FQCN, Level.DEBUG, null, msgSupplier, (Throwable) null);
    }

    @Override
    public void debug(final MessageSupplier msgSupplier, final Throwable t) {
        logIfEnabled(FQCN, Level.DEBUG, null, msgSupplier, t);
    }

    @Override
    public void entry() {
        entry(FQCN);
    }

    @Override
    public void entry(final Object... params) {
        entry(FQCN, params);
    }

    /**
     * Logs entry to a method with location information.
     *
     * @param fqcn The fully qualified class name of the caller.
     * @param params The parameters to the method.
     */
    protected void entry(final String fqcn, final Object... params) {
        if (isEnabled(Level.TRACE, ENTRY_MARKER, (Object) null, null)) {
            logIfEnabled(fqcn, Level.TRACE, ENTRY_MARKER, entryMsg(params.length, params), null);
        }
    }

    protected Message entryMsg(final int count, final Object... params) {
        if (count == 0) {
            return messageFactory.newMessage("entry");
        }
        final StringBuilder sb = new StringBuilder("entry params(");
        for (int i = 0; i < params.length; i++) {
            Object parm = params[i];
            sb.append(parm != null ? parm.toString() : "null");
            if (i + 1 < params.length) {
                sb.append(", ");
            }
        }
        sb.append(')');
        return messageFactory.newMessage(sb.toString());
    }

    @Override
    public void error(final Marker marker, final Message msg) {
        logIfEnabled(FQCN, Level.ERROR, marker, msg, null);
    }

    @Override
    public void error(final Marker marker, final Message msg, final Throwable t) {
        logIfEnabled(FQCN, Level.ERROR, marker, msg, t);
    }

    @Override
    public void error(final Marker marker, final Object message) {
        logIfEnabled(FQCN, Level.ERROR, marker, message, null);
    }

    @Override
    public void error(final Marker marker, final Object message, final Throwable t) {
        logIfEnabled(FQCN, Level.ERROR, marker, message, t);
    }

    @Override
    public void error(final Marker marker, final String message) {
        logIfEnabled(FQCN, Level.ERROR, marker, message, (Throwable) null);
    }

    @Override
    public void error(final Marker marker, final String message, final Object... params) {
        logIfEnabled(FQCN, Level.ERROR, marker, message, params);
    }

    @Override
    public void error(final Marker marker, final String message, final Throwable t) {
        logIfEnabled(FQCN, Level.ERROR, marker, message, t);
    }

    @Override
    public void error(final Message msg) {
        logIfEnabled(FQCN, Level.ERROR, null, msg, null);
    }

    @Override
    public void error(final Message msg, final Throwable t) {
        logIfEnabled(FQCN, Level.ERROR, null, msg, t);
    }

    @Override
    public void error(final Object message) {
        logIfEnabled(FQCN, Level.ERROR, null, message, null);
    }

    @Override
    public void error(final Object message, final Throwable t) {
        logIfEnabled(FQCN, Level.ERROR, null, message, t);
    }

    @Override
    public void error(final String message) {
        logIfEnabled(FQCN, Level.ERROR, null, message, (Throwable) null);
    }

    @Override
    public void error(final String message, final Object... params) {
        logIfEnabled(FQCN, Level.ERROR, null, message, params);
    }

    @Override
    public void error(final String message, final Throwable t) {
        logIfEnabled(FQCN, Level.ERROR, null, message, t);
    }

    @Override
    public void error(final Supplier<?> msgSupplier) {
        logIfEnabled(FQCN, Level.ERROR, null, msgSupplier, (Throwable) null);
    }

    @Override
    public void error(final Supplier<?> msgSupplier, final Throwable t) {
        logIfEnabled(FQCN, Level.ERROR, null, msgSupplier, t);
    }

    @Override
    public void error(final Marker marker, final Supplier<?> msgSupplier) {
        logIfEnabled(FQCN, Level.ERROR, marker, msgSupplier, (Throwable) null);
    }

    @Override
    public void error(final Marker marker, final String message, final Supplier<?>... paramSuppliers) {
        logIfEnabled(FQCN, Level.ERROR, marker, message, paramSuppliers);
    }

    @Override
    public void error(final Marker marker, final Supplier<?> msgSupplier, final Throwable t) {
        logIfEnabled(FQCN, Level.ERROR, marker, msgSupplier, t);
    }

    @Override
    public void error(final String message, final Supplier<?>... paramSuppliers) {
        logIfEnabled(FQCN, Level.ERROR, null, message, paramSuppliers);
    }

    @Override
    public void error(final Marker marker, final MessageSupplier msgSupplier) {
        logIfEnabled(FQCN, Level.ERROR, marker, msgSupplier, (Throwable) null);
    }

    @Override
    public void error(final Marker marker, final MessageSupplier msgSupplier, final Throwable t) {
        logIfEnabled(FQCN, Level.ERROR, marker, msgSupplier, t);
    }

    @Override
    public void error(final MessageSupplier msgSupplier) {
        logIfEnabled(FQCN, Level.ERROR, null, msgSupplier, (Throwable) null);
    }

    @Override
    public void error(final MessageSupplier msgSupplier, final Throwable t) {
        logIfEnabled(FQCN, Level.ERROR, null, msgSupplier, t);
    }

    @Override
    public void exit() {
        exit(FQCN, null);
    }

    @Override
    public <R> R exit(final R result) {
        return exit(FQCN, result);
    }

    /**
     * Logs exiting from a method with the result and location information.
     *
     * @param fqcn The fully qualified class name of the caller.
     * @param <R> The type of the parameter and object being returned.
     * @param result The result being returned from the method call.
     * @return the return value passed to this method.
     */
    protected <R> R exit(final String fqcn, final R result) {
        if (isEnabled(Level.TRACE, EXIT_MARKER, (Object) null, null)) {
            logIfEnabled(fqcn, Level.TRACE, EXIT_MARKER, exitMsg(result), null);
        }
        return result;
    }

    protected Message exitMsg(final Object result) {
        if (result == null) {
            return messageFactory.newMessage("exit");
        }
        return messageFactory.newMessage("exit with(" + result + ')');
    }

    @Override
    public void fatal(final Marker marker, final Message msg) {
        logIfEnabled(FQCN, Level.FATAL, marker, msg, null);
    }

    @Override
    public void fatal(final Marker marker, final Message msg, final Throwable t) {
        logIfEnabled(FQCN, Level.FATAL, marker, msg, t);
    }

    @Override
    public void fatal(final Marker marker, final Object message) {
        logIfEnabled(FQCN, Level.FATAL, marker, message, null);
    }

    @Override
    public void fatal(final Marker marker, final Object message, final Throwable t) {
        logIfEnabled(FQCN, Level.FATAL, marker, message, t);
    }

    @Override
    public void fatal(final Marker marker, final String message) {
        logIfEnabled(FQCN, Level.FATAL, marker, message, (Throwable) null);
    }

    @Override
    public void fatal(final Marker marker, final String message, final Object... params) {
        logIfEnabled(FQCN, Level.FATAL, marker, message, params);
    }

    @Override
    public void fatal(final Marker marker, final String message, final Throwable t) {
        logIfEnabled(FQCN, Level.FATAL, marker, message, t);
    }

    @Override
    public void fatal(final Message msg) {
        logIfEnabled(FQCN, Level.FATAL, null, msg, null);
    }

    @Override
    public void fatal(final Message msg, final Throwable t) {
        logIfEnabled(FQCN, Level.FATAL, null, msg, t);
    }

    @Override
    public void fatal(final Object message) {
        logIfEnabled(FQCN, Level.FATAL, null, message, null);
    }

    @Override
    public void fatal(final Object message, final Throwable t) {
        logIfEnabled(FQCN, Level.FATAL, null, message, t);
    }

    @Override
    public void fatal(final String message) {
        logIfEnabled(FQCN, Level.FATAL, null, message, (Throwable) null);
    }

    @Override
    public void fatal(final String message, final Object... params) {
        logIfEnabled(FQCN, Level.FATAL, null, message, params);
    }

    @Override
    public void fatal(final String message, final Throwable t) {
        logIfEnabled(FQCN, Level.FATAL, null, message, t);
    }

    @Override
    public void fatal(final Supplier<?> msgSupplier) {
        logIfEnabled(FQCN, Level.FATAL, null, msgSupplier, (Throwable) null);
    }

    @Override
    public void fatal(final Supplier<?> msgSupplier, final Throwable t) {
        logIfEnabled(FQCN, Level.FATAL, null, msgSupplier, t);
    }

    @Override
    public void fatal(final Marker marker, final Supplier<?> msgSupplier) {
        logIfEnabled(FQCN, Level.FATAL, marker, msgSupplier, (Throwable) null);
    }

    @Override
    public void fatal(final Marker marker, final String message, final Supplier<?>... paramSuppliers) {
        logIfEnabled(FQCN, Level.FATAL, marker, message, paramSuppliers);
    }

    @Override
    public void fatal(final Marker marker, final Supplier<?> msgSupplier, final Throwable t) {
        logIfEnabled(FQCN, Level.FATAL, marker, msgSupplier, t);
    }

    @Override
    public void fatal(final String message, final Supplier<?>... paramSuppliers) {
        logIfEnabled(FQCN, Level.FATAL, null, message, paramSuppliers);
    }

    @Override
    public void fatal(final Marker marker, final MessageSupplier msgSupplier) {
        logIfEnabled(FQCN, Level.FATAL, marker, msgSupplier, (Throwable) null);
    }

    @Override
    public void fatal(final Marker marker, final MessageSupplier msgSupplier, final Throwable t) {
        logIfEnabled(FQCN, Level.FATAL, marker, msgSupplier, t);
    }

    @Override
    public void fatal(final MessageSupplier msgSupplier) {
        logIfEnabled(FQCN, Level.FATAL, null, msgSupplier, (Throwable) null);
    }

    @Override
    public void fatal(final MessageSupplier msgSupplier, final Throwable t) {
        logIfEnabled(FQCN, Level.FATAL, null, msgSupplier, t);
    }

    @Override
    public MessageFactory getMessageFactory() {
        return messageFactory;
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public void info(final Marker marker, final Message msg) {
        logIfEnabled(FQCN, Level.INFO, marker, msg, null);
    }

    @Override
    public void info(final Marker marker, final Message msg, final Throwable t) {
        logIfEnabled(FQCN, Level.INFO, marker, msg, t);
    }

    @Override
    public void info(final Marker marker, final Object message) {
        logIfEnabled(FQCN, Level.INFO, marker, message, null);
    }

    @Override
    public void info(final Marker marker, final Object message, final Throwable t) {
        logIfEnabled(FQCN, Level.INFO, marker, message, t);
    }

    @Override
    public void info(final Marker marker, final String message) {
        logIfEnabled(FQCN, Level.INFO, marker, message, (Throwable) null);
    }

    @Override
    public void info(final Marker marker, final String message, final Object... params) {
        logIfEnabled(FQCN, Level.INFO, marker, message, params);
    }

    @Override
    public void info(final Marker marker, final String message, final Throwable t) {
        logIfEnabled(FQCN, Level.INFO, marker, message, t);
    }

    @Override
    public void info(final Message msg) {
        logIfEnabled(FQCN, Level.INFO, null, msg, null);
    }

    @Override
    public void info(final Message msg, final Throwable t) {
        logIfEnabled(FQCN, Level.INFO, null, msg, t);
    }

    @Override
    public void info(final Object message) {
        logIfEnabled(FQCN, Level.INFO, null, message, null);
    }

    @Override
    public void info(final Object message, final Throwable t) {
        logIfEnabled(FQCN, Level.INFO, null, message, t);
    }

    @Override
    public void info(final String message) {
        logIfEnabled(FQCN, Level.INFO, null, message, (Throwable) null);
    }

    @Override
    public void info(final String message, final Object... params) {
        logIfEnabled(FQCN, Level.INFO, null, message, params);
    }

    @Override
    public void info(final String message, final Throwable t) {
        logIfEnabled(FQCN, Level.INFO, null, message, t);
    }

    @Override
    public void info(final Supplier<?> msgSupplier) {
        logIfEnabled(FQCN, Level.INFO, null, msgSupplier, (Throwable) null);
    }

    @Override
    public void info(final Supplier<?> msgSupplier, final Throwable t) {
        logIfEnabled(FQCN, Level.INFO, null, msgSupplier, t);
    }

    @Override
    public void info(final Marker marker, final Supplier<?> msgSupplier) {
        logIfEnabled(FQCN, Level.INFO, marker, msgSupplier, (Throwable) null);
    }

    @Override
    public void info(final Marker marker, final String message, final Supplier<?>... paramSuppliers) {
        logIfEnabled(FQCN, Level.INFO, marker, message, paramSuppliers);
    }

    @Override
    public void info(final Marker marker, final Supplier<?> msgSupplier, final Throwable t) {
        logIfEnabled(FQCN, Level.INFO, marker, msgSupplier, t);
    }

    @Override
    public void info(final String message, final Supplier<?>... paramSuppliers) {
        logIfEnabled(FQCN, Level.INFO, null, message, paramSuppliers);
    }

    @Override
    public void info(final Marker marker, final MessageSupplier msgSupplier) {
        logIfEnabled(FQCN, Level.INFO, marker, msgSupplier, (Throwable) null);
    }

    @Override
    public void info(final Marker marker, final MessageSupplier msgSupplier, final Throwable t) {
        logIfEnabled(FQCN, Level.INFO, marker, msgSupplier, t);
    }

    @Override
    public void info(final MessageSupplier msgSupplier) {
        logIfEnabled(FQCN, Level.INFO, null, msgSupplier, (Throwable) null);
    }

    @Override
    public void info(final MessageSupplier msgSupplier, final Throwable t) {
        logIfEnabled(FQCN, Level.INFO, null, msgSupplier, t);
    }

    @Override
    public boolean isDebugEnabled() {
        return isEnabled(Level.DEBUG, null, null);
    }

    @Override
    public boolean isDebugEnabled(final Marker marker) {
        return isEnabled(Level.DEBUG, marker, (Object) null, null);
    }

    @Override
    public boolean isEnabled(final Level level) {
        return isEnabled(level, null, (Object) null, null);
    }

    @Override
    public boolean isEnabled(final Level level, final Marker marker) {
        return isEnabled(level, marker, (Object) null, null);
    }

    @Override
    public boolean isErrorEnabled() {
        return isEnabled(Level.ERROR, null, (Object) null, null);
    }

    @Override
    public boolean isErrorEnabled(final Marker marker) {
        return isEnabled(Level.ERROR, marker, (Object) null, null);
    }

    @Override
    public boolean isFatalEnabled() {
        return isEnabled(Level.FATAL, null, (Object) null, null);
    }

    @Override
    public boolean isFatalEnabled(final Marker marker) {
        return isEnabled(Level.FATAL, marker, (Object) null, null);
    }

    @Override
    public boolean isInfoEnabled() {
        return isEnabled(Level.INFO, null, (Object) null, null);
    }

    @Override
    public boolean isInfoEnabled(final Marker marker) {
        return isEnabled(Level.INFO, marker, (Object) null, null);
    }

    @Override
    public boolean isTraceEnabled() {
        return isEnabled(Level.TRACE, null, (Object) null, null);
    }

    @Override
    public boolean isTraceEnabled(final Marker marker) {
        return isEnabled(Level.TRACE, marker, (Object) null, null);
    }

    @Override
    public boolean isWarnEnabled() {
        return isEnabled(Level.WARN, null, (Object) null, null);
    }

    @Override
    public boolean isWarnEnabled(final Marker marker) {
        return isEnabled(Level.WARN, marker, (Object) null, null);
    }

    @Override
    public void log(final Level level, final Marker marker, final Message msg) {
        logIfEnabled(FQCN, level, marker, msg, (Throwable) null);
    }

    @Override
    public void log(final Level level, final Marker marker, final Message msg, final Throwable t) {
        logIfEnabled(FQCN, level, marker, msg, t);
    }

    @Override
    public void log(final Level level, final Marker marker, final Object message) {
        logIfEnabled(FQCN, level, marker, message, (Throwable) null);
    }

    @Override
    public void log(final Level level, final Marker marker, final Object message, final Throwable t) {
        if (isEnabled(level, marker, message, t)) {
            logMessage(FQCN, level, marker, message, t);
        }
    }

    @Override
    public void log(final Level level, final Marker marker, final String message) {
        logIfEnabled(FQCN, level, marker, message, (Throwable) null);
    }

    @Override
    public void log(final Level level, final Marker marker, final String message, final Object... params) {
        logIfEnabled(FQCN, level, marker, message, params);
    }

    @Override
    public void log(final Level level, final Marker marker, final String message, final Throwable t) {
        logIfEnabled(FQCN, level, marker, message, t);
    }

    @Override
    public void log(final Level level, final Message msg) {
        logIfEnabled(FQCN, level, null, msg, null);
    }

    @Override
    public void log(final Level level, final Message msg, final Throwable t) {
        logIfEnabled(FQCN, level, null, msg, t);
    }

    @Override
    public void log(final Level level, final Object message) {
        logIfEnabled(FQCN, level, null, message, null);
    }

    @Override
    public void log(final Level level, final Object message, final Throwable t) {
        logIfEnabled(FQCN, level, null, message, t);
    }

    @Override
    public void log(final Level level, final String message) {
        logIfEnabled(FQCN, level, null, message, (Throwable) null);
    }

    @Override
    public void log(final Level level, final String message, final Object... params) {
        logIfEnabled(FQCN, level, null, message, params);
    }

    @Override
    public void log(final Level level, final String message, final Throwable t) {
        logIfEnabled(FQCN, level, null, message, t);
    }

    @Override
    public void log(final Level level, final Supplier<?> msgSupplier) {
        logIfEnabled(FQCN, level, null, msgSupplier, (Throwable) null);
    }

    @Override
    public void log(final Level level, final Supplier<?> msgSupplier, final Throwable t) {
        logIfEnabled(FQCN, level, null, msgSupplier, t);
    }

    @Override
    public void log(final Level level, final Marker marker, final Supplier<?> msgSupplier) {
        logIfEnabled(FQCN, level, marker, msgSupplier, (Throwable) null);
    }

    @Override
    public void log(final Level level, final Marker marker, final String message, final Supplier<?>... paramSuppliers) {
        logIfEnabled(FQCN, level, marker, message, paramSuppliers);
    }

    @Override
    public void log(final Level level, final Marker marker, final Supplier<?> msgSupplier, final Throwable t) {
        logIfEnabled(FQCN, level, marker, msgSupplier, t);
    }

    @Override
    public void log(final Level level, final String message, final Supplier<?>... paramSuppliers) {
        logIfEnabled(FQCN, level, null, message, paramSuppliers);
    }

    @Override
    public void log(final Level level, final Marker marker, final MessageSupplier msgSupplier) {
        logIfEnabled(FQCN, level, marker, msgSupplier, (Throwable) null);
    }

    @Override
    public void log(final Level level, final Marker marker, final MessageSupplier msgSupplier, final Throwable t) {
        logIfEnabled(FQCN, level, marker, msgSupplier, t);
    }

    @Override
    public void log(final Level level, final MessageSupplier msgSupplier) {
        logIfEnabled(FQCN, level, null, msgSupplier, (Throwable) null);
    }

    @Override
    public void log(final Level level, final MessageSupplier msgSupplier, final Throwable t) {
        logIfEnabled(FQCN, level, null, msgSupplier, t);
    }

    @Override
    public void logIfEnabled(final String fqcn, final Level level, final Marker marker, final Message msg,
            final Throwable t) {
        if (isEnabled(level, marker, msg, t)) {
            logMessage(fqcn, level, marker, msg, t);
        }
    }

    @Override
    public void logIfEnabled(final String fqcn, final Level level, final Marker marker,
            final MessageSupplier msgSupplier, final Throwable t) {
        if (isEnabled(level, marker, msgSupplier, t)) {
            logMessage(fqcn, level, marker, msgSupplier, t);
        }
    }

    @Override
    public void logIfEnabled(final String fqcn, final Level level, final Marker marker, final Object message,
            final Throwable t) {
        if (isEnabled(level, marker, message, t)) {
            logMessage(fqcn, level, marker, message, t);
        }
    }

    @Override
    public void logIfEnabled(final String fqcn, final Level level, final Marker marker, final Supplier<?> msgSupplier,
            final Throwable t) {
        if (isEnabled(level, marker, msgSupplier, t)) {
            logMessage(fqcn, level, marker, msgSupplier, t);
        }
    }

    @Override
    public void logIfEnabled(final String fqcn, final Level level, final Marker marker, final String message) {
        if (isEnabled(level, marker, message)) {
            logMessage(fqcn, level, marker, message);
        }
    }

    @Override
    public void logIfEnabled(final String fqcn, final Level level, final Marker marker, final String message,
            final Supplier<?>... paramSuppliers) {
        if (isEnabled(level, marker, message)) {
            logMessage(fqcn, level, marker, message, paramSuppliers);
        }
    }

    @Override
    public void logIfEnabled(final String fqcn, final Level level, final Marker marker, final String message,
            final Object... params) {
        if (isEnabled(level, marker, message, params)) {
            logMessage(fqcn, level, marker, message, params);
        }
    }

    @Override
    public void logIfEnabled(final String fqcn, final Level level, final Marker marker, final String message,
            final Throwable t) {
        if (isEnabled(level, marker, message, t)) {
            logMessage(fqcn, level, marker, message, t);
        }
    }

    protected void logMessage(final String fqcn, final Level level, final Marker marker, final Object message,
            final Throwable t) {
        logMessage(fqcn, level, marker, messageFactory.newMessage(message), t);
    }

    protected void logMessage(final String fqcn, final Level level, final Marker marker,
            final MessageSupplier msgSupplier, final Throwable t) {
        final Message message = LambdaUtil.get(msgSupplier);
        logMessage(fqcn, level, marker, message, t);
    }

    protected void logMessage(final String fqcn, final Level level, final Marker marker, final Supplier<?> msgSupplier,
            final Throwable t) {
        final Object message = LambdaUtil.get(msgSupplier);
        logMessage(fqcn, level, marker, messageFactory.newMessage(message), t);
    }

    protected void logMessage(final String fqcn, final Level level, final Marker marker, final String message,
            final Throwable t) {
        logMessage(fqcn, level, marker, messageFactory.newMessage(message), t);
    }

    protected void logMessage(final String fqcn, final Level level, final Marker marker, final String message) {
        final Message msg = messageFactory.newMessage(message);
        logMessage(fqcn, level, marker, msg, msg.getThrowable());
    }

    protected void logMessage(final String fqcn, final Level level, final Marker marker, final String message,
            final Object... params) {
        final Message msg = messageFactory.newMessage(message, params);
        logMessage(fqcn, level, marker, msg, msg.getThrowable());
    }

    protected void logMessage(final String fqcn, final Level level, final Marker marker, final String message,
            final Supplier<?>... paramSuppliers) {
        final Message msg = messageFactory.newMessage(message, LambdaUtil.getAll(paramSuppliers));
        logMessage(fqcn, level, marker, msg, msg.getThrowable());
    }

    @Override
    public void printf(final Level level, final Marker marker, final String format, final Object... params) {
        if (isEnabled(level, marker, format, params)) {
            final Message msg = new StringFormattedMessage(format, params);
            logMessage(FQCN, level, marker, msg, msg.getThrowable());
        }
    }

    @Override
    public void printf(final Level level, final String format, final Object... params) {
        if (isEnabled(level, null, format, params)) {
            final Message msg = new StringFormattedMessage(format, params);
            logMessage(FQCN, level, null, msg, msg.getThrowable());
        }
    }

    @Override
    public <T extends Throwable> T throwing(final T t) {
        return throwing(FQCN, Level.ERROR, t);
    }

    @Override
    public <T extends Throwable> T throwing(final Level level, final T t) {
        return throwing(FQCN, level, t);
    }

    /**
     * Logs a Throwable to be thrown.
     *
     * @param <T> the type of the Throwable.
     * @param fqcn the fully qualified class name of this Logger implementation.
     * @param level The logging Level.
     * @param t The Throwable.
     * @return the Throwable.
     */
    protected <T extends Throwable> T throwing(final String fqcn, final Level level, final T t) {
        if (isEnabled(level, THROWING_MARKER, (Object) null, null)) {
            logMessage(fqcn, level, THROWING_MARKER, throwingMsg(t), t);
        }
        return t;
    }

    protected Message throwingMsg(final Throwable t) {
        return messageFactory.newMessage(THROWING);
    }

    @Override
    public void trace(final Marker marker, final Message msg) {
        logIfEnabled(FQCN, Level.TRACE, marker, msg, null);
    }

    @Override
    public void trace(final Marker marker, final Message msg, final Throwable t) {
        logIfEnabled(FQCN, Level.TRACE, marker, msg, t);
    }

    @Override
    public void trace(final Marker marker, final Object message) {
        logIfEnabled(FQCN, Level.TRACE, marker, message, null);
    }

    @Override
    public void trace(final Marker marker, final Object message, final Throwable t) {
        logIfEnabled(FQCN, Level.TRACE, marker, message, t);
    }

    @Override
    public void trace(final Marker marker, final String message) {
        logIfEnabled(FQCN, Level.TRACE, marker, message, (Throwable) null);
    }

    @Override
    public void trace(final Marker marker, final String message, final Object... params) {
        logIfEnabled(FQCN, Level.TRACE, marker, message, params);
    }

    @Override
    public void trace(final Marker marker, final String message, final Throwable t) {
        logIfEnabled(FQCN, Level.TRACE, marker, message, t);
    }

    @Override
    public void trace(final Message msg) {
        logIfEnabled(FQCN, Level.TRACE, null, msg, null);
    }

    @Override
    public void trace(final Message msg, final Throwable t) {
        logIfEnabled(FQCN, Level.TRACE, null, msg, t);
    }

    @Override
    public void trace(final Object message) {
        logIfEnabled(FQCN, Level.TRACE, null, message, null);
    }

    @Override
    public void trace(final Object message, final Throwable t) {
        logIfEnabled(FQCN, Level.TRACE, null, message, t);
    }

    @Override
    public void trace(final String message) {
        logIfEnabled(FQCN, Level.TRACE, null, message, (Throwable) null);
    }

    @Override
    public void trace(final String message, final Object... params) {
        logIfEnabled(FQCN, Level.TRACE, null, message, params);
    }

    @Override
    public void trace(final String message, final Throwable t) {
        logIfEnabled(FQCN, Level.TRACE, null, message, t);
    }

    @Override
    public void trace(final Supplier<?> msgSupplier) {
        logIfEnabled(FQCN, Level.TRACE, null, msgSupplier, (Throwable) null);
    }

    @Override
    public void trace(final Supplier<?> msgSupplier, final Throwable t) {
        logIfEnabled(FQCN, Level.TRACE, null, msgSupplier, t);
    }

    @Override
    public void trace(final Marker marker, final Supplier<?> msgSupplier) {
        logIfEnabled(FQCN, Level.TRACE, marker, msgSupplier, (Throwable) null);
    }

    @Override
    public void trace(final Marker marker, final String message, final Supplier<?>... paramSuppliers) {
        logIfEnabled(FQCN, Level.TRACE, marker, message, paramSuppliers);
    }

    @Override
    public void trace(final Marker marker, final Supplier<?> msgSupplier, final Throwable t) {
        logIfEnabled(FQCN, Level.TRACE, marker, msgSupplier, t);
    }

    @Override
    public void trace(final String message, final Supplier<?>... paramSuppliers) {
        logIfEnabled(FQCN, Level.TRACE, null, message, paramSuppliers);
    }

    @Override
    public void trace(final Marker marker, final MessageSupplier msgSupplier) {
        logIfEnabled(FQCN, Level.TRACE, marker, msgSupplier, (Throwable) null);
    }

    @Override
    public void trace(final Marker marker, final MessageSupplier msgSupplier, final Throwable t) {
        logIfEnabled(FQCN, Level.TRACE, marker, msgSupplier, t);
    }

    @Override
    public void trace(final MessageSupplier msgSupplier) {
        logIfEnabled(FQCN, Level.TRACE, null, msgSupplier, (Throwable) null);
    }

    @Override
    public void trace(final MessageSupplier msgSupplier, final Throwable t) {
        logIfEnabled(FQCN, Level.TRACE, null, msgSupplier, t);
    }

    @Override
    public void warn(final Marker marker, final Message msg) {
        logIfEnabled(FQCN, Level.WARN, marker, msg, null);
    }

    @Override
    public void warn(final Marker marker, final Message msg, final Throwable t) {
        logIfEnabled(FQCN, Level.WARN, marker, msg, t);
    }

    @Override
    public void warn(final Marker marker, final Object message) {
        logIfEnabled(FQCN, Level.WARN, marker, message, null);
    }

    @Override
    public void warn(final Marker marker, final Object message, final Throwable t) {
        logIfEnabled(FQCN, Level.WARN, marker, message, t);
    }

    @Override
    public void warn(final Marker marker, final String message) {
        logIfEnabled(FQCN, Level.WARN, marker, message, (Throwable) null);
    }

    @Override
    public void warn(final Marker marker, final String message, final Object... params) {
        logIfEnabled(FQCN, Level.WARN, marker, message, params);
    }

    @Override
    public void warn(final Marker marker, final String message, final Throwable t) {
        logIfEnabled(FQCN, Level.WARN, marker, message, t);
    }

    @Override
    public void warn(final Message msg) {
        logIfEnabled(FQCN, Level.WARN, null, msg, null);
    }

    @Override
    public void warn(final Message msg, final Throwable t) {
        logIfEnabled(FQCN, Level.WARN, null, msg, t);
    }

    @Override
    public void warn(final Object message) {
        logIfEnabled(FQCN, Level.WARN, null, message, null);
    }

    @Override
    public void warn(final Object message, final Throwable t) {
        logIfEnabled(FQCN, Level.WARN, null, message, t);
    }

    @Override
    public void warn(final String message) {
        logIfEnabled(FQCN, Level.WARN, null, message, (Throwable) null);
    }

    @Override
    public void warn(final String message, final Object... params) {
        logIfEnabled(FQCN, Level.WARN, null, message, params);
    }

    @Override
    public void warn(final String message, final Throwable t) {
        logIfEnabled(FQCN, Level.WARN, null, message, t);
    }

    @Override
    public void warn(final Supplier<?> msgSupplier) {
        logIfEnabled(FQCN, Level.WARN, null, msgSupplier, (Throwable) null);
    }

    @Override
    public void warn(final Supplier<?> msgSupplier, final Throwable t) {
        logIfEnabled(FQCN, Level.WARN, null, msgSupplier, t);
    }

    @Override
    public void warn(final Marker marker, final Supplier<?> msgSupplier) {
        logIfEnabled(FQCN, Level.WARN, marker, msgSupplier, (Throwable) null);
    }

    @Override
    public void warn(final Marker marker, final String message, final Supplier<?>... paramSuppliers) {
        logIfEnabled(FQCN, Level.WARN, marker, message, paramSuppliers);
    }

    @Override
    public void warn(final Marker marker, final Supplier<?> msgSupplier, final Throwable t) {
        logIfEnabled(FQCN, Level.WARN, marker, msgSupplier, t);
    }

    @Override
    public void warn(final String message, final Supplier<?>... paramSuppliers) {
        logIfEnabled(FQCN, Level.WARN, null, message, paramSuppliers);
    }

    @Override
    public void warn(final Marker marker, final MessageSupplier msgSupplier) {
        logIfEnabled(FQCN, Level.WARN, marker, msgSupplier, (Throwable) null);
    }

    @Override
    public void warn(final Marker marker, final MessageSupplier msgSupplier, final Throwable t) {
        logIfEnabled(FQCN, Level.WARN, marker, msgSupplier, t);
    }

    @Override
    public void warn(final MessageSupplier msgSupplier) {
        logIfEnabled(FQCN, Level.WARN, null, msgSupplier, (Throwable) null);
    }

    @Override
    public void warn(final MessageSupplier msgSupplier, final Throwable t) {
        logIfEnabled(FQCN, Level.WARN, null, msgSupplier, t);
    }
}


text:
"""Tests admin-related functionality"""

import os

import pytest

import python_pachyderm
from python_pachyderm.errors import AuthServiceNotActivated
from python_pachyderm.service import auth_proto, identity_proto
from tests import util

@pytest.fixture
def client():
    pc = python_pachyderm.Client()
    pc.activate_license(os.environ["PACH_PYTHON_ENTERPRISE_CODE"])
    pc.add_cluster("localhost", "localhost:1650", secret="secret")
    pc.activate_enterprise("localhost:1650", "localhost", "secret")

    pc.auth_token = "iamroot"
    pc.activate_auth(pc.auth_token)
    pc.set_identity_server_config(
        config=identity_proto.IdentityServerConfig(issuer="http://localhost:1658")
    )
    yield pc
    # not redundant because auth_token could be overriden by tests
    pc.auth_token = "iamroot"
    pc.delete_all()
    pc.deactivate_enterprise()

@util.skip_if_no_enterprise()
def test_auth_configuration(client):
    client.get_auth_configuration()
    client.set_auth_configuration(
        auth_proto.OIDCConfig(
            issuer="http://localhost:1658",
            client_id="client",
            client_secret="secret",
            redirect_uri="http://test.example.com",
        )
    )

@util.skip_if_no_enterprise()
def test_cluster_role_bindings(client):
    cluster_resource = auth_proto.Resource(type=auth_proto.CLUSTER)
    binding = client.get_role_binding(cluster_resource)
    assert binding["pach:root"].roles["clusterAdmin"]
    client.modify_role_binding(
        cluster_resource, "robot:someuser", roles=["clusterAdmin"]
    )

    binding = client.get_role_binding(cluster_resource)
    assert binding["robot:someuser"].roles["clusterAdmin"]

@util.skip_if_no_enterprise()
def test_authorize(client):
    client.authorize(
        auth_proto.Resource(type=auth_proto.REPO, name="foobar"),
        [auth_proto.Permission.REPO_READ],
    )

@util.skip_if_no_enterprise()
def test_who_am_i(client):
    assert client.who_am_i().username == "pach:root"

@util.skip_if_no_enterprise()
def test_get_roles_for_permission(client):
    # Checks built-in roles
    roles = client.get_roles_for_permission(auth_proto.Permission.REPO_READ)
    for r in roles:
        assert auth_proto.Permission.REPO_READ in r.permissions

    roles = client.get_roles_for_permission(
        auth_proto.Permission.CLUSTER_GET_PACHD_LOGS
    )
    for r in roles:
        assert auth_proto.Permission.CLUSTER_GET_PACHD_LOGS in r.permissions

@util.skip_if_no_enterprise()
def test_robot_token(client):
    auth_token = client.get_robot_token("robot:root", ttl=30)
    client.auth_token = auth_token
    assert client.who_am_i().username == "robot:root"
    client.revoke_auth_token(auth_token)
    with pytest.raises(python_pachyderm.RpcError):
        client.who_am_i()

@util.skip_if_no_enterprise()
def test_groups(client):
    assert client.get_groups() == []
    client.set_groups_for_user("pach:root", ["foogroup"])
    assert client.get_groups() == ["foogroup"]
    assert client.get_users("foogroup") == ["pach:root"]
    client.modify_members("foogroup", remove=["pach:root"])
    assert client.get_groups() == []
    assert client.get_users("foogroup") == []

def test_deactivate_error():
    """Test that calling AuthMixin.deactivate_auth returns a custom error
    if auth has not been activated."""
    client = python_pachyderm.Client()
    with pytest.raises(AuthServiceNotActivated):
        client.deactivate_auth()

redpajama_set_name: RedPajamaGithub


text:
var assert = require('assert'),
  RateLimiter = require('../index'),
  Redis = require('ioredis');

var ID = 'testlimiter',
  LIMIT = 10,
  DURATION = 30000;

var redisClient = new Redis();

describe('Setup', function () {
  var limiter;

  it('should not be possible to initialize w/out options', function (done) {
    try {
      var limiter = new RateLimiter();
      throw new Error('Ratelimit doesn\'t throw any error');

    } catch (e) {
      if (e instanceof assert.AssertionError) {
        done();
      }
    }
  });

  it('should intialize new limiter', function (done) {
    limiter = new RateLimiter({
      id: ID,
      limit: LIMIT,
      duration: DURATION
    }, redisClient);

    assert.strictEqual(limiter.limit, LIMIT);
    assert.strictEqual(limiter.remaining, 0);

    done();
  });
});

describe('API', function () {
  var limiter;

  function clearRedis(done) {
    redisClient.keys('ratelimit:*', function (err, keys) {
      if (err) {
        return done(err);
      }

      if (!keys.length) {
        return done();
      }

      redisClient.del.apply(redisClient, keys.concat(done));
    });
  }

  it('cleaning redis...', function (done) {
    clearRedis(done);

    limiter = new RateLimiter({
      id: ID,
      limit: LIMIT,
      duration: DURATION
    }, redisClient);
  });

  describe('.get()', function () {
    it('should decrement .remaining on each call (calling LIMIT-1 times)', function (done) {
      var i = 0,
        max = LIMIT - 1;

      next();

      function next() {
        i++;

        if (i > max) {
          return done();
        }

        limiter.get(function (err, limit, remaining, reset) {
          assert.strictEqual(err, undefined);
          assert.strictEqual(limit, LIMIT);
          assert.strictEqual(remaining, LIMIT - i);
          assert(reset instanceof Date, '.reset should be a Date');
          assert(reset.getTime() >= (new Date().getTime() + DURATION - 500), 'incorrect .reset');
          next();
        });
      }
    });

    it('should return .remaining === 0', function (done) {
      limiter.get(function (err, limit, remaining, reset) {
        assert.strictEqual(err, undefined);
        assert.strictEqual(limit, LIMIT);
        assert.strictEqual(remaining, 0);
        assert(reset instanceof Date, '.reset should be a Date');
        assert(reset.getTime() >= (new Date().getTime() + DURATION - 500), 'incorrect .reset');
        done();
      });
    });

    it('should return .remaining === -1', function (done) {
      limiter.get(function (err, limit, remaining, reset) {
        assert.strictEqual(err, undefined);
        assert.strictEqual(limit, LIMIT);
        assert.strictEqual(remaining, -1);
        assert(reset instanceof Date, '.reset should be a Date');
        assert(reset.getTime() >= (new Date().getTime() + DURATION - 500), 'incorrect .reset');
        done();
      });
    });
  });

  it('cleaning redis...', function (done) {
    clearRedis(done);

    limiter = new RateLimiter({
      id: ID,
      limit: LIMIT,
      duration: 500
    }, redisClient);
  });

  describe('.reset', function () {
    it('should decrement .remaining', function (done) {
      limiter.get(function (err, limit, remaining, reset) {
        assert.strictEqual(err, undefined);
        assert.strictEqual(remaining, LIMIT - 1);
        done();
      });
    });

    it('should reset .remaining after timeout', function (done) {
      setTimeout(function () {
        limiter.get(function (err, limit, remaining, reset) {
          assert.strictEqual(err, undefined);
          assert.strictEqual(limit, LIMIT);
          assert.strictEqual(remaining, LIMIT - 1);
          assert(reset instanceof Date, '.reset should be a Date');
          assert(reset.getTime() < (new Date().getTime() + DURATION), 'incorrect .reset');
          done();
        });
      }, 600);
    });
  });
});


text:
package jigg.util

import ucar.nc2.{Attribute, Group, NetcdfFile}

class HDF5Object(rootGroup: Group) {

  def checkAndGetAttribute(name: String): Attribute = Option(rootGroup.findAttribute(name)) match {
    case Some(x) => x
    case None => throw new IllegalArgumentException("cannot get " + name + " attribute from input model file")
  }

  def checkAndGetGroup(name: String): Group = Option(rootGroup.findGroup(name)) match {
    case Some(x) => x
    case None => throw new IllegalArgumentException("cannot get " + name + " group from input model file")
  }

}

object HDF5Object {

  // Load from a path on the file system
  def fromFile(path: String): HDF5Object =  {
    val file = NetcdfFile.open(path, null)
    mkObj(file)
  }

  // Load from class loader
  def fromResource(path: String): HDF5Object = {
    val file =
      NetcdfFile.openInMemory(IOUtil.findResource(path).toURI)
    mkObj(file)
  }

  private def mkObj(file: NetcdfFile) = {
    val group = file.getRootGroup
    new HDF5Object(group)
  }
}


text:
package com.lostofthought.mup.curse;

import com.lostofthought.mup.Category;
import com.lostofthought.mup.Config;
import com.lostofthought.mup.Mod;
import com.lostofthought.mup.ModFile;
import com.lostofthought.mup.curse.soap.request.GetAddOnDescription;
import com.lostofthought.mup.curse.soap.request.GetAddOns;
import com.lostofthought.mup.curse.soap.response.GetAddOnResponse;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
import com.thoughtworks.xstream.annotations.XStreamOmitField;

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

/**
 * Created by LostOfThought on 10/25/2016.
 */

@XStreamAlias("CurseMod")
public class CurseMod extends Mod{
    @XStreamOmitField
    private GetAddOnResponse r;

    @XStreamAlias("ID")
    @XStreamAsAttribute
    private int curseId;

    public CurseMod(String id){
        curseId = Integer.parseInt(id, 10);
        this.r = new GetAddOns().Execute(Config.GetActiveSession(), Collections.singletonList(id)).get(0);
        this.Initialize();
    }

    @Override
    public String Name() {
        if (this.name == null){
            this.name = r.Name();
        }
        return this.name;
    }

    @Override
    public String Description() {
        if (this.description == null){
            this.description = r.Summary();
        }
        return this.description;
    }

    @Override
    public String DescriptionLong() {
        if (this.descriptionLong == null){
            this.descriptionLong = new GetAddOnDescription().Execute(Config.GetActiveSession(), String.valueOf(curseId)).Description();
        }
        return this.descriptionLong;
    }

    @Override
    public List<String> Authors() {
        if (this.authors != null){
            return this.authors;
        }
        this.authors = new ArrayList<String>();
        for (GetAddOnResponse.AddOnAuthor a : r.Authors()){
            this.authors.add(a.Name);
        }
        return this.authors;
    }

    @Override
    public String Copyright() {
        return "//TODO:"; //TODO: Implement, not worth throwing an exception for though.
    }

    @Override
    public String Homepage() {
        if (this.homepage == null){
            this.homepage = r.ExternalUrl();
        }
        return this.homepage;
    }

    @Override
    public List<ModFile> Files(){
        if (this.files != null){
            return this.files;
        }
        this.files = CurseModFile.FromMod(this);

        return this.files;
    }

    @Override
    public List<Category> Categories() {
        return null; //TODO: Implement, not worth throwing an exception for though.
    }

    public int CurseID() {
        return this.curseId;
    }
}


text:
"use strict";Object.defineProperty(exports, "__esModule", { value: true });exports.registerAuthenticationRequiredCallback = registerAuthenticationRequiredCallback;exports.unregisterAuthenticationRequiredCallback = unregisterAuthenticationRequiredCallback;exports.default = void 0;

var _Card = _interopRequireDefault(require("@material-ui/core/Card"));

var _CardContent = _interopRequireDefault(require("@material-ui/core/CardContent"));

var _CardHeader = _interopRequireDefault(require("@material-ui/core/CardHeader"));

var _styles = require("@material-ui/core/styles");

var _react = _interopRequireDefault(require("react"));

var _Typography = _interopRequireDefault(require("@material-ui/core/Typography"));

var _ResponsiveContentArea = _interopRequireDefault(require("../../rb-appbase-webapp/components/ResponsiveContentArea"));function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { default: obj };}

const doNothing = () => {};

let authenticationRequiredCallback = doNothing;

function registerAuthenticationRequiredCallback(cb) {
  authenticationRequiredCallback = cb;
}

function unregisterAuthenticationRequiredCallback() {
  authenticationRequiredCallback = doNothing;
}

const styles = theme => ({
  card: {
    maxWidth: 400 } });

class RequiresAuthenticationNotice extends _react.default.Component

{
  componentDidMount() {
    authenticationRequiredCallback();
  }

  render() {
    const { classes } = this.props;

    return (
      _react.default.createElement(_ResponsiveContentArea.default, null,
      _react.default.createElement(_Card.default, { className: classes.card },
      _react.default.createElement(_CardHeader.default, { title: "Please log in" }),
      _react.default.createElement(_CardContent.default, null,
      _react.default.createElement(_Typography.default, { paragraph: true }, "Accessing this area of the application requires you to be logged in.")))));

  }}var _default =

(0, _styles.withStyles)(styles)(RequiresAuthenticationNotice);exports.default = _default;
//# sourceMappingURL=RequiresAuthentication.js.map


text:
layout: docs
title: Views
permalink: /docs/views/
---

# Views

Sugar features a number of ways to render views, including both HTML (via EEx) and JSON.

## EEx

Sugar - more specifically, the `Sugar.Controller` module - ships with a `render/4` function that will automatically render a specified EEx template to the specified connection when called.  For example, in your application's main controller:

```elixir
defmodule YourProject.Controllers.Main do
  use Sugar.Controller

  def index do
    conn |> render(:index)
  end
end
```

The above will cause Sugar to render and send an EEx template located in `lib/your_project/views/main/index.html.eex` (you can configure this in your `config.exs`, however; just set the `:sugar, :views_dir` key to whatever tickles your fancy).  In fact, you don't even need to specify which template to render; as long as you're using standard RESTful template names in the right locations, Sugar will happily guess which template to render based on your controller module's name and the method called, like so:

```elixir
  def index do
    # will render `lib/your_project/views/main/index.html.eex`
    conn |> render
  end
```

What if you want to pass some arguments to the template, though?  Well, you can do that, too:

```elixir
  def show(params) do
    conn |> render(:show, [foo: find_a_foo(params[:id])])
  end
```

## Calliope

`render/4` (as described above) will actually detect and process Haml documents with Calliope if they exist.  Thus, if Haml is more your thing, you can use the same exact code as described above for EEx templates while using Haml templates in `lib/your_project/views/#{your_controller}` and it'll work perfectly!

## Static files

If you have any HTML files that aren't templated in any way, Sugar will gladly find and send them.  Just use the `static/2` function, like so:

```elixir
  def index do
    conn |> static("index.html")
  end
```

`static/2` looks in the `priv/static` folder of your project's source code.  You can also use `Plug.Static` in your router to serve an entire folder of static files, like so:

```elixir
defmodule YourProject.Router do
  ...
  plug Plug.Static, at: "/static", from: :your_project
end
```

The above will make any files in your app's `priv/static` folder accessible to clients via the `/static` path (so, the file `priv/static/my_style.css` could be accessed from `/static/my_style.css`).  For more details on how to use `Plug.Static`, see [Plug's documentation site](http://hexdocs.pm/plug/Plug.Static.html).

## JSON

Sugar has built-in support for rendering JSON representations of things using the `json/2` function.  For example:

```elixir
defmodule YourProject.Controllers.Main do
  use Sugar.Controller

  def show_json(params) do
  # outputs `{foo: "This is foo.", bar: "This is bar."}`
    conn |> json([foo: "This is foo.", bar: "This is bar."])
  end
end
```


text:
<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of DataModelDataViewModel
 *
 * @author nemo
 */
class DataModelDataViewModel extends CommonViewModel {

    protected $viewFields = array(
        "DataModelData" => array("*", "_type"=>"left"),
        "DataModel" => array("name" => "model_name",  "_on"=>"DataModel.id=DataModelData.model_id", "_type"=>"left"),
        "DataModelFields" => array("display_name", "field_name ", "extra_data", "_on"=>"DataModelData.field_id=DataModelFields.id", "_type"=>"left")
    );

    /**
     * 包含模型数据
     * @param $sourceData 源多条数据
     * @param $modelDataIds 所有包含的模型ID
     * @param $modelAlias
     */
    public function assignModelData($sourceData, $modelDataIds = false) {

        $modelData = array();

        //无model data id时
        if(!$modelDataIds or $modelDataIds === "product") {
            $modelDataIds = array();
            foreach($sourceData as $k=>$v) {
                if($v["factory_code_all"]) {
                    $tmp = explode(DBC("goods.unique.separator"), $v["factory_code_all"]); //根据factory_code_all factory_code - standard - version
                    $factory_code = array_shift($tmp);
                    $modelDataIds = array_merge($modelDataIds, $tmp);
                    $sourceData[$k]["modelIds"] = $tmp;
                }
            }
        //model data id为product modelAlias时
        } else if(!is_array($modelDataIds)) {
            // $modelDataIds为模型alias
            $dataModelObject = D("DataModel");
            $theDataModel = $dataModelObject->getByAlias($modelDataIds);

            foreach($sourceData as $v) {
                $sourceIds[$v["id"]] = $v["id"];
            }

            $tmp  = $this->where(array(
                "model_id" => $theDataModel["id"],
                "source_id" => array("IN", implode(",", $sourceIds))
            ))->select();

            $modelDataIdsQueryd = array();
            foreach($tmp as $v) {
                $modelDataIdsQueryd[$v["source_id"]][] = $v["id"];
                $modelData[$v["id"]] = $v;
            }

            foreach($sourceData as $k=>$v) {
                $sourceData[$k]["modelIds"] = $modelDataIdsQueryd[$v["id"]];
            }

            $modelDataIds = $modelDataIdsQueryd;
        }

        if(empty($modelDataIds)) {
            return $sourceData;
        }

        if(!$modelData) {

            $tmp = $this->where(array(
                "id" => array("IN", implode(",", $modelDataIds))
            ))->select();

            foreach($tmp as $v) {
                $modelData[$v["id"]] = $v;
            }
        }

        foreach($sourceData as $k=>$v) {
            if(!$v["modelIds"]) {
                continue;
            }
            foreach($v["modelIds"] as $mid) {
                $fieldConf = explode("\n", $modelData[$mid]["extra_data"]);
                if(in_array("bindToLabel::true", $fieldConf)) {
                    $sourceData[$k][$modelData[$mid]["field_name"]] = $mid;
                    $sourceData[$k][$modelData[$mid]["field_name"]."_label"] = $modelData[$mid]["data"];
                } else {
                    $sourceData[$k][$modelData[$mid]["field_name"]] = $modelData[$mid]["data"];
                }

            }
        }

        return $sourceData;
    }

}


text:
r"""Models for storing schemas and data related to user defined Grades.

Grade
    \____ GradeType
                \_______grade_field_1____option_1
                 \                   \___option_2
                  \                   \__option_3
                   \____grade_field_2
                                  \______option_1
                                   \_.....

Then a Grade has serveral GradeEntries of type GradeFieldType_i

Grade
    \___grade_entry_1
    \___grade_entry_2
    \_...

The Grade object needs to grade something.  It is meant to be subclassed
in the models.py file of the app that needs grading, with the
ObjectGrade(Grade) subclass having a foreign key pointing to the object
of the grade.
"""
from django.db import models
from django.contrib.auth.models import User

# Create your models here.
class Grade(models.Model):
    """Grade assigned to an eyelid/patient by a User."""

    user = models.ForeignKey(User)
    grade_type = models.ForeignKey('grade.GradeType')

class GradeEntry(models.Model):
    """Each grade has a variable number of entries determined by its type.

    This table will store the actual data generated by the user when
    grading patients.
    """

    grade = models.ForeignKey('grade.Grade')
    grade_field_type = models.ForeignKey('grade.GradeField')
    value = models.CharField(max_length=100)

    class Meta:
        verbose_name_plural = 'grade_entries'

    def save(self, *args, **kwargs):
        """Ensure that GradeEntries with valid values can be saved."""
        if self.value in self._valid_values():
            super(GradeEntry, self).save(*args, **kwargs)
        else:
            raise ValueError(
                'Value {} is not a valid option.'.format(self.value)
            )

    def _valid_values(self):
        """Get the possible values for this GradeEntry."""
        options = self.grade_field_type.option_set.all()
        return [o.value for o in options]

class GradeType(models.Model):
    """User defined grade type.

    An (admin) user can create a new kind of question to assign to a group
    of patients in a Study.

    Once a Study has a GradeType "+added" to it, Grade forms will be generated
    for each patient displayed in that study.
    """

    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name

class GradeField(models.Model):
    """Defies a field for GradeType, and has many Option objects FK'd."""

    field_name = models.CharField(
        max_length=100,
        verbose_name=('Name'),
    )

    description = models.CharField(
        max_length=100,
        blank=True,
        null=True,
    )
    grade_type = models.ForeignKey('grade.GradeType')

    def __unicode__(self):
        return '{0}'.format(self.field_name)

class Option(models.Model):
    """An element of a set of options for a grading field type.

    E.g. The grade field type "Follicles Present" has 4 options:
        1) definitely not
        2) probably not
        3) probably yes
        4) definitely yes
    which will determine the possible values of GradeEntries for this
    GradeField when a User generates an actual grade.
    """

    grade_field = models.ForeignKey('grade.GradeField')
    value = models.CharField(max_length=100)

    def __unicode__(self):
        return '{0}'.format(self.value)

def create_grade_field_with_options(
    grade_field_name,
    description,
    grade_type,
    options
):
    """Create a grade field for a given type with given options (strings).

    This is a convenience function that takes care of creating all the Option
    objects for a given grade field.
    """
    grade_field = GradeField(
        field_name=grade_field_name,
        description=description,
        grade_type=grade_type
    )
    grade_field.save()
    for opt in options:
        Option(grade_field=grade_field, value=opt).save()

    return grade_field


text:
<?php

// ensure this file is being included by a parent file
if ( ! ( defined( '_VALID_CB' ) || defined( '_JEXEC' ) || defined( '_VALID_MOS' ) ) ) { die( 'Direct Access to this location is not allowed.' ); }

// Auto-load and initialize everything that was in here:
/** @see CB\Legacy\LegacyComprofilerFunctions */

\CBLib\Application\Application::DI()->get( 'CB\Legacy\LegacyComprofilerFunctions' );

/**
 * The classes that were in here have moved to libraries/CBLib/CB/Legacy folder.
 * The functions in here have moved to libraries/CBLib/CB/Legacy/LegacyComprofilerFunctions.php
 */


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:security="http://www.springframework.org/schema/security"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
		http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/security
		http://www.springframework.org/schema/security/spring-security.xsd">

	<security:http>
 		<security:form-login login-page="/login" default-target-url="/secret" authentication-failure-url="/login?failed"
							 username-parameter="j_username" password-parameter="j_password" />
		<security:logout logout-success-url="/" />
		<security:intercept-url pattern="/secret" access="ROLE_ADMIN" />
	</security:http>

</beans>


text:
layout: post
title: "C# Bir Windows Service'in Durumunu Belirlemek"
date: 2010-09-02 16:07
author: engin.polat
comments: true
category: [C#]
tags: [constructor, continuepending, displayname, machinename, paused, pausepending, running, service, servicecontroller, servicecontrollerstatus, servicename, serviceprocess, startpending, status, stopped, stoppending, windows service]
---
Bir **Windows Service**'ine bağımlı uygulama geliştirdiğiniz zaman, ilgili **Windows Service**'in *durumunu belirlemek* kritik öneme sahip oluyor. **Service**, uygulamamızı destekleyen, kendi geliştirdiğimiz bir service olabileceği gibi, Windows ile birlikte gelen service'lerden biri de olabilir.

**ServiceController Sınıfı**

ServiceController sınıfı, System.ServiceProcess namespace'inde yer alır. *Lokal makinadaki* veya *Uzak makinadaki* bir **windows service**'ini temsil eder, ilgili service'in **sorgulanmasına** ve çeşitli özelliklerinin **değiştirilmesine** izin verir.

**ServiceController Sınıfının Kullanımı**

*ServiceController* sınıfını projelerimizde kullanabilmek için, projemize *System.ServiceProcess.dll* dosyasını referans olarak eklemeliyiz.

Daha sonra, kodumuzun using kısmına **System.ServiceProcess** eklemeliyiz;

using System.ServiceProcess;

**Lokal makinadaki bir service'in durumunu belirleme**
Lokal makinadaki bir service'in durumunu belirlemek için, öncelikle *ServiceController* sınıfından yeni bir örnek oluşturmamız lazım.

Sordulamak istediğimiz windows servis'i ile değişkenimizi ilişkilendirmek için kullanabileceğimiz üç yöntem var.

*   **ServiceName** özelliği
*   **DisplayName** özelliği
*   ServiceController **constructor**'ı

Örnek olarak *Print Spooler* servisini sorgulamak için;

ServiceController ServiceByServiceName = new ServiceController();
ServiceByServiceName.ServiceName = "Spooler";

ServiceController ServiceByDisplayName = new ServiceController();
ServiceByDisplayName.DisplayName = "Print Spooler";

ServiceController ServiceByConstructor = new ServiceController("Spooler");

Yukarıdaki kodda görebileceğiniz gibi **ServiceController** sınıfımızı tanımladıktan sonra, Status özelliğini kullanarak, servis'in durum bilgisini sorgulayabiliriz.

**Status** özelliği ServiceControllerStatus enum tipinde değer döndürür;

*   **ContinuePending: **Servis durdurulmuş ve başlatılıyor
*   **Paused: **Servis durdurulmuş
*   **PausePending: **Servis durduruluyor
*   **Running: **Servis çalışıyor
*   **StartPending: **Servis başlatılıyor
*   **Stopped: **Servis çalışmıyor
*   **StopPending: **Servis durduruluyor

Servis'in çalıştığı durumu kontrol etmek için kodumuzu aşağıdaki gibi yazabiliriz;

ServiceController sc = new ServiceController("Spooler");

if (sc.Status == ServiceControllerStatus.Running)
{
    MessageBox.Show("Servis çalışıyor");
}

*Not: Servis durumunu sorgulayan uygulamayı çalıştıran kullanıcının yeterli yetkisi bulunmalıdır. Aksi taktirde bir hata fırlatılacaktır.*

**Uzak makinadaki bir service'in durumunu belirleme**

*Uzak makinadaki* bir service'in durumunu belirleme, *lokal makinadaki* service'in durumunu belirlemek kadar kolaydır. Tek yapmamız gereken MachineName özelliğine uzak makinanın adresini girmek.

Uzak makinadaki *Print Spooler* servisini sorgulamak istediğimizde;

ServiceController sc = new ServiceController("Spooler", "UzakSunucu");

if (sc.Status == ServiceControllerStatus.Running)
{
    MessageBox.Show("Servis çalışıyor");
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;

namespace Taro.Transports.InProcess
{
    public class HandlerMethod
    {
        private MethodInfo _methodInfo;
        private Action<object, object> _invoke;

        public string Name
        {
            get { return _methodInfo.Name; }
        }

        public Type ReflectedType
        {
            get { return _methodInfo.ReflectedType; }
        }

        public HandlerMethod(MethodInfo methodInfo)
        {
            _methodInfo = methodInfo;
            CompileInvoker();
        }

        private void CompileInvoker()
        {
            var instance = Expression.Parameter(typeof(object));
            var theEvent = Expression.Parameter(typeof(object));

            var handlerType = _methodInfo.ReflectedType;
            var eventType = _methodInfo.GetParameters()[0].ParameterType;

            _invoke = Expression.Lambda<Action<object, object>>(
                Expression.Call(Expression.TypeAs(instance, handlerType), _methodInfo, Expression.TypeAs(theEvent, eventType)), instance, theEvent).Compile();
        }

        public void Invoke(object handlerInstance, IEvent theEvent)
        {
            _invoke(handlerInstance, theEvent);
        }
    }
}


text:
const DeleteSubscriptionsResponse_Schema = {
    name: "DeleteSubscriptionsResponse",
    fields: [
        { name: "responseHeader", fieldType: "ResponseHeader" },
        { name: "results", isArray: true, fieldType: "StatusCode"     },
        { name: "diagnosticInfos", isArray: true, fieldType: "DiagnosticInfo" }
    ]
};
export {DeleteSubscriptionsResponse_Schema};


text:
package freemarker.core;

import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

/**
 * A reference to a top-level variable
 */
final class Identifier extends Expression {

    private final String name;

    Identifier(String name) {
        this.name = name;
    }

    TemplateModel _eval(Environment env) throws TemplateException {
        try {
            return env.getVariable(name);
        } catch (NullPointerException e) {
            if (env == null) {
                throw new _MiscTemplateException(new Object[] {
                        "Variables are not available (certainly you are in a parse-time executed directive). "
                        + "The name of the variable you tried to read: ", name });
            } else {
                throw e;
            }
        }
    }

    public String toString() {
        return name;
    }

    public String getCanonicalForm() {
        return name;
    }

    String getName() {
        return name;
    }

    String getNodeTypeSymbol() {
        return getCanonicalForm();
    }

    boolean isLiteral() {
        return false;
    }

    int getParameterCount() {
        return 0;
    }

    Object getParameterValue(int idx) {
        throw new IndexOutOfBoundsException();
    }

    ParameterRole getParameterRole(int idx) {
        throw new IndexOutOfBoundsException();
    }

    protected Expression deepCloneWithIdentifierReplaced_inner(
            String replacedIdentifier, Expression replacement, ReplacemenetState replacementState) {
        if(this.name.equals(replacedIdentifier)) {
            if (replacementState.replacementAlreadyInUse) {
                Expression clone = replacement.deepCloneWithIdentifierReplaced(null, null, replacementState);
                clone.copyLocationFrom(replacement);
                return clone;
            } else {
                replacementState.replacementAlreadyInUse = true;
                return replacement;
            }
        } else {
            return new Identifier(this.name);
        }
    }

}


text:
<component name="libraryTable">
  <library name="kotlin-test" type="repository">
    <properties maven-id="org.jetbrains.kotlin:kotlin-test:1.6.10">
      <exclude>
        <dependency maven-id="org.jetbrains.kotlin:kotlin-stdlib-common" />
        <dependency maven-id="org.jetbrains.kotlin:kotlin-stdlib" />
      </exclude>
    </properties>
    <CLASSES>
      <root url="jar://$MAVEN_REPOSITORY$/org/jetbrains/kotlin/kotlin-test/1.6.10/kotlin-test-1.6.10.jar!/" />
    </CLASSES>
    <JAVADOC />
    <SOURCES>
      <root url="jar://$MAVEN_REPOSITORY$/org/jetbrains/kotlin/kotlin-test/1.6.10/kotlin-test-1.6.10-sources.jar!/" />
    </SOURCES>
  </library>
</component>


text:
Set-StrictMode -version 2.0
$ErrorActionPreference="Stop"

try {
    . (Join-Path $PSScriptRoot "build-utils.ps1")
    $p = Get-VisualStudioDir
    Write-Host (Join-Path $p "Common7\Tools\")
}
catch {
  Write-Error $_.Exception.Message
  # Return an empty string and let the caller fallback or handle this as appropriate
  return ""
}


text:
import { Component, ElementRef, IterableDiffers, Optional, KeyValueDiffers, ChangeDetectorRef, Renderer2 } from '@angular/core';
import { IgEditorBase } from './igeditorbase';
import { NgModel } from '@angular/forms';

@Component({
    selector: 'ig-text-editor',
    template: '<ng-content></ng-content>',
    inputs: ['widgetId', 'options', 'changeDetectionInterval', 'disabled', 'create', 'width', 'height', 'value', 'tabIndex', 'allowNullValue', 'nullValue', 'inputName', 'readOnly', 'validatorOptions', 'buttonType', 'listItems', 'listWidth', 'listItemHoverDuration', 'dropDownAttachedToBody', 'dropDownAnimationDuration', 'visibleItemsCount', 'includeKeys', 'excludeKeys', 'textAlign', 'placeHolder', 'selectionOnFocus', 'textMode', 'spinWrapAround', 'isLimitedToListValues', 'revertIfNotValid', 'preventSubmitOnEnter', 'dropDownOrientation', 'maxLength', 'dropDownOnReadOnly', 'toUpper', 'toLower', 'locale', 'suppressNotifications'],
    outputs: ['rendering', 'rendered', 'mousedown', 'mouseup', 'mousemove', 'mouseover', 'mouseout', 'blur', 'focus', 'keydown', 'keypress', 'keyup', 'valueChanging', 'valueChanged', 'dropDownListOpening', 'dropDownListOpened', 'dropDownListClosing', 'dropDownListClosed', 'dropDownItemSelecting', 'dropDownItemSelected', 'textChanged']
})
export class IgTextEditorComponent extends IgEditorBase<IgTextEditor> {
    constructor(el: ElementRef, renderer: Renderer2, differs: IterableDiffers, kvalDiffers: KeyValueDiffers,
                cdr: ChangeDetectorRef, @Optional() public model: NgModel) {
      super(el, renderer, differs, kvalDiffers, cdr, model);
    }

    /**
     * Changes the all locales into the widget element to the language specified in [options.language](ui.igtexteditor#options:language)
     * Note that this method is for rare scenarios, see [language](ui.igtexteditor#options:language) or
     * [locale](ui.igtexteditor#options:locale) option setter
     */
    /* istanbul ignore next */
    public changeLocale(): void { return; }

    /**
     * Gets the visible text in the editor.
     */
    /* istanbul ignore next */
    public displayValue(): string { return; }

    /**
     * Gets reference to jquery object which is used as container of drop-down list.
     */
    /* istanbul ignore next */
    public dropDownContainer(): string { return; }

    /**
     * Shows the drop down list.
     */
    /* istanbul ignore next */
    public showDropDown(): void { return; }

    /**
     * Hides the drop down list.
     */
    /* istanbul ignore next */
    public hideDropDown(): void { return; }

    /**
     * Returns a reference to the drop-down button UI element of the editor.
     */
    /* istanbul ignore next */
    public dropDownButton(): string { return; }

    /**
     * Returns if the drop-down list is visible.
     */
    /* istanbul ignore next */
    public dropDownVisible(): boolean { return; }

    /**
     * Returns a reference to the clear button UI element of the editor.
     */
    /* istanbul ignore next */
    public clearButton(): string { return; }

    /**
     * Finds index of list item by text that matches with the search parameters.
     *
     * @param text The text to search for in the drop down list.
     * @param matchType The rule that is applied for searching the text.
     */
    /* istanbul ignore next */
    public findListItemIndex(text: string, matchType?: object): number { return; }

    /**
     * Gets the index of the selected list item. Sets selected item by index.
     *
     * @param index The index of the item that needs to be selected.
     */
    /* istanbul ignore next */
    public selectedListIndex(index?: number): number { return; }

    /**
     * Gets the selected list item.
     */
    /* istanbul ignore next */
    public getSelectedListItem(): string { return; }

    /**
     * Gets the selected text from the editor in edit mode. This can be done inside key event handlers, like keydown or keyup.
     * This method can be used only when the editor is focused.
     * If you invoke this method in display mode, when the editor input is blurred, the returned value will be an empty string.
     */
    /* istanbul ignore next */
    public getSelectedText(): string { return; }

    /**
     * Gets the start index of the selected text in the editor.
     */
    /* istanbul ignore next */
    public getSelectionStart(): number { return; }

    /**
     * Gets the end index of the selected text in the editor.
     */
    /* istanbul ignore next */
    public getSelectionEnd(): number { return; }

    /**
     * Inserts the text at the location of the caret or over the current selection.
     * If the editor is focused the method will insert the text over the current selection.
     * If the editor is not focused the method will set the text as value of the editor.
     * Note: The method raises [textChanged](ui.igtexteditor#events:textChanged) event.
     *
     * @param value The string to be inserted.
     */
    /* istanbul ignore next */
    public insert(value: string): void { return; }

    /**
     * Selects the text between start and end indices in the editor.
     * If the parameters are equal, then the method sets location of caret. The method has effect only when the editor has focus.
     *
     * @param start Start of the selection.
     * @param end End of the selection.
     */
    /* istanbul ignore next */
    public select(start: number, end: number): void { return; }

    /**
     * Selects the previous item from the drop-down list.
     */
    /* istanbul ignore next */
    public spinUp(): void { return; }

    /**
     * Selects the next item from the drop-down list.
     */
    /* istanbul ignore next */
    public spinDown(): void { return; }

    /**
     * Returns a reference to the spin up UI element of the editor.
     */
    /* istanbul ignore next */
    public spinUpButton(): string { return; }

    /**
     * Returns a reference to the spin down UI element of the editor.
     */
    /* istanbul ignore next */
    public spinDownButton(): string { return; }

    /**
     * Gets/Sets name attribute applied to the editor element.
     *
     * @param newValue The new input name.
     */
    /* istanbul ignore next */
    public inputName(newValue?: string): string { return; }

    public value(newValue: object): void { return; }

    /**
     * Gets the input element of the editor.
     */
    /* istanbul ignore next */
    public field(): string { return; }

    /**
     * Gets a reference to the jQuery element that wraps the editor.
     */
    /* istanbul ignore next */
    public editorContainer(): string { return; }

    /**
     * Gets whether the editor has focus.
     */
    /* istanbul ignore next */
    public hasFocus(): boolean { return; }

    /**
     * Sets focus to the editor after the specified delay.
     *
     * @param delay The delay before focusing the editor.
     */
    /* istanbul ignore next */
    public setFocus(delay?: number): void { return; }

    /**
     * Hides the editor.
     */
    /* istanbul ignore next */
    public hide(): void { return; }

    /**
     * Shows the editor.
     */
    /* istanbul ignore next */
    public show(): void { return; }

    /**
     * Gets a reference to [igValidator](ui.igvalidator) used by the editor.
     */
    /* istanbul ignore next */
    public validator(): object { return; }

    /**
     * Checks if the value in the editor is valid. Note: This function will not trigger automatic notifications.
     */
    /* istanbul ignore next */
    public isValid(): boolean { return; }

    /**
     * Triggers validation for the editor. If validatorOptions are set will also call validate on the [igValidator](ui.igvalidator).
     */
    /* istanbul ignore next */
    public validate(): boolean { return; }

    /**
     * Destroys the widget
     */
    /* istanbul ignore next */
    public destroy(): void { return; }
}


text:
package edu.uci.ics.hyracks.storage.common.buffercache;

import edu.uci.ics.hyracks.api.exceptions.HyracksDataException;
import edu.uci.ics.hyracks.api.io.FileReference;

public interface IBufferCache {
    public void createFile(FileReference fileRef) throws HyracksDataException;

    public int createMemFile() throws HyracksDataException;

    public void openFile(int fileId) throws HyracksDataException;

    public void closeFile(int fileId) throws HyracksDataException;

    public void deleteFile(int fileId, boolean flushDirtyPages) throws HyracksDataException;

    public void deleteMemFile(int fileId) throws HyracksDataException;

    public ICachedPage tryPin(long dpid) throws HyracksDataException;

    public ICachedPage pin(long dpid, boolean newPage) throws HyracksDataException;

    public ICachedPage pinVirtual(long vpid) throws HyracksDataException;

    public ICachedPage unpinVirtual(long vpid, long dpid) throws HyracksDataException;

    public void unpin(ICachedPage page) throws HyracksDataException;

    public void flushDirtyPage(ICachedPage page) throws HyracksDataException;

    public void force(int fileId, boolean metadata) throws HyracksDataException;

    public int getPageSize();

    public int getNumPages();

    public int getFileReferenceCount(int fileId);

    public void close() throws HyracksDataException;
}


text:
import * as AWS from 'aws-sdk';
import {SQS as SQSTypes} from 'aws-sdk'; // tslint:disable-line
import * as sinon from 'sinon';

interface AWSPromiseResult<T> {
	promise(): Promise<T | undefined>;
}

class SQS {
	getQueueUrl(
		request: SQSTypes.Types.GetQueueUrlRequest
	): AWSPromiseResult<Partial<SQSTypes.Types.GetQueueUrlResult>> {
		return {
			// tslint:disable-next-line:no-unnecessary-type-annotation
			promise: async (): Promise<Partial<SQSTypes.Types.GetQueueUrlResult> | undefined> => {
				if (!request.QueueName || request.QueueName === 'unknownQueue') {
					return Promise.resolve(undefined);
				}

				const accountId = request.QueueOwnerAWSAccountId || '123456789012';

				return Promise.resolve({
					QueueUrl: `https://sqs.eu-west-1.amazonaws.com/${accountId}/${request.QueueName}`
				});
			}
		};
	}

	sendMessage({
		MessageBody,
		QueueUrl,
		MessageGroupId
	}: SQSTypes.Types.SendMessageRequest): AWSPromiseResult<Partial<SQSTypes.Types.SendMessageResult>> {
		return {
			// tslint:disable-next-line:no-unnecessary-type-annotation
			promise: async (): Promise<Partial<SQSTypes.Types.SendMessageResult> | undefined> => {
				if (
					MessageBody === JSON.stringify({payload: 'something'}) &&
					QueueUrl === 'https://sqs.eu-west-1.amazonaws.com/123456789012/demoQueue'
				) {
					return Promise.resolve({
						MessageId: '123456789'
					});
				}

				if (QueueUrl === 'https://sqs.eu-west-1.amazonaws.com/123456789012/somequeue.fifo' && MessageGroupId) {
					return Promise.resolve({MessageId: '1337'});
				}

				return;
			}
		};
	}
}
const sqs = new SQS();

// tslint:disable-next-line:only-arrow-functions typedef
(AWS as any).SQS = function() {
	return sqs;
};

export default sqs;

sinon.spy(sqs, 'sendMessage');


text:
<?php

namespace Analogue\ORM\Relationships;

use Analogue\ORM\System\Builders\ResultBuilder;
use Analogue\ORM\System\Manager;
use Analogue\ORM\System\Wrappers\Factory;

abstract class EmbeddedRelationship
{
    /**
     * The class that embeds the current relation.
     *
     * @var string
     */
    protected $parentClass;

    /**
     * The class of the embedded relation.
     *
     * @var string
     */
    protected $relatedClass;

    /**
     * The relation attribute on the parent object.
     *
     * @var string
     */
    protected $relation;

    /**
     * If set to true, embedded Object's attributes will
     * be stored as a serialized array in a JSON Column.
     *
     * @var bool
     */
    protected $asArray = false;

    /**
     * If set to true, embedded Object's attributes will
     * be json encoded before storing to database.
     *
     * @var bool
     */
    protected $asJson = false;

    /**
     * Prefix on which the object's attributes are saved into
     * the parent's table. defaults to "<relatedClass>_".
     *
     * @var string
     */
    protected $prefix;

    /**
     * Attributes Map allow the calling EntityMap to overrides attributes
     * on the embedded relation.
     *
     * @var array
     */
    protected $columnMap = [];

    /**
     * Wrapper factory.
     *
     * @var \Analogue\ORM\System\Wrappers\Factory
     */
    protected $factory;

    public function __construct($parent, string $relatedClass, string $relation)
    {
        $this->parentClass = get_class($parent);
        $this->relatedClass = $relatedClass;
        $this->relation = $relation;
        $this->prefix = $relation.'_';
        $this->factory = new Factory();
    }

    /**
     * Switch the 'store as array' feature.
     *
     * @param bool $storeAsArray
     *
     * @return static
     */
    public function asArray(bool $storeAsArray = true)
    {
        $this->asArray = $storeAsArray;

        return $this;
    }

    /**
     * Switch the 'store as json' feature.
     *
     * @param bool $storeAsJson
     *
     * @return static
     */
    public function asJson(bool $storeAsJson = true)
    {
        $this->asJson = $storeAsJson;

        return $this->asArray();
    }

    /**
     * Set the column map for the embedded relation.
     *
     * @param array $columns
     *
     * @return static
     */
    public function setColumnMap(array $columns)
    {
        $this->columnMap = $columns;

        return $this;
    }

    /**
     * Set parent's attribute prefix.
     *
     * @param string $prefix
     *
     * @return static
     */
    public function setPrefix(string $prefix)
    {
        $this->prefix = $prefix;

        return $this;
    }

    /**
     * Return parent's attribute prefix.
     *
     * @return string
     */
    public function getPrefix(): string
    {
        return $this->prefix;
    }

    /**
     * Get the embedded object's attributes that will be
     * hydrated using parent's entity attributes.
     *
     * @return array
     */
    protected function getEmbeddedObjectAttributes(): array
    {
        $entityMap = $this->getRelatedMapper()->getEntityMap();

        $attributes = $entityMap->getAttributes();
        $properties = $entityMap->getProperties();

        return array_merge($attributes, $properties);
    }

    /**
     * Get the corresponding attribute on parent's attributes.
     *
     * @param string $key
     *
     * @return string
     */
    protected function getParentAttributeKey($key): string
    {
        return $this->getPrefixedAttributeKey($this->getMappedParentAttribute($key));
    }

    /**
     * Get attribute name from the parent, if a map has been
     * defined.
     *
     * @param string $key
     *
     * @return string
     */
    protected function getMappedParentAttribute(string $key): string
    {
        if (array_key_exists($key, $this->columnMap)) {
            return $this->columnMap[$key];
        } else {
            return $key;
        }
    }

    /**
     * Return the name of the attribute with key.
     *
     * @param string $attributeKey
     *
     * @return string
     */
    protected function getPrefixedAttributeKey(string $attributeKey): string
    {
        return $this->prefix.$attributeKey;
    }

    /**
     * Transform attributes into embedded object(s), and
     * match it into the given resultset.
     *
     * @return array
     */
    abstract public function match(array $results): array;

    /**
     * Build an embedded object instance.
     *
     * @param array $attributes
     *
     * @return mixed
     */
    protected function buildEmbeddedObject(array $attributes)
    {
        $resultBuilder = new ResultBuilder($this->getRelatedMapper(), true);

        // TODO : find a way to support eager load within an embedded
        // object.
        $eagerLoads = [];

        return $resultBuilder->build([$attributes], $eagerLoads)[0];
    }

    /**
     * Transform embedded object into db column(s).
     *
     * @param mixed $object
     *
     * @return array $columns
     */
    abstract public function normalize($object): array;

    /**
     * Return parent mapper.
     *
     * @return \Analogue\ORM\System\Mapper
     */
    protected function getParentMapper()
    {
        return Manager::getInstance()->mapper($this->parentClass);
    }

    /**
     * Return embedded relationship mapper.
     *
     * @return \Analogue\ORM\System\Mapper
     */
    protected function getRelatedMapper()
    {
        return Manager::getInstance()->mapper($this->relatedClass);
    }
}


text:
<?php

namespace ShopifyApi\Api;

use BadMethodCallException;
use ShopifyApi\Client;
use ShopifyApi\Api\Traits\OwnsMetafields;

/**
 * Class Variants
 *
 * API calls that can be carried out on a Product
 */
class Variants extends AbstractApi
{

    use OwnsMetafields;

    /** @var string $parameters_wrap */
    protected static $parameters_wrap = 'variant';

    /** @var string $parameters_wrap_many */
    protected static $parameters_wrap_many = 'variants';

    /** @var string $path */
    protected static $path = '/variants/#id#.json';

    /** @var array $fields */
    public static $fields = [
        'id',
        'product_id',
        'title',
        'price',
        'sku',
        'position',
        'grams',
        'inventory_policy',
        'compare_at_price',
        'fulfillment_service',
        'inventory_management',
        'option1',
        'option2',
        'option3',
        'created_at',
        'updated_at',
        'taxable',
        'barcode',
        'image_id',
        'inventory_quantity',
        'weight',
        'weight_unit',
        'old_inventory_quantity',
        'requires_shipping'
    ];

    /** @var array $ignore_on_update_fields */
    public static $ignore_on_update_fields = [];

    /** @var int|null $product_id */
    protected $product_id = null;

    /** @var int|null $variant_id */
    protected $variant_id = null;

    /**
     * @param Client $client
     * @param int|null $product_id
     * @param int|null $variant_id
     */
    public function __construct($client, $variant_id = null, $product_id = null)
    {
        parent::__construct($client);
        $this->variant_id = $variant_id;
        $this->product_id = $product_id;
    }

    /**
     * @param $product_id
     * @return $this
     */
    public function product($product_id)
    {
        $this->product_id = $product_id;
        return $this;
    }

    /**
     * Retrieve all Product Variants (api limit is 250)
     *
     * @link https://help.shopify.com/api/reference/product_variant#index
     *
     * @param array $params
     * @return \Guzzle\Http\EntityBodyInterface|mixed|string
     */
    public function all(array $params = [])
    {
        $product_id = $this->product_id;

        if (empty($product_id)) {
            throw new BadMethodCallException('Please specify a product id.');
        }

        return $this->get($this->getRelatedPath($product_id), $params);
    }

    /**
     * Retrieve the number of variants
     *
     * @link https://help.shopify.com/api/reference/product_variant#count
     *
     * @param array $params
     * @return \Guzzle\Http\EntityBodyInterface|mixed|string
     */
    public function count(array $params = [])
    {
        if (empty($this->product_id)) {
            throw new BadMethodCallException('Please specify a product id.');
        }

        $count = $this->get(sprintf('/products/%d/variants/count.json', $this->product_id), $params);

        return isset($count['count']) ? $count['count'] : 0;
    }

    /**
     * Find a Product Variant
     *
     * @link https://help.shopify.com/api/reference/product_variant#show
     *
     * @param string $id     the board's id
     * @param array  $params optional attributes
     *
     * @return array board info
     */
    public function show($id, array $params = [])
    {
        return $this->get($this->getPath($id), $params);
    }

    /**
     * Update a Product Variant
     *
     * @link https://help.shopify.com/api/reference/product_variant#update
     *
     * @param $id
     * @param array $params
     * @return array
     */
    public function update($id, array $params = [])
    {
        return $this->put($this->getPath(rawurlencode($id)), $params);
    }

    /**
     * Delete a Product Variant
     *
     * @link https://help.shopify.com/api/reference/product_variant#delete
     *
     * @param $product_id
     * @param $id
     * @param array $params
     * @return array
     */
    public function remove($product_id, $id, array $params = [])
    {
        $path = sprintf('/products/%d/variants/%d.json', $product_id, $id);
        return $this->delete($path, $params);
    }

    /**
     * Create a Product Variant
     *
     * @link https://help.shopify.com/api/reference/product_variant#create
     *
     * @param array  $params optional attributes
     *
     * @return array card info
     */
    public function create(array $params = array())
    {
        $product_id = isset($params['product_id'])
            ? $params['product_id']
            : $this->product_id;

        if (empty($product_id)) {
            throw new BadMethodCallException('Please specify a product id.');
        }

        $option_required = array_fill_keys(['option1', 'option2', 'option2'], null);

        if (empty(array_intersect_key($params, $option_required))) {
            throw new BadMethodCallException('Please specify a option.');
        }

        $variant = $params;

        return $this->post($this->getRelatedPath($product_id), compact('variant'));
    }

    /**
     * @param $product_id
     * @return string
     */
    private function getRelatedPath($product_id)
    {
        return sprintf('/products/%d/variants.json', $product_id);
    }

}