text:
package io.dropwizard.logging;

import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.core.Appender;
import ch.qos.logback.core.FileAppender;
import ch.qos.logback.core.encoder.LayoutWrappingEncoder;
import ch.qos.logback.core.rolling.DefaultTimeBasedFileNamingAndTriggeringPolicy;
import ch.qos.logback.core.rolling.FixedWindowRollingPolicy;
import ch.qos.logback.core.rolling.RollingFileAppender;
import ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy;
import ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy;
import ch.qos.logback.core.rolling.TimeBasedFileNamingAndTriggeringPolicy;
import ch.qos.logback.core.rolling.TimeBasedRollingPolicy;
import ch.qos.logback.core.spi.DeferredProcessingAware;
import ch.qos.logback.core.util.FileSize;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeName;
import io.dropwizard.logging.async.AsyncAppenderFactory;
import io.dropwizard.logging.filter.LevelFilterFactory;
import io.dropwizard.logging.layout.LayoutFactory;
import io.dropwizard.util.Size;
import io.dropwizard.validation.MinSize;
import io.dropwizard.validation.ValidationMethod;
import javax.validation.constraints.Min;

/**
 * An {@link AppenderFactory} implementation which provides an appender that writes events to a file, archiving older
 * files as it goes.
 *

 * Configuration Parameters:
 *

 *

 *         Name
 *         Default
 *         Description
 *

 *

 *         {@code type}
 *         REQUIRED
 *         The appender type. Must be {@code file}.
 *

 *

 *         {@code threshold}
 *         {@code ALL}
 *         The lowest level of events to write to the file.
 *

 *

 *         {@code currentLogFilename}
 *         REQUIRED
 *         The filename where current events are logged.
 *

 *

 *         {@code archive}
 *         {@code true}
 *         Whether or not to archive old events in separate files.
 *

 *

 *         {@code archivedLogFilenamePattern}
 *         REQUIRED if {@code archive} is {@code true}.
 *
 *             The filename pattern for archived files.
 *             If {@code maxFileSize} is specified, rollover is size-based, and the pattern must contain {@code %i} for
 *             an integer index of the archived file.
 *             Otherwise rollover is date-based, and the pattern must contain {@code %d}, which is replaced with the
 *             date in {@code yyyy-MM-dd} form.
 *             If the pattern ends with {@code .gz} or {@code .zip}, files will be compressed as they are archived.
 *
 *

 *

 *         {@code archivedFileCount}
 *         {@code 5}
 *
 *             The number of archived files to keep. Must be greater than or equal to {@code 0}. Zero is a
 *             special value signifying to keep infinite logs (use with caution)
 *
 *

 *

 *         {@code maxFileSize}
 *         (unlimited)
 *
 *             The maximum size of the currently active file before a rollover is triggered. The value can be expressed
 *             in bytes, kilobytes, megabytes, gigabytes, and terabytes by appending B, K, MB, GB, or TB to the
 *             numeric value.  Examples include 100MB, 1GB, 1TB.  Sizes can also be spelled out, such as 100 megabytes,
 *             1 gigabyte, 1 terabyte.
 *
 *

 *

 *         {@code timeZone}
 *         {@code UTC}
 *         The time zone to which event timestamps will be converted.
 *

 *

 *         {@code logFormat}
 *         the default format
 *
 *             The Logback pattern with which events will be formatted. See
 *             the Logback documentation
 *             for details.
 *
 *

 *

 *         {@code bufferSize}
 *         8KB
 *
 *             The buffer size of the underlying FileAppender (setting added in logback 1.1.10). Increasing this from
 *             the default of 8KB to 256KB is reported to significantly reduce thread contention.
 *
 *

 *

 *
 * @see AbstractAppenderFactory
 */
@JsonTypeName("file")
public class FileAppenderFactory<E extends DeferredProcessingAware> extends AbstractAppenderFactory<E> {

    private String currentLogFilename;

    private boolean archive = true;

    private String archivedLogFilenamePattern;

    @Min(0)
    private int archivedFileCount = 5;

    private Size maxFileSize;

    @MinSize(1)
    private Size bufferSize = Size.bytes(FileAppender.DEFAULT_BUFFER_SIZE);

    @JsonProperty
    public String getCurrentLogFilename() {
        return currentLogFilename;
    }

    @JsonProperty
    public void setCurrentLogFilename(String currentLogFilename) {
        this.currentLogFilename = currentLogFilename;
    }

    @JsonProperty
    public boolean isArchive() {
        return archive;
    }

    @JsonProperty
    public void setArchive(boolean archive) {
        this.archive = archive;
    }

    @JsonProperty
    public String getArchivedLogFilenamePattern() {
        return archivedLogFilenamePattern;
    }

    @JsonProperty
    public void setArchivedLogFilenamePattern(String archivedLogFilenamePattern) {
        this.archivedLogFilenamePattern = archivedLogFilenamePattern;
    }

    @JsonProperty
    public int getArchivedFileCount() {
        return archivedFileCount;
    }

    @JsonProperty
    public void setArchivedFileCount(int archivedFileCount) {
        this.archivedFileCount = archivedFileCount;
    }

    @JsonProperty
    public Size getMaxFileSize() {
        return maxFileSize;
    }

    @JsonProperty
    public void setMaxFileSize(Size maxFileSize) {
        this.maxFileSize = maxFileSize;
    }

    @JsonProperty
    public Size getBufferSize() {
        return bufferSize;
    }

    @JsonProperty
    public void setBufferSize(Size bufferSize) {
        this.bufferSize = bufferSize;
    }

    @JsonIgnore
    @ValidationMethod(message = "must have archivedLogFilenamePattern if archive is true")
    public boolean isValidArchiveConfiguration() {
        return !archive || (archivedLogFilenamePattern != null);
    }

    @JsonIgnore
    @ValidationMethod(message = "when specifying maxFileSize, archivedLogFilenamePattern must contain %i")
    public boolean isValidForMaxFileSizeSetting() {
        return !archive || maxFileSize == null ||
                (archivedLogFilenamePattern != null && archivedLogFilenamePattern.contains("%i"));
    }

    @JsonIgnore
    @ValidationMethod(message = "when archivedLogFilenamePattern contains %i, maxFileSize must be specified")
    public boolean isMaxFileSizeSettingSpecified() {
        return !archive || !(archivedLogFilenamePattern != null && archivedLogFilenamePattern.contains("%i")) ||
                maxFileSize != null;
    }

    @JsonIgnore
    @ValidationMethod(message = "currentLogFilename can only be null when archiving is enabled")
    public boolean isValidFileConfiguration() {
        return archive || currentLogFilename != null;
    }

    @Override
    public Appender<E> build(LoggerContext context, String applicationName, LayoutFactory<E> layoutFactory,
                             LevelFilterFactory<E> levelFilterFactory, AsyncAppenderFactory<E> asyncAppenderFactory) {
        final FileAppender<E> appender = buildAppender(context);
        appender.setName("file-appender");

        appender.setAppend(true);
        appender.setContext(context);

        final LayoutWrappingEncoder<E> layoutEncoder = new LayoutWrappingEncoder<>();
        layoutEncoder.setLayout(buildPatternLayout(context, layoutFactory));
        appender.setEncoder(layoutEncoder);

        appender.setPrudent(false);
        appender.addFilter(levelFilterFactory.build(threshold));
        getFilterFactories().forEach(f -> appender.addFilter(f.build()));
        appender.start();

        return wrapAsync(appender, asyncAppenderFactory);
    }

    protected FileAppender<E> buildAppender(LoggerContext context) {
        if (archive) {
            final RollingFileAppender<E> appender = new RollingFileAppender<>();
            appender.setContext(context);
            appender.setFile(currentLogFilename);
            appender.setBufferSize(new FileSize(bufferSize.toBytes()));

            if (maxFileSize != null && !archivedLogFilenamePattern.contains("%d")) {
                final FixedWindowRollingPolicy rollingPolicy = new FixedWindowRollingPolicy();
                rollingPolicy.setContext(context);
                rollingPolicy.setMaxIndex(getArchivedFileCount());
                rollingPolicy.setFileNamePattern(getArchivedLogFilenamePattern());
                rollingPolicy.setParent(appender);
                rollingPolicy.start();
                appender.setRollingPolicy(rollingPolicy);

                final SizeBasedTriggeringPolicy<E> triggeringPolicy = new SizeBasedTriggeringPolicy<>();
                triggeringPolicy.setMaxFileSize(new FileSize(maxFileSize.toBytes()));
                triggeringPolicy.setContext(context);
                triggeringPolicy.start();
                appender.setTriggeringPolicy(triggeringPolicy);

                return appender;
            } else {
                final TimeBasedRollingPolicy<E> rollingPolicy;
                if (maxFileSize == null) {
                    rollingPolicy = new TimeBasedRollingPolicy<>();

                    final TimeBasedFileNamingAndTriggeringPolicy<E> triggeringPolicy = new DefaultTimeBasedFileNamingAndTriggeringPolicy<>();
                    triggeringPolicy.setContext(context);
                    triggeringPolicy.setTimeBasedRollingPolicy(rollingPolicy);
                    appender.setTriggeringPolicy(triggeringPolicy);
                } else {
                    // Creating a size and time policy does not need a separate triggering policy set
                    // on the appender because this policy registers the trigger policy
                    final SizeAndTimeBasedRollingPolicy<E> sizeAndTimeBasedRollingPolicy = new SizeAndTimeBasedRollingPolicy<>();
                    sizeAndTimeBasedRollingPolicy.setMaxFileSize(new FileSize(maxFileSize.toBytes()));
                    rollingPolicy = sizeAndTimeBasedRollingPolicy;
                }

                rollingPolicy.setContext(context);
                rollingPolicy.setFileNamePattern(archivedLogFilenamePattern);
                rollingPolicy.setMaxHistory(archivedFileCount);

                appender.setRollingPolicy(rollingPolicy);

                rollingPolicy.setParent(appender);
                rollingPolicy.start();
                return appender;
            }
        }

        final FileAppender<E> appender = new FileAppender<>();
        appender.setContext(context);
        appender.setFile(currentLogFilename);
        appender.setBufferSize(new FileSize(bufferSize.toBytes()));
        return appender;
    }
}


text:
layout: page
title: Camacho Dart Global Seminar
date: 2016-05-24
author: Diana Kent
tags: weekly links, java
status: published
summary: Etiam tortor est, scelerisque eu aliquam a, porta.
banner: images/banner/wedding.jpg
booking:
  startDate: 04/08/2018
  endDate: 04/12/2018
  ctyhocn: FKLKYHX
  groupCode: CDGS
published: true
---
Praesent lacinia magna quis velit aliquet, ut convallis metus pretium. Duis sed augue at mauris facilisis tincidunt vitae vel sem. Donec vel enim non metus tincidunt vulputate. Quisque porta eros non ornare posuere. In vel enim ante. Nullam vestibulum arcu sit amet pharetra iaculis. Etiam at sagittis neque. Aenean tellus diam, ullamcorper eu pellentesque nec, porttitor nec ex.

1 Aliquam ac lorem ut ex luctus mattis
1 Nam nec orci porta, ultrices massa a, tincidunt purus.

Fusce facilisis tellus lorem, accumsan consequat erat laoreet eget. Phasellus sed diam vitae magna elementum posuere. Nulla varius felis non viverra aliquet. Maecenas convallis ac orci eu tristique. Pellentesque elementum posuere elit nec consequat. Duis lacinia felis condimentum magna luctus, vitae pharetra est congue. Integer congue tortor ligula, ac lobortis elit tempor ac. Suspendisse faucibus sem ipsum, eget scelerisque quam ultricies et. Curabitur maximus vel dui congue laoreet.
Curabitur leo quam, luctus sit amet gravida vel, ultricies quis ante. Donec eget justo eget turpis gravida condimentum sit amet ut odio. Nullam eget dapibus nibh, ut gravida tellus. Nam diam justo, consectetur a luctus in, dignissim nec arcu. Nam porta egestas mattis. Nullam laoreet odio ut nibh accumsan, sed facilisis nunc cursus. Donec hendrerit magna in neque iaculis facilisis. Sed bibendum ipsum id varius placerat. Pellentesque et ligula lobortis, cursus turpis sit amet, hendrerit est. Praesent vitae cursus nulla.

redpajama_set_name: RedPajamaGithub


text:
package org.apache.commons.imaging.formats.jpeg;

import static org.apache.commons.imaging.common.BinaryFunctions.getStreamBytes;
import static org.apache.commons.imaging.common.BinaryFunctions.readAndVerifyBytes;
import static org.apache.commons.imaging.common.BinaryFunctions.readByte;
import static org.apache.commons.imaging.common.BinaryFunctions.readBytes;

import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteOrder;

import org.apache.commons.imaging.ImageReadException;
import org.apache.commons.imaging.common.BinaryFileParser;
import org.apache.commons.imaging.common.ByteConversions;
import org.apache.commons.imaging.common.bytesource.ByteSource;
import org.apache.commons.imaging.internal.Debug;

public class JpegUtils extends BinaryFileParser {
    public JpegUtils() {
        setByteOrder(ByteOrder.BIG_ENDIAN);
    }

    public interface Visitor {
        // return false to exit before reading image data.
        boolean beginSOS();

        void visitSOS(int marker, byte[] markerBytes, byte[] imageData);

        // return false to exit traversal.
        boolean visitSegment(int marker, byte[] markerBytes,
                int segmentLength, byte[] segmentLengthBytes,
                byte[] segmentData) throws ImageReadException,
                IOException;
    }

    public void traverseJFIF(final ByteSource byteSource, final Visitor visitor)
            throws ImageReadException,
            IOException {
        try (InputStream is = byteSource.getInputStream()) {
            readAndVerifyBytes(is, JpegConstants.SOI,
                    "Not a Valid JPEG File: doesn't begin with 0xffd8");

            int markerCount;
            for (markerCount = 0; true; markerCount++) {
                final byte[] markerBytes = new byte[2];
                do {
                    markerBytes[0] = markerBytes[1];
                    markerBytes[1] = readByte("marker", is,
                            "Could not read marker");
                } while ((0xff & markerBytes[0]) != 0xff
                        || (0xff & markerBytes[1]) == 0xff);
                final int marker = ((0xff & markerBytes[0]) << 8)
                        | (0xff & markerBytes[1]);

                if (marker == JpegConstants.EOI_MARKER || marker == JpegConstants.SOS_MARKER) {
                    if (!visitor.beginSOS()) {
                        return;
                    }

                    final byte[] imageData = getStreamBytes(is);
                    visitor.visitSOS(marker, markerBytes, imageData);
                    break;
                }

                final byte[] segmentLengthBytes = readBytes("segmentLengthBytes", is, 2, "segmentLengthBytes");
                final int segmentLength = ByteConversions.toUInt16(segmentLengthBytes, getByteOrder());
                if (segmentLength < 2) {
                    throw new ImageReadException("Invalid segment size");
                }

                final byte[] segmentData = readBytes("Segment Data",
                        is, segmentLength - 2,
                        "Invalid Segment: insufficient data");

                if (!visitor.visitSegment(marker, markerBytes, segmentLength, segmentLengthBytes, segmentData)) {
                    return;
                }
            }

            Debug.debug(markerCount + " markers");
        }
    }

    public static String getMarkerName(final int marker) {
        switch (marker) {
        case JpegConstants.SOS_MARKER:
            return "SOS_MARKER";
            // case JPEG_APP0 :
            // return "JPEG_APP0";
            // case JPEG_APP0_MARKER :
            // return "JPEG_APP0_MARKER";
        case JpegConstants.JPEG_APP1_MARKER:
            return "JPEG_APP1_MARKER";
        case JpegConstants.JPEG_APP2_MARKER:
            return "JPEG_APP2_MARKER";
        case JpegConstants.JPEG_APP13_MARKER:
            return "JPEG_APP13_MARKER";
        case JpegConstants.JPEG_APP14_MARKER:
            return "JPEG_APP14_MARKER";
        case JpegConstants.JPEG_APP15_MARKER:
            return "JPEG_APP15_MARKER";
        case JpegConstants.JFIF_MARKER:
            return "JFIF_MARKER";
        case JpegConstants.SOF0_MARKER:
            return "SOF0_MARKER";
        case JpegConstants.SOF1_MARKER:
            return "SOF1_MARKER";
        case JpegConstants.SOF2_MARKER:
            return "SOF2_MARKER";
        case JpegConstants.SOF3_MARKER:
            return "SOF3_MARKER";
        case JpegConstants.DHT_MARKER:
            return "SOF4_MARKER";
        case JpegConstants.SOF5_MARKER:
            return "SOF5_MARKER";
        case JpegConstants.SOF6_MARKER:
            return "SOF6_MARKER";
        case JpegConstants.SOF7_MARKER:
            return "SOF7_MARKER";
        case JpegConstants.SOF8_MARKER:
            return "SOF8_MARKER";
        case JpegConstants.SOF9_MARKER:
            return "SOF9_MARKER";
        case JpegConstants.SOF10_MARKER:
            return "SOF10_MARKER";
        case JpegConstants.SOF11_MARKER:
            return "SOF11_MARKER";
        case JpegConstants.DAC_MARKER:
            return "DAC_MARKER";
        case JpegConstants.SOF13_MARKER:
            return "SOF13_MARKER";
        case JpegConstants.SOF14_MARKER:
            return "SOF14_MARKER";
        case JpegConstants.SOF15_MARKER:
            return "SOF15_MARKER";
        case JpegConstants.DQT_MARKER:
            return "DQT_MARKER";
        case JpegConstants.DRI_MARKER:
            return "DRI_MARKER";
        case JpegConstants.RST0_MARKER:
            return "RST0_MARKER";
        case JpegConstants.RST1_MARKER:
            return "RST1_MARKER";
        case JpegConstants.RST2_MARKER:
            return "RST2_MARKER";
        case JpegConstants.RST3_MARKER:
            return "RST3_MARKER";
        case JpegConstants.RST4_MARKER:
            return "RST4_MARKER";
        case JpegConstants.RST5_MARKER:
            return "RST5_MARKER";
        case JpegConstants.RST6_MARKER:
            return "RST6_MARKER";
        case JpegConstants.RST7_MARKER:
            return "RST7_MARKER";
        default:
            return "Unknown";
        }
    }

    public void dumpJFIF(final ByteSource byteSource) throws ImageReadException,
            IOException {
        final Visitor visitor = new Visitor() {
            // return false to exit before reading image data.
            @Override
            public boolean beginSOS() {
                return true;
            }

            @Override
            public void visitSOS(final int marker, final byte[] markerBytes, final byte[] imageData) {
                Debug.debug("SOS marker.  " + imageData.length + " bytes of image data.");
                Debug.debug("");
            }

            // return false to exit traversal.
            @Override
            public boolean visitSegment(final int marker, final byte[] markerBytes,
                    final int segmentLength, final byte[] segmentLengthBytes,
                    final byte[] segmentData) {
                Debug.debug("Segment marker: " + Integer.toHexString(marker)
                        + " (" + getMarkerName(marker) + "), "
                        + segmentData.length + " bytes of segment data.");
                return true;
            }
        };

        traverseJFIF(byteSource, visitor);
    }
}


text:
//MIT, 2020, WinterDev
using System;
namespace LayoutFarm.UI
{
    public class UIMouseBehaviour<S, T> : UIMouseBehaviourBase<S, T>
          where S : IAcceptBehviour
    {

        readonly MouseBehaviourInstance<S, T> _sharedInstance;
        public UIMouseBehaviour(T defaultSharedState = default)
        {
            //TODO:  _sharedInstance => should be replacable?
            _sharedInstance = new MouseBehaviourInstance<S, T>(this, defaultSharedState);
        }
        /// <summary>
        /// attach shared behavior instance to specific object
        /// </summary>
        /// <param name="acc"></param>
        public void AttachSharedBehaviorTo(S acc)
        {
            acc.AttachBehviour(_sharedInstance);
        }
        /// <summary>
        /// attach new behaviour instance+ its state to specific object
        /// </summary>
        /// <param name="acc"></param>
        /// <param name="state"></param>
        public void AttachUniqueBehaviorTo(S acc, T state)
        {
            acc.AttachBehviour(new MouseBehaviourInstance<S, T>(this, state));
        }
    }
    public class UIMouseBehaviour<S> : UIMouseBehaviourBase<S, object>
         where S : IAcceptBehviour
    {
        readonly MouseBehaviourInstance<S, object> _sharedInstance;
        public UIMouseBehaviour()
        {
            //TODO:  _sharedInstance => should be replacable?
            _sharedInstance = new MouseBehaviourInstance<S, object>(this, null);
        }
        /// <summary>
        /// attach shared behavior instance to specific object
        /// </summary>
        /// <param name="acc"></param>
        public void AttachSharedBehaviorTo(S acc)
        {
            acc.AttachBehviour(_sharedInstance);
        }
    }

    /// <summary>
    /// behavior group for specific object S and State T
    /// </summary>
    /// <typeparam name="S"></typeparam>
    /// <typeparam name="T"></typeparam>
    public abstract class UIMouseBehaviourBase<S, T>
                          where S : IAcceptBehviour
    {
        public readonly struct SenderInfo
        {
            /// <summary>
            /// event source
            /// </summary>
            public readonly S Source;
            /// <summary>
            /// state, may be nothing
            /// </summary>
            public readonly T State;

            public SenderInfo(S source, T state)
            {
                Source = source;
                State = state;
            }
        }

        public event Action<SenderInfo, UIMouseDownEventArgs> MouseDown;
        public event Action<SenderInfo, UIMouseUpEventArgs> MouseUp;
        public event Action<SenderInfo, UIMouseMoveEventArgs> MouseMove;
        public event Action<SenderInfo, UIMouseMoveEventArgs> MouseDrag;
        //----
        public event Action<SenderInfo, UIMouseMoveEventArgs> MouseEnter;
        public event Action<SenderInfo, UIMouseLeaveEventArgs> MouseLeave;
        public event Action<SenderInfo, UIMouseHoverEventArgs> MouseHover;
        public event Action<SenderInfo, UIMouseLostFocusEventArgs> MouseLostFocus;

        public event Action<SenderInfo, UIMousePressEventArgs> MousePress;
        public event Action<SenderInfo, UIMouseEventArgs> MouseClick;
        public event Action<SenderInfo, UIMouseEventArgs> MouseDoubleClick;
        public event Action<SenderInfo, UIGuestMsgEventArgs> GuestMsg;
        //----

        /// <summary>
        /// has mouse-down
        /// </summary>
        internal bool HasMouseDown => MouseDown != null;
        internal void InvokeMouseDown(S sender, T state, UIMouseDownEventArgs e)
        {
            MouseDown.Invoke(new SenderInfo(sender, state), e);
        }
        /// <summary>
        /// has mouse-up
        /// </summary>
        internal bool HasMouseUp => MouseUp != null;
        internal void InvokeMouseUp(S sender, T state, UIMouseUpEventArgs e)
        {
            MouseUp?.Invoke(new SenderInfo(sender, state), e);
        }
        /// <summary>
        /// has mouse move subscription
        /// </summary>
        internal bool HasMouseMove => MouseMove != null;
        internal void InvokeMouseMove(S sender, T state, UIMouseMoveEventArgs e) => MouseMove.Invoke(new SenderInfo(sender, state), e);
        /// <summary>
        /// has mouse move subscription
        /// </summary>
        internal bool HasMouseDrag => MouseDrag != null;
        internal void InvokeMouseDrag(S sender, T state, UIMouseMoveEventArgs e) => MouseDrag.Invoke(new SenderInfo(sender, state), e);

        /// <summary>
        /// has mouse enter
        /// </summary>
        internal bool HasMouseEnter => MouseEnter != null;
        internal void InvokeMouseEnter(S sender, T state, UIMouseMoveEventArgs e) => MouseEnter.Invoke(new SenderInfo(sender, state), e);

        /// <summary>
        /// has mouse leave
        /// </summary>
        internal bool HasMouseLeave => MouseLeave != null;
        internal void InvokeMouseLeave(S sender, T state, UIMouseLeaveEventArgs e) => MouseLeave.Invoke(new SenderInfo(sender, state), e);

        internal bool HasMousePress => MousePress != null;
        internal void InvokeMousePress(S sender, T state, UIMousePressEventArgs e) => MousePress.Invoke(new SenderInfo(sender, state), e);

        internal bool HasMouseClick => MouseClick != null;
        internal void InvokeMouseClick(S sender, T state, UIMouseEventArgs e) => MouseClick.Invoke(new SenderInfo(sender, state), e);

        internal bool HasMouseDoubleClick => MouseDoubleClick != null;
        internal void InvokeMouseDoubleClick(S sender, T state, UIMouseEventArgs e) => MouseDoubleClick.Invoke(new SenderInfo(sender, state), e);

        internal bool HasGuestMsg => GuestMsg != null;
        internal void InvokeGuestMsg(S sender, T state, UIGuestMsgEventArgs e) => GuestMsg.Invoke(new SenderInfo(sender, state), e);

        internal bool HasMouseLostFocus => MouseLostFocus != null;
        internal void InvokeMouseLostFocus(S sender, T state, UIMouseLostFocusEventArgs e) => MouseLostFocus.Invoke(new SenderInfo(sender, state), e);

        internal bool HasMouseHover => MouseHover != null;
        internal void InvokeMouseHover(S sender, T state, UIMouseHoverEventArgs e) => MouseHover.Invoke(new SenderInfo(sender, state), e);

    }

    public abstract class MouseBehaviorInstanceBase
    {
        internal abstract void ListenGuestMsg(object sender, UIGuestMsgEventArgs e);
        internal abstract void ListenLostMouseFocus(object sender, UIMouseLostFocusEventArgs e);
        internal abstract void ListenMouseDoubleClick(object sender, UIMouseEventArgs e);
        internal abstract void ListenMouseClick(object sender, UIMouseEventArgs e);
        internal abstract void ListenMouseDown(object sender, UIMouseDownEventArgs e);
        internal abstract void ListenMouseEnter(object sender, UIMouseMoveEventArgs e);
        internal abstract void ListenMouseLeave(object sender, UIMouseLeaveEventArgs e);
        internal abstract void ListenMouseMove(object sender, UIMouseMoveEventArgs e);
        internal abstract void ListenMouseUp(object sender, UIMouseUpEventArgs e);
        internal abstract void ListenMousePress(object sender, UIMousePressEventArgs e);
        internal abstract void ListenMouseHover(object sender, UIMouseHoverEventArgs e);
    }

    public interface IAcceptBehviour
    {
        bool AttachBehviour(MouseBehaviorInstanceBase inst);
    }

    public class MouseBehaviourInstance<S, T> : MouseBehaviorInstanceBase
        where S : IAcceptBehviour
    {
        readonly UIMouseBehaviourBase<S, T> _ownerBeh;
        T _state;
        public MouseBehaviourInstance(UIMouseBehaviourBase<S, T> ownerBeh, T state)
        {
#if DEBUG
#endif
            _ownerBeh = ownerBeh;
            _state = state;
        }

        internal override void ListenGuestMsg(object sender, UIGuestMsgEventArgs e)
        {
            //since we don't want a 'blank round trip'
            //(invoke a blank action), so , => check before invocation
            if (_ownerBeh.HasGuestMsg) _ownerBeh.InvokeGuestMsg((S)sender, _state, e);
        }
        internal override void ListenLostMouseFocus(object sender, UIMouseLostFocusEventArgs e)
        {

            if (_ownerBeh.HasMouseLostFocus) _ownerBeh.InvokeMouseLostFocus((S)sender, _state, e);
        }
        internal override void ListenMouseDoubleClick(object sender, UIMouseEventArgs e)
        {

            if (_ownerBeh.HasMouseDoubleClick) _ownerBeh.InvokeMouseDoubleClick((S)sender, _state, e);
        }
        internal override void ListenMouseClick(object sender, UIMouseEventArgs e)
        {
            if (_ownerBeh.HasMouseClick) _ownerBeh.InvokeMouseClick((S)sender, _state, e);
        }
        internal override void ListenMouseDown(object sender, UIMouseDownEventArgs e)
        {
            if (_ownerBeh.HasMouseDown) _ownerBeh.InvokeMouseDown((S)sender, _state, e);
        }
        internal override void ListenMouseEnter(object sender, UIMouseMoveEventArgs e)
        {
            if (_ownerBeh.HasMouseEnter) _ownerBeh.InvokeMouseEnter((S)sender, _state, e);
        }
        internal override void ListenMouseLeave(object sender, UIMouseLeaveEventArgs e)
        {
            if (_ownerBeh.HasMouseLeave) _ownerBeh.InvokeMouseLeave((S)sender, _state, e);
        }
        internal override void ListenMouseMove(object sender, UIMouseMoveEventArgs e)
        {
            if (e.IsDragging)
            {
                if (_ownerBeh.HasMouseDrag)
                {
                    _ownerBeh.InvokeMouseDrag((S)sender, _state, e);
                }
            }
            else
            {
                if (_ownerBeh.HasMouseMove)
                {
                    _ownerBeh.InvokeMouseMove((S)sender, _state, e);
                }
            }

        }
        internal override void ListenMouseUp(object sender, UIMouseUpEventArgs e)
        {
            if (_ownerBeh.HasMouseUp) _ownerBeh.InvokeMouseUp((S)sender, _state, e);
        }
        internal override void ListenMousePress(object sender, UIMousePressEventArgs e)
        {
            if (_ownerBeh.HasMousePress) _ownerBeh.InvokeMousePress((S)sender, _state, e);
        }
        internal override void ListenMouseHover(object sender, UIMouseHoverEventArgs e)
        {
            if (_ownerBeh.HasMouseHover) _ownerBeh.InvokeMouseHover((S)sender, _state, e);
        }
    }

}


text:
//
//  bbPlaybackPosition.m
//  AthensPublic
//
//  Created by Eddie Boswell on 9/27/13.
//  Copyright (c) 2013 Athens Public Access. All rights reserved.
//

#import "bbPlaybackPosition.h"
#import "constants.h"
@implementation bbPlaybackPosition
@synthesize loading,view,slider,currentTime,remainingTime;
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    [self setClipsToBounds:YES];
    if (self) {
        if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
            [[NSBundle mainBundle] loadNibNamed:@"bbPlaybackSlider" owner:self options:nil];
        }else{
            [[NSBundle mainBundle] loadNibNamed:@"bbPlaybackSlider_iPad" owner:self options:nil];
        }
        [self.slider setThumbImage:[UIImage imageNamed:@"slide.png"] forState:UIControlStateNormal];
        [self.slider setThumbImage:[UIImage imageNamed:@"slide.png"] forState:UIControlStateSelected];
        [self.slider setThumbImage:[UIImage imageNamed:@"slide.png"] forState:UIControlStateHighlighted];
        [self.slider setThumbImage:[UIImage imageNamed:@"slide.png"] forState:UIControlStateDisabled];
        [self.slider setThumbImage:[UIImage imageNamed:@"slide.png"] forState:UIControlStateReserved];
        if(SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0")){
            if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
                self.loading.center=CGPointMake(self.loading.center.x,self.loading.center.y+5);
            }else{
                self.loading.center=CGPointMake(self.loading.center.x,self.loading.center.y+5);
                self.slider.center=CGPointMake(self.slider.center.x,self.slider.center.y-5);
            }
        }
        [self addSubview:self.view];
    }
    return self;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

@end


text:
namespace SolrExpress.Core.Search.Parameter
{
    /// <summary>
    /// Signatures to use in limit parameter
    /// </summary>
    public interface ILimitParameter<TDocument> : ISearchParameter
        where TDocument : IDocument
    {
        /// <summary>
        /// Configure current instance
        /// </summary>
        /// <param name="value">Value of limit</param>
        ILimitParameter<TDocument> Configure(long value);

        /// <summary>
        /// Value of limit
        /// </summary>
        long Value { get; }
    }
}


text:
#ifndef                                         __MODEST_HILDON_PANNABLE_AREA_SCROLLABLE_H__
#define                                         __MODEST_HILDON_PANNABLE_AREA_SCROLLABLE_H__

#include <glib-object.h>
#include <modest-scrollable.h>
#include <hildon/hildon-pannable-area.h>

G_BEGIN_DECLS

#define                                         MODEST_TYPE_HILDON_PANNABLE_AREA_SCROLLABLE \
                                                (modest_hildon_pannable_area_scrollable_get_type())

#define                                         MODEST_HILDON_PANNABLE_AREA_SCROLLABLE(obj) \
                                                (G_TYPE_CHECK_INSTANCE_CAST ((obj), \
                                                MODEST_TYPE_HILDON_PANNABLE_AREAS_CROLLABLE, ModestHildonPannableAreaScrollable))

#define                                         MODEST_HILDON_PANNABLE_AREA_SCROLLABLE_CLASS(klass) \
                                                (G_TYPE_CHECK_CLASS_CAST ((klass), \
                                                MODEST_TYPE_HILDON_PANNABLE_AREA_SCROLLABLE, ModestHildonPannableAreaScrollable))

#define                                         MODEST_IS_HILDON_PANNABLE_AREA_SCROLLABLE(obj) \
                                                (G_TYPE_CHECK_INSTANCE_TYPE ((obj), MODEST_TYPE_HILDON_PANNABLE_AREA_SCROLLABLE))

#define                                         MODEST_IS_HILDON_PANNABLE_AREA_SCROLLABLE_CLASS(klass) \
                                                (G_TYPE_CHECK_CLASS_TYPE ((klass), MODEST_TYPE_HILDON_PANNABLE_AREA_SCROLLABLE))

#define                                         MODEST_HILDON_PANNABLE_AREA_SCROLLABLE_GET_CLASS(obj) \
                                                (G_TYPE_INSTANCE_GET_CLASS ((obj), \
                                                MODEST_TYPE_HILDON_PANNABLE_ARE_SCROLLABLE, ModestHildonPannableAreaScrollableClass))

typedef struct                                  _ModestHildonPannableAreaScrollable ModestHildonPannableAreaScrollable;

typedef struct                                  _ModestHildonPannableAreaScrollableClass ModestHildonPannableAreaScrollableClass;

struct                                          _ModestHildonPannableAreaScrollableClass
{
	HildonPannableAreaClass parent_class;

	/* ModestScrollable interface */
	void (*add_with_viewport_func) (ModestScrollable *self, GtkWidget *widget);
	GtkAdjustment * (*get_vadjustment_func) (ModestScrollable *self);
	GtkAdjustment * (*get_hadjustment_func) (ModestScrollable *self);
	void (*scroll_to_func) (ModestScrollable *self, const gint x, const gint y);
	void (*jump_to_func) (ModestScrollable *self, const gint x, const gint y);
	GtkPolicyType (*get_vertical_policy_func) (ModestScrollable *self);
	GtkPolicyType (*get_horizontal_policy_func) (ModestScrollable *self);
	void (*set_vertical_policy_func) (ModestScrollable *self, GtkPolicyType policy);
	void (*set_horizontal_policy_func) (ModestScrollable *self, GtkPolicyType policy);
};

struct                                          _ModestHildonPannableAreaScrollable
{
    HildonPannableArea parent;
};

GType
modest_hildon_pannable_area_scrollable_get_type                       (void) G_GNUC_CONST;

GtkWidget *
modest_hildon_pannable_area_scrollable_new                            (void);

G_END_DECLS

#endif /* __MODEST_WP_TEXT_VIEW_H__ */


text:
namespace internal {

FatalLogMessage::~FatalLogMessage() {
  fprintf(stderr, "Fatal error: %s\n", str().c_str());
  exit(EXIT_FAILURE);
}

} // namespace internal

Timer::Timer() : t1_(std::chrono::high_resolution_clock::now()) {}

double Timer::elapsed() {
  auto t2 = std::chrono::high_resolution_clock::now();
  std::chrono::duration<double> elapsed = t2 - t1_;
  return elapsed.count();
}

namespace {

void usage_and_exit(const std::string& progname) {
  std::cout << "Expecting " << progname << " [flags] <BF file>\n";
  std::cout << "\nSupported flags:\n";
  std::cout << "    --verbose           enable verbose output\n";
  exit(EXIT_SUCCESS);
}

} // namespace {

void parse_command_line(int argc, const char** argv, std::string* bf_file_path,
                        bool* verbose) {
  *verbose = false;

  // This loop handles flags that optionally come before the actual arguments.
  // When it's done, arg_i will point to the first non-flag argument.
  int arg_i = 1;
  for (; arg_i < argc; ++arg_i) {
    std::string arg = argv[arg_i];
    if (!(arg.size() > 2 && arg[0] == '-' && arg[1] == '-')) {
      // If this arg doesn't start with a --, it's not a flag. So we expect it
      // to be the BF program.
      break;
    } else if (arg == "--verbose") {
      *verbose = true;
    } else if (arg == "--help") {
      usage_and_exit(argv[0]);
    } else {
      usage_and_exit(argv[0]);
    }
  }

  if (arg_i >= argc) {
    usage_and_exit(argv[0]);
  }
  *bf_file_path = argv[arg_i];
}


text:
package cn.dmesoft.haibao.modules.haibao.service;

import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.dmesoft.haibao.common.persistence.Page;
import cn.dmesoft.haibao.common.service.CrudService;
import cn.dmesoft.haibao.modules.haibao.entity.Stat;
import cn.dmesoft.haibao.modules.haibao.dao.StatDao;

/**
 * 单表生成Service
 * @author Dmesoft
 * @version 2016-08-22
 */
@Service
@Transactional(readOnly = true)
public class StatService extends CrudService<StatDao, Stat> {

	public Stat get(String id) {
		return super.get(id);
	}

	public List<Stat> findList(Stat stat) {
		return super.findList(stat);
	}

	public Page<Stat> findPage(Page<Stat> page, Stat stat) {
		return super.findPage(page, stat);
	}

	@Transactional(readOnly = false)
	public void save(Stat stat) {
		super.save(stat);
	}

	@Transactional(readOnly = false)
	public void delete(Stat stat) {
		super.delete(stat);
	}

}


text:
package com.infinities.keystone4j.model.common;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;

public class MemberLinks implements java.io.Serializable {

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	private String self;

	@JsonInclude(Include.ALWAYS)
	public String getSelf() {
		return self;
	}

	public void setSelf(String self) {
		this.self = self;
	}

}


text:
layout: blip
name: "Grails"
status: "Assess"
first_added: "October 2016"
site: https://grails.org/
---
Web application framework for JVM built on Spring Boot


text:
from __future__ import (absolute_import, division,
                        print_function, unicode_literals)

import json
import urllib
import urllib2
import sys
import logging
import threading
from time import sleep, time
from scenes.chess import Chess
from cython.functions import tuple_to_chess_notation, chess_notation_to_tuple
from consts.colors import BLACK, WHITE, next
from consts.urls import (
	URL_BASE,
	NEW_GAME,
	JOIN_GAME,
	NEW_MOVE,
	WAITING_MOVE_VALIDATION,
	VALIDATE_MOVE,
	SHOW_MOVE,
	NEW_GAME_OVER_REQUEST,
	WAITING_GAME_OVER_VALIDATION,
	SHOW_GAME_OVER,
	SUCCESS,
	SUCCESS_CODES
)
from consts.pieces import (
	PAWN,
	KNIGHT,
	BISHOP,
	ROOK,
	QUEEN,
	KING,
)

INVALID_REQUEST = "INVALID REQUEST"
INVALID_TURN = "INVALID TURN"

PROMOTION_MAP = {
	0: ROOK,
	1: KNIGHT,
	2: BISHOP,
	3: QUEEN,
	4: KING,
	5: PAWN
}

def html_request(url, method, values={}):
	try:
		data = urllib.urlencode(values)
		request = urllib2.Request(url, data)
		request.get_method = lambda: method
		result = json.load(urllib2.urlopen(request))
		if not result['code'] in SUCCESS_CODES:
			raise Exception(INVALID_REQUEST, result['code'], result['message'])
		if not result['code'] == 19:
			if 'board' in result:
				del result['board']
			print(time(), result)
		return result
	except Exception as e:
		logging.exception('URL {0} {1}\n{3}\n{2}'.format(
			method, url, str(e), values
		))
		raise e

def post(url, values={}):
	return html_request(url, 'POST', values)

def get(url, values={}):
	return html_request(url, 'GET', values)

class OnlineChess(Chess):

	def __init__(self, game, level_white, level_black, id=None, *args, **kwargs):
		if level_white != -1:
			data = post(URL_BASE + NEW_GAME, {'player_name': 'wgrupo1'})
			self.online = BLACK
			self.player_key = data['player_key']
			self.game_id = data['game_id']
			self.player_name = 'wgrupo1'

		if level_black != -1:
			self.game_id = id
			data = post(URL_BASE + JOIN_GAME, {
				'player_name': 'bgrupo1',
				'game_id': self.game_id,
			})
			self.online = WHITE
			self.player_key = data['player_key']
			self.player_name = 'bgrupo1'
		self.sent_end_game = False
		super(OnlineChess, self).__init__(game, level_white, level_black, *args, **kwargs)
		threading.Thread(target=self.wait_end_game_validation).start()

	def do_move(self, selected, square, promotion=5):
		color = self.board.color()
		move = self.board.move(selected, square, promotion)
		if self.online == color:
			data = post(URL_BASE + VALIDATE_MOVE, {
				'move_id': self.move_id,
				'player_key': self.player_key,
				'valid': 'true' if move else 'false'
			})
			return move
		elif move:
			move_type = move.type()
			param = {
				'game_id': self.game_id,
				'player_key': self.player_key,
				'type': move_type
			}
			if move_type in [0, 2, 3]:
				param['move_from'] = tuple_to_chess_notation(selected)
				param['move_to'] = tuple_to_chess_notation(square)
			if move_type == 1: #castling
				param['rook_from'] = tuple_to_chess_notation(move.rook_from())
				param['rook_to'] = tuple_to_chess_notation(move.rook_to())
				param['king_from'] = tuple_to_chess_notation(selected)
				param['king_to'] = tuple_to_chess_notation(square)

			if move_type == 2: #en passant
				param['eliminated_pawn'] = tuple_to_chess_notation(
					move.get_eliminated_pawn())
			if move_type == 3: #promotion
				param['promotion_type'] = 3 #queen

			data = post(URL_BASE + NEW_MOVE, param)
			self.move_id = data['move']['id']
			while self.running:
				self.do_jit_draw()
				data = get(URL_BASE + SHOW_MOVE.format(self.move_id))
				if data['move']['validation_time']:
					if not data['move']['legal']:
						move.undo_update(self.board)
						return False
					else:
						return move
				sleep(3)
		return False

	def wait_move_validation(self):
		while self.running:
			data = get(URL_BASE + WAITING_MOVE_VALIDATION, {
				'game_id': self.game_id
			})
			if 'move' in data:
				self.move_id = data['move']['id']
				move_type = data['move']['move_type']
				move = data['move']['movimentations'][0]
				if move_type == 1: #castling
					for move in data['move']['movimentations']:
						if move['from'] in ['e1', 'e8']:
							return (
								chess_notation_to_tuple(move['from']),
								chess_notation_to_tuple(move['to']),
								5
							)
				elif move_type == 3: #promotion
					return (
						chess_notation_to_tuple(move['from']),
						chess_notation_to_tuple(move['to']),
						PROMOTION_MAP[data['move']['promotion_type']]
					)
				return (
					chess_notation_to_tuple(move['from']),
					chess_notation_to_tuple(move['to']),
					5
				)
			sleep(3)

	def wait_end_game_validation(self):
		while self.running:
			if self.sent_end_game:
				continue
			data = get(URL_BASE + WAITING_GAME_OVER_VALIDATION, {
				'game_id': self.game_id
			})
			if 'game_over_request' in data:
				request = data['game_over_request']
				if request['winner'] == self.player_name:
					self.end_game(1 if self.online == BLACK else -1)
				else:
					end = self.verify_status(self.board.status(None))
					if not end:
						if not request['winner']:
							self.sent_end_game = True
							self.other_player.confirm_draw()
						else:
							self.send_illigal_endgame()

	def request_draw(self):
		self.end_game(0)

	def send_illigal_endgame(self):
		post(URL_BASE + NEW_GAME_OVER_REQUEST, {
			'game_id': self.game_id,
			'player_key': self.player_key,
			'result': 1
		})

	def deny_draw(self, player, send=True):
		if send:
			self.send_illigal_endgame()
		Chess.deny_draw(self, player)
		self.sent_end_game = False

	def end_game(self, state):
		self.sent_end_game = True
		data = post(URL_BASE + NEW_GAME_OVER_REQUEST, {
			'game_id': self.game_id,
			'player_key': self.player_key,
			'result': state * (1 if self.online == BLACK else -1)
		})
		self.game_over_request_id = data['game_over_request_id']
		if data['code'] == 14:
			Chess.end_game(self, state)
		while self.running:
			data = get(URL_BASE + SHOW_GAME_OVER.format(
				self.game_over_request_id
			))
			if data['game_over_request']['validation_time']:
				if data['game_over_request']['legal']:
					Chess.end_game(self, state)
					#self.sent_end_game = False
				else:
					self.deny_draw(self.current_player, send=False)
				return None
			sleep(3)


text:
begin
require 'rails/railtie'
rescue LoadError
else

module ActiveModel
  # Set up the signed GlobalID verifier and include Active Record support for
  # #global_id and #signed_global_id.
  class Railtie < Rails::Railtie # :nodoc:
    initializer "active_model.globalid" do
      config.after_initialize do |app|
        ActiveModel::SignedGlobalID.verifier = app.message_verifier(:signed_global_ids)
      end

      ActiveSupport.on_load(:active_record) do
        require 'active_model/global_identification'
        send :include, ActiveModel::GlobalIdentification
      end
    end
  end
end

end


text:
FactoryGirl.define do
  factory :gift_card_type do
    value { rand(100).to_d }
    valid_for { GiftCardType::VALID_INTERVAL_IN_MONTH.shuffle.first }
    company { Company.first || FactoryGirl.create(:company) }
  end
end


text: A HipChat bot for sending regular reminders to a room.


text:
This is a library to work with NASA's astronomy pictures of the day.
It also includes the script, apod-download, which will download the
current picture of the day to your computer.

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'apod'
```

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install apod

## Usage

This library comes with an executable, apod-download, which can be used
to download the current picture of the day.  For usage, run:

```apod -h```

## Development

After checking out the repo, run `bin/setup` to install dependencies. Then, run `bin/console` for an interactive prompt that will allow you to experiment. Run `bundle exec apod` to use the code located in this directory, ignoring other installed copies of this gem.

To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release` to create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).

## Contributing

1. Fork it ( https://github.com/[my-github-username]/apod/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request


text:
package jsint;

public class LexicalEnvironment implements java.io.Serializable {

/** The global environment.  All info is in the Symbols themselves. **/
public static final LexicalEnvironment NULLENV
    = new LexicalEnvironment(Pair.EMPTY, null, null, true);

/** The parent LexicalEnvironment: where you look if you can't find
 * a variable.
 **/
private LexicalEnvironment parent;
/** A list of variables in this env.  May be dotted or a lone
 * symbol.
 **/
private Object vars;
/** An array of values in a 1-1 correspondance with the vars. **/
private Object[] vals;

private boolean isNullEnv = false;

/** Create an LexicalEnvironment with local variables and values,
 * and a parent LexicalEnvironment.
 **/
public LexicalEnvironment(Object vars, Object[] vals,
                          LexicalEnvironment parent) {
    this(vars, vals, parent, false);
}

public LexicalEnvironment(Object vars, Object[] vals,
                          LexicalEnvironment parent, boolean isNullEnv) {
    this.vars = vars; this.vals = vals; this.parent = parent;
    this.isNullEnv = isNullEnv;
}

private Object readResolve() throws java.io.ObjectStreamException {
    return isNullEnv ? NULLENV : this;
}

public LocalVariable lookup(Symbol var) { return lookup(var, 0, 0, vars); }

/** Lookup the symbol in the environment.  Return either a
 * LocalVariable a Symbol representing the global variable.
 **/
public LocalVariable lookup(Symbol var, int up, int in, Object vars) {
    if (this == NULLENV) { return null; }
    else if (vars == var) { return new LocalVariable(up, in, var); }
    else if (!U.isPair(vars)) { return parent.lookup(var, up + 1, 0, parent.vars); }
    else if (U.first(vars) == var) { return new LocalVariable(up, in, var); }
    else { return lookup(var, up, in + 1, U.rest(vars)); }
}

/** Get the value of the LocalVariable in this LexicalEnvironment. **/
public Object get(LocalVariable var) {
    return this.up(var.up).vals[var.in];
}

/** Set the value of the LocalVariable in this LexicalEnvironment to
 * a new value.
 **/
public Object set(LocalVariable var, Object newVal) {
    return this.up(var.up).vals[var.in] = newVal;
}

/** Go up a specified number of levels in the parent chain. **/
LexicalEnvironment up(int levels) {
    return (levels == 0) ? this : this.parent.up(levels - 1);
}

public String toString() {
    return "{|" + toString0() + "|}";
}
private String toString0() {
    if (this == NULLENV) { return ""; }
    else return U.stringify(vars) + " " + U.stringify(vals) +
                    ((parent == null) ? "" : "|" + parent.toString0());
}

public void show(java.io.PrintWriter s) {
    LexicalEnvironment e = this;
    while (e != NULLENV) {
        Object vars = e.vars;
        Object[] vals = e.vals;
        int i = 0;
        while (U.isPair(vars)) {
            show0(s, U.first(vars), vals[i]);
            vars = U.rest(vars);
            i = i + 1;
        }
        if (vars != Pair.EMPTY) { show0(s, vars, vals[i]); }
        e = e.parent;
    }
}

private static void show0(java.io.PrintWriter s, Object var, Object val) {
    String sval = showValue(val);
    if (sval.length() > 100) { sval = sval.substring(0, 100) + "..."; }
    s.println("  " + U.stringify(var) + " = " + sval);
}

private static String showValue(Object x) {
    if (BacktraceException.checkBacktrace()) {
        Object btvsProc = Scheme.currentEvaluator().getInteractionEnvironment().
                          getValue(Symbol.intern("backtraceValueString"));
        return (String) U.toProc(btvsProc).apply(jscheme.JScheme.list(x));
    } else { return (x == null) ? "null" : x.toString(); }
}
}


text:
build/crawler &
build/web


text:
<?php

/**
 * Session Module
 *
 * @author Bálint Horváth <balint@snett.net>
 */

namespace Franklin\IO;

class Session {

    public $System;

    private $Name;

    public function __construct($System, $Name="") {
        $this->System = $System;
        if (empty($Name)){
            $this->Name = "Franklin." . rand(10001, 28000) . "." . date("His");
        } else{
            $this->Name = $Name;
        }
        $this->Start();
    }

    public function Set($Name, $Value) {
        $_SESSION[$Name] = $Value;
    }

    public function Get($Name) {
        return($_SESSION[$Name]);
    }

    public function getName() {
        return($this->Name);
    }

    public function Start() {
        //session_name($this->Name);
        session_start();
    }

    public function Close() {
        session_write_close();
        session_destroy();
    }

}


text:
@interface CKGoogleMapsViewController : UIViewController

@end


text:
namespace doppia
{

using namespace boost;

program_options::options_description AbstractVideoInput::get_args_options()
{

    using boost::program_options::value;

    program_options::options_description desc("AbstractVideoInput options");

    desc.add_options()

            // FIXME this is a hack, should have a proto file to describe the ground plane model
            // or at least move it into camera_calibration ?
            ("video_input.camera_height", value<float>()->default_value(1.2f),
             "specify the distance in meters to the ground plane")
            ("video_input.camera_pitch", value<float>()->default_value(0.0f),
             "define the pitch angle in radians with respect to the ground plane. This value will typically be a small negative value.")
            ("video_input.camera_roll", value<float>()->default_value(0.0f),
             "define the roll angle with respect to the ground plane")

            ;

    return desc;
}

AbstractVideoInput::AbstractVideoInput(const program_options::variables_map &options)
    : current_frame_number(0)
{

    camera_height =
            get_option_value<float>(options, "video_input.camera_height");
    camera_pitch =
            get_option_value<float>(options, "video_input.camera_pitch");
    camera_roll =
            get_option_value<float>(options, "video_input.camera_roll");

    return;
}

AbstractVideoInput::~AbstractVideoInput()
{
    // nothing to do here
    return;
}

int AbstractVideoInput::get_current_frame_number() const
{
    return this->current_frame_number;
}

const MetricStereoCamera& AbstractVideoInput::get_metric_camera() const
{
    if(metric_camera_p == false)
    {
        metric_camera_p.reset(new MetricStereoCamera(this->get_stereo_calibration()));
    }

    return *metric_camera_p;
}

} // end of namespace doppia


text:
<?php

namespace mageekguy\atoum\asserters;

use
	mageekguy\atoum\asserters,
	mageekguy\atoum\exceptions
;

class dateTime extends asserters\object
{
	public function setWith($value, $checkType = true)
	{
		parent::setWith($value, false);

		if ($checkType === true)
		{
			if (self::isDateTime($this->value) === false)
			{
				$this->fail(sprintf($this->getLocale()->_('%s is not an instance of \\dateTime'), $this));
			}
			else
			{
				$this->pass();
			}
		}

		return $this;
	}

	public function hasTimezone(\dateTimezone $timezone, $failMessage = null)
	{
		if ($this->valueIsSet()->value->getTimezone()->getName() == $timezone->getName())
		{
			$this->pass();
		}
		else
		{
			$this->fail($failMessage !== null ? $failMessage : sprintf($this->getLocale()->_('Timezone is %s instead of %s'), $this->value->getTimezone()->getName(), $timezone->getName()));
		}

		return $this;
	}

	public function hasYear($year, $failMessage = null)
	{
		if ($this->valueIsSet()->value->format('Y') === sprintf('%04d', $year))
		{
			$this->pass();
		}
		else
		{
			$this->fail($failMessage !== null ? $failMessage : sprintf($this->getLocale()->_('Year is %s instead of %s'), $this->value->format('Y'), $year));
		}

		return $this;
	}

	public function isInYear()
	{
		die('The method ' . __METHOD__ . ' is deprecated, please use ' . __CLASS__ . '::hasYear instead');
	}

	public function hasMonth($month, $failMessage = null)
	{
		if ($this->valueIsSet()->value->format('m') === sprintf('%02d', $month))
		{
			$this->pass();
		}
		else
		{
			$this->fail($failMessage !== null ? $failMessage : sprintf($this->getLocale()->_('Month is %s instead of %02d'), $this->value->format('m'), $month));
		}

		return $this;
	}

	public function isInMonth()
	{
		die('The method ' . __METHOD__ . ' is deprecated, please use ' . __CLASS__ . '::hasMonth instead');
	}

	public function hasDay($day, $failMessage = null)
	{
		if ($this->valueIsSet()->value->format('d') === sprintf('%02d', $day))
		{
			$this->pass();
		}
		else
		{
			$this->fail($failMessage !== null ? $failMessage : sprintf($this->getLocale()->_('Day is %s instead of %02d'), $this->value->format('d'), $day));
		}

		return $this;
	}

	public function isInDay()
	{
		die('The method ' . __METHOD__ . ' is deprecated, please use ' . __CLASS__ . '::hasDay instead');
	}

	public function hasDate($year, $month, $day, $failMessage = null)
	{
		if ($this->valueIsSet()->value->format('Y-m-d') === sprintf('%04d-%02d-%02d', $year, $month, $day))
		{
			$this->pass();
		}
		else
		{
			$this->fail($failMessage !== null ? $failMessage : sprintf($this->getLocale()->_('Date is %s instead of %s'), $this->value->format('Y-m-d'), sprintf('%04d-%02d-%02d', $year, $month, $day)));
		}

		return $this;
	}

	public function hasHours($hours, $failMessage = null)
	{
		if ($this->valueIsSet()->value->format('H') === sprintf('%02d', $hours))
		{
			$this->pass();
		}
		else
		{
			$this->fail($failMessage !== null ? $failMessage : sprintf($this->getLocale()->_('Hours are %s instead of %02d'), $this->value->format('H'), $hours));
		}

		return $this;
	}

	public function hasMinutes($minutes, $failMessage = null)
	{
		if ($this->valueIsSet()->value->format('i') === sprintf('%02d', $minutes))
		{
			$this->pass();
		}
		else
		{
			$this->fail($failMessage !== null ? $failMessage : sprintf($this->getLocale()->_('Minutes are %s instead of %02d'), $this->value->format('i'), $minutes));
		}

		return $this;
	}

	public function hasSeconds($seconds, $failMessage = null)
	{
		if ($this->valueIsSet()->value->format('s') === sprintf('%02d', $seconds))
		{
			$this->pass();
		}
		else
		{
			$this->fail($failMessage !== null ? $failMessage : sprintf($this->getLocale()->_('Seconds are %s instead of %02d'), $this->value->format('s'), $seconds));
		}

		return $this;
	}

	public function hasTime($hours, $minutes, $seconds, $failMessage = null)
	{
		if ($this->valueIsSet()->value->format('H:i:s') === sprintf('%02d:%02d:%02d', $hours, $minutes, $seconds))
		{
			$this->pass();
		}
		else
		{
			$this->fail($failMessage !== null ? $failMessage : sprintf($this->getLocale()->_('Time is %s instead of %s'), $this->value->format('H:i:s'), sprintf('%02d:%02d:%02d', $hours, $minutes, $seconds)));
		}

		return $this;
	}

	public function hasDateAndTime($year, $month, $day, $hours, $minutes, $seconds, $failMessage = null)
	{
		if ($this->valueIsSet()->value->format('Y-m-d H:i:s') === sprintf('%04d-%02d-%02d %02d:%02d:%02d', $year, $month, $day, $hours, $minutes, $seconds))
		{
			$this->pass();
		}
		else
		{
			$this->fail($failMessage !== null ? $failMessage : sprintf($this->getLocale()->_('Datetime is %s instead of %s'), $this->value->format('Y-m-d H:i:s'), sprintf('%04d-%02d-%02d %02d:%02d:%02d', $year, $month, $day, $hours, $minutes, $seconds)));
		}

		return $this;
	}

	protected function valueIsSet($message = 'Instance of \dateTime is undefined')
	{
		if (self::isDateTime(parent::valueIsSet($message)->value) === false)
		{
			throw new exceptions\logic($message);
		}

		return $this;
	}

	protected static function check($value, $method)
	{
		if (self::isDateTime($value) === false)
		{
			throw new exceptions\logic('Argument of ' . $method . '() must be an instance of \\dateTime');
		}
	}

	protected static function isDateTime($value)
	{
		return ($value instanceof \dateTime);
	}
}


text:
package com.orientechnologies.orient.core.index;

import com.orientechnologies.orient.core.db.ODatabaseDocumentInternal;

/**
 * Transactional wrapper for dictionary index. Stores changes locally to the transaction until
 * tx.commit(). All the other operations are delegated to the wrapped OIndex instance.
 *
 * @author Luca Garulli (l.garulli--(at)--orientdb.com)
 */
public class OIndexTxAwareDictionary extends OIndexTxAwareOneValue {
  public OIndexTxAwareDictionary(ODatabaseDocumentInternal iDatabase, OIndexInternal delegate) {
    super(iDatabase, delegate);
  }
}


text:
import os
from flask import Response, request, g
import zipfile
import shutil
from refinery import app, db
from refinery.data.models import Dataset, Document, DataDoc, Folder
from refinery.webapp.pubsub import msgServer

def add_txt(path, fid, filename, dataset):

    doc = Document(filename, path)
    db.session.add(doc)
    db.session.commit() #sets the primary key
    target = file(path, "wb")
    shutil.copyfileobj(fid, target)

    data_doc = DataDoc(dataset.id, doc.id)
    db.session.add(data_doc)

    doc_ids = dataset.folders[0].docIDs

    doc_ids[doc.id] = 0 #how do i make a hash set?
    db.session.commit()
    folder = Folder.query.get(dataset.folders[0].id)

    folder.docIDs = doc_ids

    db.session.commit()

    return doc.id

# Initiates the upload process once files have been dropped in
@app.route('/<username>/upload/drop/', methods=['POST'])
def upload_drop(username=None):

    name = "My New Dataset"
    summary = "A summary of the dataset"
    user_id = g.user.id

    dset = Dataset(user_id,name,summary)
    db.session.add(dset)
    db.session.commit()
    did = dset.id

    main_folder = Folder(dset.id,"Main Folder",dict())
    db.session.add(main_folder)
    db.session.commit()

    main_folder.initialize()
    db.session.commit()

    print "DROP"

    dset = Dataset.query.get(did)

    ufilename = request.form['filename']
    fid = request.files.getlist('file')[0]  #grab only a single file

    fn,ext = os.path.splitext(ufilename)

    userpath = "refinery/static/users/" + username + "/documents"
    channel = username + "Xmenus"

    if ext == ".zip":
        zip_file = zipfile.ZipFile(fid)
        files = zip_file.namelist()
        nFiles = len(files)
        lastProg = 0
        count = 0.0
        for member in files:
            filename = os.path.basename(member)
            if filename:
                fn,ext = os.path.splitext(filename)
                if ext == ".txt" or ext == ".pdf":
                    add_txt(os.path.join(userpath,filename),zip_file.open(member),filename,dset)
            count += 1.0
            update = str(int(count / float(nFiles) * 100))
            if update != lastProg:
                lastProg = update
                s = 'uprog,' + update
                msgServer.publish(channel, "%s" % s)

    elif ext == ".txt" or ext == ".pdf":
        add_txt(os.path.join(userpath,filename),fid,filename,dset)

    elif ext == ".tar" or ext == ".gz" or ext == ".bz2":
        import tarfile
        tar_file = tarfile.open(fileobj=fid)
        tar_filename = os.path.join(userpath,ufilename)
        valid_names = [x for x in tar_file.getnames() if (os.path.splitext(x)[1] == '.txt') or (os.path.splitext(x)[1] == '.pdf')]
        nFiles = len(valid_names)
        print nFiles
        lastProg = 0
        count = 0.0
        for member in valid_names:
            filename = os.path.basename(member)
            if filename:
                add_txt(os.path.join(userpath,filename), tar_file.extractfile(member),filename,dset)
            count += 1.0
            update = str(int(count / float(nFiles) * 100))
            if update != lastProg:
                lastProg = update
                s = 'uprog,' + update
                msgServer.publish(channel, "%s" % s)

    else:
        print "unknown file format",ext,filename

    dset.dirty = "dirty"

    db.session.commit()

    print "GOT ",len(dset.folders[0].docIDs), "Documents"

    msgServer.publish(channel, "ucomplete," + ufilename)

    return Response(status="200")


text:
module DevelopmentModeStubs
  class FakeRummagerApiForStatisticsAnnouncements
    def self.advanced_search(params = {})
      raise ArgumentError.new(":page and :per_page are required") unless params[:page].present? && params[:per_page].present?
      raise_unless_values_are_strings(params)

      scope = ::StatisticsAnnouncement.joins(:current_release_date).order("statistics_announcement_dates.release_date ASC")
      scope = scope.where("statistics_announcements.title LIKE('%#{params[:keywords]}%') or statistics_announcements.summary LIKE('%#{params[:keywords]}%')") if params[:keywords].present?
      if params[:organisations].present?
        organisation_ids = Organisation.where(slug: params[:organisations]).pluck(:id)
        scope = scope.in_organisations(organisation_ids)
      end
      if params[:topics].present?
        topic_ids = Topic.where(slug: params[:topics]).pluck(:id)
        scope = scope.with_topics(topic_ids)
      end
      if params[:release_timestamp].present?
        scope = scope.where("statistics_announcement_dates.release_date > ?", params[:release_timestamp][:from]) if params[:release_timestamp][:from].present?
        scope = scope.where("statistics_announcement_dates.release_date < ?", params[:release_timestamp][:to]) if params[:release_timestamp][:to].present?
      end
      if params[:statistics_announcement_state] == 'cancelled'
        scope = scope.where("cancelled_at IS NOT NULL")
      end

      scope = scope.group("statistics_announcements.id")
      count = scope.length
      scope = scope.limit(params[:per_page]).offset((params[:page].to_i - 1) * params[:per_page].to_i)

      {
        'total' => count,
        'results' => scope.map { |announcement| announcement_to_rummager_hash(announcement) }
      }
    end

  private
    def self.raise_unless_values_are_strings(param_hash)
      param_hash.each do |key, value|
        if value.is_a? Hash
          raise_unless_values_are_strings(value)
        elsif !(value.is_a?(String) || value.is_a?(Array))
          raise ArgumentError.new("Search paramaters must be provided as strings, :#{key} was a #{value.class.name}")
        end
      end
    end

    def self.announcement_to_rummager_hash(announcement)
      {
        "title" => announcement.title,
        "description" => announcement.summary,
        "slug" => announcement.slug,
        "release_timestamp" => announcement.current_release_date.release_date.iso8601,
        "organisations" => announcement.organisations_slugs,
        "topics" => announcement.topic_slugs,
        "display_type" => announcement.publication_type.singular_name,
        "search_format_types" => ["statistics_announcement"],
        "format" => "statistics_announcement",
        "statistics_announcement_state" => announcement.state,
        "metadata" => {
          "confirmed" => announcement.current_release_date.confirmed,
          "display_date" => announcement.current_release_date.display_date,
          "change_note" => announcement.last_change_note,
          "previous_display_date" => announcement.previous_display_date,
          "cancellation_reason" => announcement.cancellation_reason,
          "cancellation_date" => announcement.cancelled_at,
        }
      }
    end
  end
end


text:
// this file was created by SCC 2019 and is largely a derived work from the
// original java class/interface

package org.orekit.propagation;

import org.hipparchus.CalculusFieldElement;
import org.orekit.attitudes.AttitudeProvider;
import org.orekit.frames.Frame;
import org.orekit.propagation.events.FieldEventDetector;
import org.orekit.propagation.integration.FieldAbstractIntegratedPropagator;
import org.orekit.propagation.integration.FieldAdditionalEquations;
import org.orekit.propagation.sampling.FieldOrekitFixedStepHandler;
import org.orekit.propagation.sampling.FieldOrekitStepHandler;
import org.orekit.propagation.sampling.FieldStepHandlerMultiplexer;
import org.orekit.time.FieldAbsoluteDate;
import org.orekit.utils.TimeStampedFieldPVCoordinates;

public class PythonFieldPropagator<T extends CalculusFieldElement<T>> implements FieldPropagator<T> {

    /** Part of JCC Python interface to object */
    private long pythonObject;

    /** Part of JCC Python interface to object */
    public void pythonExtension(long pythonObject)
    {
        this.pythonObject = pythonObject;
    }

    /** Part of JCC Python interface to object */
    public long pythonExtension()
    {
        return this.pythonObject;
    }

    /** Part of JCC Python interface to object */
    public void finalize()
            throws Throwable
    {
        pythonDecRef();
    }

    /** Part of JCC Python interface to object */
    public native void pythonDecRef();

    /**
     * Get the current operating mode of the propagator.
     *
     * @return one of {@link #SLAVE_MODE}, {@link #MASTER_MODE},
     * {@link #EPHEMERIS_GENERATION_MODE}
     * @see #setSlaveMode()
     * @see #setMasterMode(CalculusFieldElement, FieldOrekitFixedStepHandler)
     * @see #setMasterMode(FieldOrekitStepHandler)
     * @see #setEphemerisMode()
     */
    @Override
    public native int getMode();

    /**
     * Set the propagator to slave mode.
     *
This mode is used when the user needs only the final orbit at the target time.
     * The (slave) propagator computes this result and return it to the calling
     * (master) application, without any intermediate feedback.

     *
This is the default mode.

     *
     * @see #setMasterMode(CalculusFieldElement, FieldOrekitFixedStepHandler)
     * @see #setMasterMode(FieldOrekitStepHandler)
     * @see #setEphemerisMode()
     * @see #getMode()
     * @see #SLAVE_MODE
     */
    @Override
    public native void setSlaveMode();

    /**
     * Set the propagator to master mode with fixed steps.
     *
This mode is used when the user needs to have some custom function called at the
     * end of each finalized step during integration. The (master) propagator integration
     * loop calls the (slave) application callback methods at each finalized step.

     *
     * @param h       fixed stepsize (s)
     * @param handler handler called at the end of each finalized step
     * @see #setSlaveMode()
     * @see #setMasterMode(FieldOrekitStepHandler)
     * @see #setEphemerisMode()
     * @see #getMode()
     * @see #MASTER_MODE
     */
    @Override
    public void setMasterMode(T h, FieldOrekitFixedStepHandler<T> handler) {
        this.setMasterMode_TF(h, handler);
    }

    /**
     * Set the propagator to master mode with fixed steps.
     *
This mode is used when the user needs to have some custom function called at the
     * end of each finalized step during integration. The (master) propagator integration
     * loop calls the (slave) application callback methods at each finalized step.

     *
     * @param h       fixed stepsize (s)
     * @param handler handler called at the end of each finalized step
     * @see #setSlaveMode()
     * @see #setMasterMode(FieldOrekitStepHandler)
     * @see #setEphemerisMode()
     * @see #getMode()
     * @see #MASTER_MODE
     */
    public native void setMasterMode_TF(T h, FieldOrekitFixedStepHandler<T> handler);

    /**
     * Set the propagator to master mode with variable steps.
     *
This mode is used when the user needs to have some custom function called at the
     * end of each finalized step during integration. The (master) propagator integration
     * loop calls the (slave) application callback methods at each finalized step.

     *
     * @param handler handler called at the end of each finalized step
     * @see #setSlaveMode()
     * @see #setMasterMode(CalculusFieldElement, FieldOrekitFixedStepHandler)
     * @see #setEphemerisMode()
     * @see #getMode()
     * @see #MASTER_MODE
     */
    @Override
    public native void setMasterMode(FieldOrekitStepHandler<T> handler);

    /**
     * Set the propagator to ephemeris generation mode.
     *
This mode is used when the user needs random access to the orbit state at any time
     * between the initial and target times, and in no sequential order. A typical example is
     * the implementation of search and iterative algorithms that may navigate forward and
     * backward inside the propagation range before finding their result.

     *
Beware that since this mode stores all intermediate results,
     * it may be memory intensive for long integration ranges and high precision/short
     * time steps.

     *
     * @see #getGeneratedEphemeris()
     * @see #setSlaveMode()
     * @see #setMasterMode(CalculusFieldElement, FieldOrekitFixedStepHandler)
     * @see #setMasterMode(FieldOrekitStepHandler)
     * @see #getMode()
     * @see #EPHEMERIS_GENERATION_MODE
     */
    @Override
    public native void setEphemerisMode();

    /**
     * Get the ephemeris generated during propagation.
     *
     * @return generated ephemeris
     * @throws IllegalStateException if the propagator was not set in ephemeris
     *                               generation mode before propagation
     * @see #setEphemerisMode()
     */
    @Override
    public native FieldBoundedPropagator<T> getGeneratedEphemeris() throws IllegalStateException;

    /**
     * Get the multiplexer holding all step handlers.
     *
     * @return multiplexer holding all step handlers
     * @since 11.0
     */
    @Override
    public native FieldStepHandlerMultiplexer<T> getMultiplexer();

    /**
     * Set up an ephemeris generator that will monitor the propagation for building
     * an ephemeris from it once completed.
     *
     *

     * This generator can be used when the user needs fast random access to the orbit
     * state at any time between the initial and target times. A typical example is the
     * implementation of search and iterative algorithms that may navigate forward and
     * backward inside the propagation range before finding their result even if the
     * propagator used is integration-based and only goes from one initial time to one
     * target time.
     *

     *

     * Beware that when used with integration-based propagators, the generator will
     * store all intermediate results. It is therefore memory intensive
     * for long integration-based ranges and high precision/short time steps. When
     * used with analytical propagators, the generator only stores start/stop time
     * and a reference to the analytical propagator itself to call it back as needed,
     * so it is less memory intensive.
     *

     *

     * The returned ephemeris generator will be initially empty, it will be filled
     * with propagation data when a subsequent call to either {@link #propagate(FieldAbsoluteDate)
     * propagate(target)} or {@link #propagate(FieldAbsoluteDate, FieldAbsoluteDate)
     * propagate(start, target)} is called. The proper way to use this method is
     * therefore to do:
     *

     *

     *   FieldEphemerisGenerator<T> generator = propagator.getEphemerisGenerator();
     *   propagator.propagate(target);
     *   FieldBoundedPropagator<T> ephemeris = generator.getGeneratedEphemeris();
     *

     *
     * @return ephemeris generator
     */
    @Override
    public FieldEphemerisGenerator<T> getEphemerisGenerator() {
        return null;
    }

    /**
     * Get the propagator initial state.
     *
     * @return initial state
     */
    @Override
    public native FieldSpacecraftState<T> getInitialState();

    /**
     * Reset the propagator initial state.
     *
     * @param state new initial state to consider
     */
    @Override
    public native void resetInitialState(FieldSpacecraftState<T> state);

    /**
     * Add a set of user-specified state parameters to be computed along with the orbit propagation.
     *
     * @param additionalStateProvider provider for additional state
     */
    @Override
    public native void addAdditionalStateProvider(FieldAdditionalStateProvider<T> additionalStateProvider);

    /**
     * Get an unmodifiable list of providers for additional state.
     *
     * @return providers for the additional states
     */
    @Override
    public native List<FieldAdditionalStateProvider<T>> getAdditionalStateProviders();

    /**
     * Check if an additional state is managed.
     *

     * Managed states are states for which the propagators know how to compute
     * its evolution. They correspond to additional states for which an
     * {@link FieldAdditionalStateProvider additional state provider} has been registered
     * by calling the {@link #addAdditionalStateProvider(FieldAdditionalStateProvider)
     * addAdditionalStateProvider} method. If the propagator is an {@link
     * FieldAbstractIntegratedPropagator integrator-based
     * propagator}, the states for which a set of {@link
     * FieldAdditionalEquations additional equations} has
     * been registered by calling the {@link
     * FieldAbstractIntegratedPropagator#addAdditionalEquations(
     *FieldAdditionalEquations) addAdditionalEquations}
     * method are also counted as managed additional states.
     *

     *

     * Additional states that are present in the {@link #getInitialState() initial state}
     * but have no evolution method registered are not considered as managed states.
     * These unmanaged additional states are not lost during propagation, though. Their
     * value will simply be copied unchanged throughout propagation.
     *

     *
     * @param name name of the additional state
     * @return true if the additional state is managed
     */
    @Override
    public native boolean isAdditionalStateManaged(String name);

    /**
     * Get all the names of all managed states.
     *
     * @return names of all managed states
     */
    @Override
    public native String[] getManagedAdditionalStates();

    /**
     * Add an event detector.
     *
     * @param detector event detector to add
     * @see #clearEventsDetectors()
     * @see #getEventsDetectors()
     */
    @Override
    public native <D extends FieldEventDetector<T>> void addEventDetector(D detector);

    /**
     * Get all the events detectors that have been added.
     *
     * @return an unmodifiable collection of the added detectors
     * @see #addEventDetector(FieldEventDetector)
     * @see #clearEventsDetectors()
     */
    @Override
    public native Collection<FieldEventDetector<T>> getEventsDetectors();

    /**
     * Remove all events detectors.
     *
     * @see #addEventDetector(FieldEventDetector)
     * @see #getEventsDetectors()
     */
    @Override
    public native void clearEventsDetectors();

    /**
     * Get attitude provider.
     *
     * @return attitude provider
     */
    @Override
    public native AttitudeProvider getAttitudeProvider();

    /**
     * Set attitude provider.
     *
     * @param attitudeProvider attitude provider
     */
    @Override
    public native void setAttitudeProvider(AttitudeProvider attitudeProvider);

    /**
     * Get the frame in which the orbit is propagated.
     *

     * The propagation frame is the definition frame of the initial
     * state, so this method should be called after this state has
     * been set, otherwise it may return null.
     *

     *
     * @return frame in which the orbit is propagated
     * @see #resetInitialState(FieldSpacecraftState)
     */
    @Override
    public native Frame getFrame();

    /**
     * Propagate towards a target date.
     *
Simple propagators use only the target date as the specification for
     * computing the propagated state. More feature rich propagators can consider
     * other information and provide different operating modes or G-stop
     * facilities to stop at pinpointed events occurrences. In these cases, the
     * target date is only a hint, not a mandatory objective.

     *
     * @param target target date towards which orbit state should be propagated
     * @return propagated state
     */
    @Override
    public native FieldSpacecraftState<T> propagate(FieldAbsoluteDate<T> target);

    /**
     * Propagate from a start date towards a target date.
     *
Those propagators use a start date and a target date to
     * compute the propagated state. For propagators using event detection mechanism,
     * if the provided start date is different from the initial state date, a first,
     * simple propagation is performed, without processing any event computation.
     * Then complete propagation is performed from start date to target date.

     *
     * @param start  start date from which orbit state should be propagated
     * @param target target date to which orbit state should be propagated
     * @return propagated state
     */
    @Override
    public FieldSpacecraftState<T> propagate(FieldAbsoluteDate<T> start, FieldAbsoluteDate<T> target) {
        return this.propagate_FF(start, target);
    }

    /**
     * Propagate from a start date towards a target date.
     *
Those propagators use a start date and a target date to
     * compute the propagated state. For propagators using event detection mechanism,
     * if the provided start date is different from the initial state date, a first,
     * simple propagation is performed, without processing any event computation.
     * Then complete propagation is performed from start date to target date.

     *
     * @param start  start date from which orbit state should be propagated
     * @param target target date to which orbit state should be propagated
     * @return propagated state
     */
    public native FieldSpacecraftState<T> propagate_FF(FieldAbsoluteDate<T> start, FieldAbsoluteDate<T> target);

    /**
     * Get the {@link FieldPVCoordinates} of the body in the selected frame.
     *
     * @param date  current date
     * @param frame the frame where to define the position
     * @return time-stamped position/velocity of the body (m and m/s)
     */
    @Override
    public native TimeStampedFieldPVCoordinates<T> getPVCoordinates(FieldAbsoluteDate<T> date, Frame frame);
}


text:
//
// cssmalloc - memory allocation in the CDSA world
//
#ifndef _H_CSSMALLOC
#define _H_CSSMALLOC

#include <security_utilities/alloc.h>
#include <Security/cssm.h>
#include <cstring>

namespace Security
{

//
// A POD wrapper for the memory functions structure passed around in CSSM.
//
class CssmMemoryFunctions : public PodWrapper<CssmMemoryFunctions, CSSM_MEMORY_FUNCS> {
public:
	CssmMemoryFunctions(const CSSM_MEMORY_FUNCS &funcs)
	{ *(CSSM_MEMORY_FUNCS *)this = funcs; }
	CssmMemoryFunctions() { }

	void *malloc(size_t size) const throw(std::bad_alloc);
	void free(void *mem) const throw() { free_func(mem, AllocRef); }
	void *realloc(void *mem, size_t size) const throw(std::bad_alloc);
	void *calloc(uint32 count, size_t size) const throw(std::bad_alloc);

	bool operator == (const CSSM_MEMORY_FUNCS &other) const throw()
	{ return !memcmp(this, &other, sizeof(*this)); }
};

inline void *CssmMemoryFunctions::malloc(size_t size) const throw(std::bad_alloc)
{
	if (void *addr = malloc_func(size, AllocRef))
		return addr;
	throw std::bad_alloc();
}

inline void *CssmMemoryFunctions::calloc(uint32 count, size_t size) const throw(std::bad_alloc)
{
	if (void *addr = calloc_func(count, size, AllocRef))
		return addr;
	throw std::bad_alloc();
}

inline void *CssmMemoryFunctions::realloc(void *mem, size_t size) const throw(std::bad_alloc)
{
	if (void *addr = realloc_func(mem, size, AllocRef))
		return addr;
	throw std::bad_alloc();
}

//
// A Allocator based on CssmMemoryFunctions
//
class CssmMemoryFunctionsAllocator : public Allocator {
public:
	CssmMemoryFunctionsAllocator(const CssmMemoryFunctions &memFuncs) : functions(memFuncs) { }

	void *malloc(size_t size) throw(std::bad_alloc);
	void free(void *addr) throw();
	void *realloc(void *addr, size_t size) throw(std::bad_alloc);

	operator const CssmMemoryFunctions & () const throw() { return functions; }

private:
	const CssmMemoryFunctions functions;
};

//
// A MemoryFunctions object based on a Allocator.
// Note that we don't copy the Allocator object. It needs to live (at least)
// as long as any CssmAllocatorMemoryFunctions object based on it.
//
class CssmAllocatorMemoryFunctions : public CssmMemoryFunctions {
public:
	CssmAllocatorMemoryFunctions(Allocator &alloc);
	CssmAllocatorMemoryFunctions() { /*IFDEBUG(*/ AllocRef = NULL /*)*/ ; }	// later assignment req'd

private:
	static void *relayMalloc(size_t size, void *ref) throw(std::bad_alloc);
	static void relayFree(void *mem, void *ref) throw();
	static void *relayRealloc(void *mem, size_t size, void *ref) throw(std::bad_alloc);
	static void *relayCalloc(uint32 count, size_t size, void *ref) throw(std::bad_alloc);

	static Allocator &allocator(void *ref) throw()
	{ return *reinterpret_cast<Allocator *>(ref); }
};

//
// A generic helper for the unhappily ubiquitous CSSM-style
// (count, pointer-to-array) style of arrays.
//
template <class Base, class Wrapper = Base>
class CssmVector {
public:
    CssmVector(uint32 &cnt, Base * &vec, Allocator &alloc = Allocator::standard())
        : count(cnt), vector(reinterpret_cast<Wrapper * &>(vec)),
          allocator(alloc)
    {
        count = 0;
        vector = NULL;
    }

    ~CssmVector()	{ allocator.free(vector); }

    uint32 &count;
    Wrapper * &vector;
    Allocator &allocator;

public:
    Wrapper &operator [] (uint32 ix)
    { assert(ix < count); return vector[ix]; }

    void operator += (const Wrapper &add)
    {
        vector = reinterpret_cast<Wrapper *>(allocator.realloc(vector, (count + 1) * sizeof(Wrapper)));
        //@@@???compiler bug??? vector = allocator.alloc<Wrapper>(vector, count + 1);
        vector[count++] = add;
    }
};

} // end namespace Security

#endif //_H_CSSMALLOC


text:
package org.pocketcampus.plugin.transport.android.req;

import org.pocketcampus.platform.android.io.Request;
import org.pocketcampus.plugin.transport.android.TransportController;
import org.pocketcampus.plugin.transport.android.TransportModel;
import org.pocketcampus.plugin.transport.shared.TransportService.Iface;
import org.pocketcampus.plugin.transport.shared.TransportTripSearchRequest;
import org.pocketcampus.plugin.transport.shared.TransportTripSearchResponse;

public class SearchForTripsRequest
		extends
		Request<TransportController, Iface, TransportTripSearchRequest, TransportTripSearchResponse> {

	private TransportTripSearchRequest request;

	@Override
	protected TransportTripSearchResponse runInBackground(Iface client,
			TransportTripSearchRequest param) throws Exception {
		request = param;
		return client.searchForTrips(param);
	}

	@Override
	protected void onResult(TransportController controller,
			TransportTripSearchResponse result) {
		TransportModel model = (TransportModel) controller.getModel();
		model.setTransportTripSearchResponse(request, result);
	}

	@Override
	protected void onError(TransportController controller, Exception e) {
		TransportModel model = (TransportModel) controller.getModel();
		model.setTransportTripSearchResponse(request, null);
		e.printStackTrace();
	}

}


text:
namespace google {
namespace cloud {
namespace run {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN

ServicesConnection::~ServicesConnection() = default;

future<StatusOr<google::cloud::run::v2::Service>>
ServicesConnection::CreateService(
    google::cloud::run::v2::CreateServiceRequest const&) {
  return google::cloud::make_ready_future<
      StatusOr<google::cloud::run::v2::Service>>(
      Status(StatusCode::kUnimplemented, "not implemented"));
}

StatusOr<google::cloud::run::v2::Service> ServicesConnection::GetService(
    google::cloud::run::v2::GetServiceRequest const&) {
  return Status(StatusCode::kUnimplemented, "not implemented");
}

StreamRange<google::cloud::run::v2::Service> ServicesConnection::ListServices(
    google::cloud::run::v2::
        ListServicesRequest) {  // NOLINT(performance-unnecessary-value-param)
  return google::cloud::internal::MakeUnimplementedPaginationRange<
      StreamRange<google::cloud::run::v2::Service>>();
}

future<StatusOr<google::cloud::run::v2::Service>>
ServicesConnection::UpdateService(
    google::cloud::run::v2::UpdateServiceRequest const&) {
  return google::cloud::make_ready_future<
      StatusOr<google::cloud::run::v2::Service>>(
      Status(StatusCode::kUnimplemented, "not implemented"));
}

future<StatusOr<google::cloud::run::v2::Service>>
ServicesConnection::DeleteService(
    google::cloud::run::v2::DeleteServiceRequest const&) {
  return google::cloud::make_ready_future<
      StatusOr<google::cloud::run::v2::Service>>(
      Status(StatusCode::kUnimplemented, "not implemented"));
}

StatusOr<google::iam::v1::Policy> ServicesConnection::GetIamPolicy(
    google::iam::v1::GetIamPolicyRequest const&) {
  return Status(StatusCode::kUnimplemented, "not implemented");
}

StatusOr<google::iam::v1::Policy> ServicesConnection::SetIamPolicy(
    google::iam::v1::SetIamPolicyRequest const&) {
  return Status(StatusCode::kUnimplemented, "not implemented");
}

StatusOr<google::iam::v1::TestIamPermissionsResponse>
ServicesConnection::TestIamPermissions(
    google::iam::v1::TestIamPermissionsRequest const&) {
  return Status(StatusCode::kUnimplemented, "not implemented");
}

std::shared_ptr<ServicesConnection> MakeServicesConnection(Options options) {
  internal::CheckExpectedOptions<CommonOptionList, GrpcOptionList,
                                 UnifiedCredentialsOptionList,
                                 ServicesPolicyOptionList>(options, __func__);
  options = run_internal::ServicesDefaultOptions(std::move(options));
  auto background = internal::MakeBackgroundThreadsFactory(options)();
  auto stub =
      run_internal::CreateDefaultServicesStub(background->cq(), options);
  return std::make_shared<run_internal::ServicesConnectionImpl>(
      std::move(background), std::move(stub), std::move(options));
}

GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
}  // namespace run
}  // namespace cloud
}  // namespace google


text:
package algs.model.performance.array;

import algs.model.IPoint;
import algs.model.array.FirstSelector;
import algs.model.array.IPivotIndex;
import algs.model.array.LastSelector;
import algs.model.array.MedianSelector;
import algs.model.array.PISelector;
import algs.model.array.QuickSort;
import algs.model.array.RandomSelector;
import algs.model.data.points.UniformGenerator;
import algs.model.tests.common.TrialSuite;

public class TimeQuickSortMain  {

	int BASE = 16777216;

	public static void main(String[] args) {
		new TimeQuickSortMain().testQS();
	}

	private void runTrial (int size, TrialSuite set,
			IPoint[]pts, IPivotIndex selector) {
		Integer[] ar = new Integer[size];
		for (int i = 0, idx = 0; i < pts.length; i++) {
			ar[idx++] = (int) (pts[i].getX() * BASE);
			ar[idx++] = (int) (pts[i].getY() * BASE);
		}

		QuickSort<Integer> qs = new QuickSort<Integer>(ar);
		qs.setMinimumSize(6);
		qs.setPivotMethod(selector);

		System.gc();
		long start = System.currentTimeMillis();
		qs.qsort(0,size-1);
		long end = System.currentTimeMillis();
		set.addTrial(size, start, end);

		for (int i = 0; i < ar.length-1; i++) {
			assert (ar[i] <= ar[i+1]);
		}
	}

	public void testQS() {
		UniformGenerator ug = new UniformGenerator();
		TrialSuite pi = new TrialSuite();
		TrialSuite first = new TrialSuite();
		TrialSuite last = new TrialSuite();
		TrialSuite random = new TrialSuite();
		TrialSuite median = new TrialSuite ();

		// 50 trials over sizes from 10 to 1000000
		int numDigits = 1;
		for (int size = 10; size <= 1000000; size *= 10) {
			System.out.println (size + "...");
			if (numDigits < 6) { numDigits ++; }
			for (int t = 0; t < 20; t++) {
				// create random arrays of given SIZE with range [0 .. 32768]
				IPoint[]pts = ug.generate(size/2);  // 500 points = 1000 random [0,1] values
				runTrial (size,first, pts, new FirstSelector());
				runTrial (size, last, pts, new LastSelector());
				runTrial (size, pi, pts, new PISelector(numDigits));
				runTrial (size, random, pts, new RandomSelector());
				runTrial (size, median, pts, new MedianSelector());
			}
		}

		// random one (based upon pi)
		System.out.println ("PI");
		System.out.println (pi.computeTable());

		// first one always
		System.out.println ("FIRST");
		System.out.println (first.computeTable());

		// last one always
		System.out.println ("LAST");
		System.out.println (last.computeTable());

		// random one always
		System.out.println ("RANDOM");
		System.out.println (random.computeTable());

		// median one always
		System.out.println ("MEDIAN");
		System.out.println (median.computeTable());
	}
}


text:
pageTitle: Ember.js
menuTitle: Ember.js

To execute javascript unit and integration tests with ember.js follow the steps below:

1. [install karma]

2. install the qunit plugin

    npm install karma-qunit --save-dev

3. install the ember preprocessor plugin

    npm install karma-ember-preprocessor --save-dev

4. genenerate a configuration file for karma

    karma init

note -the above will walk you through the basic setup. An example configuration file that works with ember.js/qunit and phantomjs is below

```javascript
module.exports = function(config) {
  config.set({
    basePath: 'js',

    files: [
      'vendor/jquery/jquery.min.js',
      'vendor/handlebars/handlebars.js',
      'vendor/ember/ember.js',
      'app.js',
      'tests/*.js',
      'templates/*.handlebars'
    ],

    browsers: ['PhantomJS'],
    singleRun: true,
    autoWatch: false,

    frameworks: ['qunit'],

    plugins: [
      'karma-qunit',
      'karma-ember-preprocessor',
      'karma-phantomjs-launcher'
    ],

    preprocessors: {
      '**/*.handlebars': 'ember'
    }
  });
};

Note - the `files` section above should include all dependencies, ie- jQuery/handlebars/ember.js along with the js and handlebars files required to deploy and run your production ember.js application

5. add a simple qunit test

    test('one should equal one', function() {
        equal(1, 1, 'error: one did not equal one');
    });

6. run the tests with karma from the command line

    karma start

A simple unit / integration tested example app showing karma / qunit / ember in action can be found [here]

[install karma]: ../intro/installation.html
[here]: https://github.com/toranb/ember-testing-example


text:
import { GraphQLError, GraphQLFormattedError } from 'graphql';
export declare class ApolloError extends Error implements GraphQLError {
    extensions: Record<string, any>;
    readonly name: any;
    readonly locations: any;
    readonly path: any;
    readonly source: any;
    readonly positions: any;
    readonly nodes: any;
    originalError: any;
    [key: string]: any;
    constructor(message: string, code?: string, properties?: Record<string, any>);
}
export declare function toApolloError(error: Error & {
    extensions?: Record<string, any>;
}, code?: string): Error & {
    extensions: Record<string, any>;
};
export interface ErrorOptions {
    code?: string;
    errorClass?: typeof ApolloError;
}
export declare function fromGraphQLError(error: GraphQLError, options?: ErrorOptions): ApolloError;
export declare class SyntaxError extends ApolloError {
    constructor(message: string);
}
export declare class ValidationError extends ApolloError {
    constructor(message: string);
}
export declare class AuthenticationError extends ApolloError {
    constructor(message: string);
}
export declare class ForbiddenError extends ApolloError {
    constructor(message: string);
}
export declare class PersistedQueryNotFoundError extends ApolloError {
    constructor();
}
export declare class PersistedQueryNotSupportedError extends ApolloError {
    constructor();
}
export declare class UserInputError extends ApolloError {
    constructor(message: string, properties?: Record<string, any>);
}
export declare function formatApolloErrors(errors: Array<Error>, options?: {
    formatter?: (error: GraphQLError) => GraphQLFormattedError;
    debug?: boolean;
}): Array<ApolloError>;
//# sourceMappingURL=index.d.ts.map


text:
. (Join-Path $PSScriptRoot Compare-SecOpenPort.ps1)
. (Join-Path $PSScriptRoot Get-SecOpenPort.ps1)
. (Join-Path $PSScriptRoot Get-SecOpenPorts.ps1)
. (Join-Path $PSScriptRoot Set-SecFireWallSettings.ps1)
. (Join-Path $PSScriptRoot Compare-SecWirelessNetwork.ps1)
. (Join-Path $PSScriptRoot Get-SecWirelessNetwork.ps1)


text:
.class final Landroid/app/ContextImpl$38;
.super Landroid/app/ContextImpl$ServiceFetcher;
.source "ContextImpl.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/app/ContextImpl;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x8
    name = null
.end annotation

# direct methods
.method constructor <init>()V
    .locals 0

    .prologue
    .line 518
    invoke-direct {p0}, Landroid/app/ContextImpl$ServiceFetcher;-><init>()V

    return-void
.end method

# virtual methods
.method public getService(Landroid/app/ContextImpl;)Ljava/lang/Object;
    .locals 4
    .parameter "ctx"

    .prologue
    .line 520
    #getter for: Landroid/app/ContextImpl;->mDisplay:Landroid/view/Display;
    invoke-static {p1}, Landroid/app/ContextImpl;->access$100(Landroid/app/ContextImpl;)Landroid/view/Display;

    move-result-object v0

    .line 521
    .local v0, display:Landroid/view/Display;
    if-nez v0, :cond_0

    .line 522
    invoke-virtual {p1}, Landroid/app/ContextImpl;->getOuterContext()Landroid/content/Context;

    move-result-object v2

    const-string v3, "display"

    invoke-virtual {v2, v3}, Landroid/content/Context;->getSystemService(Ljava/lang/String;)Ljava/lang/Object;

    move-result-object v1

    check-cast v1, Landroid/hardware/display/DisplayManager;

    .line 524
    .local v1, dm:Landroid/hardware/display/DisplayManager;
    const/4 v2, 0x0

    invoke-virtual {v1, v2}, Landroid/hardware/display/DisplayManager;->getDisplay(I)Landroid/view/Display;

    move-result-object v0

    .line 526
    .end local v1           #dm:Landroid/hardware/display/DisplayManager;
    :cond_0
    new-instance v2, Landroid/view/WindowManagerImpl;

    invoke-direct {v2, v0}, Landroid/view/WindowManagerImpl;-><init>(Landroid/view/Display;)V

    return-object v2
.end method