text:
package com.github.juanrh.streaming.source;

import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Supplier;
import com.google.common.collect.Lists;
import lombok.Data;
import lombok.NonNull;
import lombok.Setter;
import lombok.experimental.Accessors;
import org.apache.flink.api.common.functions.MapFunction;

import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.streaming.api.TimeCharacteristic;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.timestamps.AscendingTimestampExtractor;
import org.apache.flink.streaming.api.functions.timestamps.BoundedOutOfOrdernessTimestampExtractor;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

/**
 * This class provides basically the same functionality as StreamExecutionEnvironment.fromCollection
 * but allows to specify a collection of elements together with a delay time when the element should be
 * generated, that is used to assign that as the event time of each element. Hence the DataStream
 * returned by get() should be used with env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime)
 *
 * That delay is interpreted as a relative time, i.e. a time delta from an arbitrary initial time
 *
 * Currently there are two implementations
 *  - earlyImplementation = true: the initial time is is the the current time at the call of get() as returned by
 *  System.currentTimeMillis(). The absolute time build as initial time + delta is assigned as the event time of
 *  the element. This means we get early elements, i.e. elements with a timestamp in the future wrt to processing
 *  time. AscendingTimestampExtractor is used in this implementation, after sorting the elements by time
 *
 * - earlyImplementation = false: this is the default. The initial time is set to the current time minus the
 * sum of all delays, so all events are late events, and a BoundedOutOfOrdernessTimestampExtractor is
 * configured so no late event is dropped.
 *
 * NOTE this source doesn't delay the emission of elements, and instead elements are emitted instantaneously.
 * So the event timestamp will only be relevant when window operations are applied, that do use the event
 * time stamp for the aggregation operation that is applied to the window
 * */
public class EventTimeDelayedElementsSource<T> implements Supplier<DataStream<T>> {
    private static final transient Logger LOG = LoggerFactory.getLogger(EventTimeDelayedElementsSource.class);

    @Data(staticConstructor="of")
    public static final class Elem<T> implements Serializable, Comparable<Elem<T>> {
        private static final long serialVersionUID = 1L;
        @NonNull private final T value;
        // Times are relative to an arbitrary start time
        @NonNull private final Time delay;

        @Override
        public int compareTo(Elem other) {
            long thisMillis = this.delay.toMilliseconds();
            long otherMillis = other.delay.toMilliseconds();
            return thisMillis < otherMillis ? -1 : (thisMillis == otherMillis ? 0 : 1);
        }
    }

    private final List<Elem<T>> elements;
    private final TypeInformation<T> elementsTypeInfo;
    private final StreamExecutionEnvironment env;

    @Accessors(chain = true) @Setter
    private boolean earlyImplementation = false;

    public EventTimeDelayedElementsSource(StreamExecutionEnvironment env,
                                          Optional<TypeInformation<T>> elementsTypeInfo,
                                          final Iterable<Elem<T>> elements) {
        Preconditions.checkArgument(elements.iterator().hasNext(),
                "EventTimeDelayedElementsSource needs at least one element");
        Preconditions.checkArgument(env.getStreamTimeCharacteristic().equals(TimeCharacteristic.EventTime),
                                    "EventTimeDelayedElementsSource only works with TimeCharacteristic.EventTime, %s found",
                                    env.getStreamTimeCharacteristic());

        this.elementsTypeInfo = SourceUtils.getTypeInformation(elementsTypeInfo,
                new Supplier<T>() {
                    @Override
                    public T get() {
                        return elements.iterator().next().getValue();
                    }
                });
        this.env = env;
        this.elements = Lists.newArrayList(elements);
    }

    public EventTimeDelayedElementsSource(StreamExecutionEnvironment env,
                                          TypeInformation<T> elementsTypeInfo,
                                          final Iterable<Elem<T>> elements) {
        this(env, Optional.of(elementsTypeInfo), elements);
    }

    public EventTimeDelayedElementsSource(StreamExecutionEnvironment env,
                                          final Iterable<Elem<T>> elements) {
        this(env, Optional.<TypeInformation<T>>absent(), elements);
    }

    public static <T> EventTimeDelayedElementsSource<T> withEqualGaps(StreamExecutionEnvironment env,
                                                                      final Time gap,
                                                                      T ... elements) {
        return withEqualGaps(env, gap, Lists.newArrayList(elements));
    }

    /**
     * @param gap relative gap between each element and the following
     * */
    public static <T> EventTimeDelayedElementsSource<T> withEqualGaps(StreamExecutionEnvironment env,
                                                                      Optional<TypeInformation<T>> elementsTypeInfo,
                                                                      final Time gap,
                                                                      Iterable<T> elements) {
        Preconditions.checkArgument(elements.iterator().hasNext(),
                "EventTimeDelayedElementsSource needs at least one element");
        List<Elem<T>> delayedElements = new LinkedList<>();
        long totalDelayMillis = 0L;
        for (T elem : elements) {
            delayedElements.add(Elem.of(elem, Time.milliseconds(totalDelayMillis)));
            totalDelayMillis += gap.toMilliseconds();
        }

        return new EventTimeDelayedElementsSource<>(env, elementsTypeInfo, delayedElements);
    }

    public static <T> EventTimeDelayedElementsSource<T> withEqualGaps(StreamExecutionEnvironment env,
                                                                       TypeInformation<T> elementsTypeInfo,
                                                                       final Time gap,
                                                                       Iterable<T> elements) {
        return withEqualGaps(env, Optional.of(elementsTypeInfo), gap, elements);
    }

    public static <T> EventTimeDelayedElementsSource<T> withEqualGaps(StreamExecutionEnvironment env,
                                                                      final Time gap,
                                                                      Iterable<T> elements) {
        return withEqualGaps(env, Optional.<TypeInformation<T>>absent(), gap, elements);
    }
    /**
     * The interval (every n milliseconds) in which the watermark will be generated
     * is defined via ExecutionConfig.setAutoWatermarkInterval
     * */
    @Override
    public DataStream<T> get() {
        if (earlyImplementation) {
            return getEarly();
        }
        return getLate();
    }

    private DataStream<T> getLate() {
        long totalDelayMillis = 0L;
        for (Elem<T> elem : elements) {
            totalDelayMillis += elem.getDelay().toMilliseconds();
        }
        LOG.debug("totalDelayMillis = {}", totalDelayMillis);

        final long startTimestamp = System.currentTimeMillis() - totalDelayMillis;
        return env.fromCollection(elements)
           .assignTimestampsAndWatermarks(
                   new BoundedOutOfOrdernessTimestampExtractor<Elem<T>>(Time.milliseconds(totalDelayMillis*2)) {
                       @Override
                       public long extractTimestamp(Elem<T> elem) {
                           long timestamp = startTimestamp + elem.getDelay().toMilliseconds();
                            LOG.debug("Assigning timestamp of {}  to element {}",
                                      timestamp,  elem.getValue());
                            return timestamp;
                        }
                   })
           .map(new MapFunction<Elem<T>, T>() {
               @Override
               public T map(Elem<T> elem) throws Exception {
                   return elem.getValue();
               }
           })
           .returns(elementsTypeInfo);
    }

    public DataStream<T> getEarly() {
        // sort so we can use AscendingTimestampExtractor
        Collections.sort(elements);

        final long startTimestamp = System.currentTimeMillis();
        return env.fromCollection(elements)
           .assignTimestampsAndWatermarks(new AscendingTimestampExtractor<Elem<T>>() {
               @Override
               public long extractAscendingTimestamp(Elem<T> elem) {
                        long timestamp = startTimestamp + elem.getDelay().toMilliseconds();
                        LOG.debug("Assigning timestamp of {}  to element {}",
                                 timestamp,  elem.getValue());
                        return timestamp;
                    }
                })
                .map(new MapFunction<Elem<T>, T>() {
                    @Override
                    public T map(Elem<T> elem) throws Exception {
                        return elem.getValue();
                    }
                })
                .returns(elementsTypeInfo);
    }
}


text:
package org.eclipse.hudson.jna;

import hudson.model.Descriptor;
import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * A Native Support Utility (singleton) that delegates the actions to available
 * Native Support Extensions
 *
 * @since 3.0.0
 * @see NativeAccessSupport, ZfsSupport
 */
public class NativeUtils implements Serializable {

    private NativeZfsSupport nativeZfsSupport;
    private NativeUnixSupport nativeUnixSupport;
    private NativeWindowsSupport nativeWindowsSupport;
    private NativeMacSupport nativeMacSupport;
    private static Logger logger = LoggerFactory.getLogger(NativeUtils.class);

   public static NativeUtils INSTANCE;

    private NativeUtils() {
        try {
            List<NativeUnixSupport> nativeUnixSupports = getAvailableNativeUnixSupports();
            if (nativeUnixSupports.size() > 0) {
                nativeUnixSupport = nativeUnixSupports.get(0);
            }

            List<NativeWindowsSupport> nativeWindowsSupports = getAvailableNativeWindowSupports();
            if (nativeWindowsSupports.size() > 0) {
                nativeWindowsSupport = nativeWindowsSupports.get(0);
            }

            List<NativeMacSupport> nativeMacSupports = getAvailableNativeMacSupports();
            if (nativeMacSupports.size() > 0) {
                nativeMacSupport = nativeMacSupports.get(0);
            }
            List<NativeZfsSupport> nativeZfsSupports = getAvailableNativeZfsSupports();
            if (nativeZfsSupports.size() > 0) {
                nativeZfsSupport = nativeZfsSupports.get(0);
            }
        } catch (Exception exc) {
            logger.info("Error getting Native Support Extensions", exc);
        }

    }

    private List<NativeUnixSupport> getAvailableNativeUnixSupports() {
        List<NativeUnixSupport> nativeUnixSupports = new ArrayList<NativeUnixSupport>();
        if (NativeUnixSupport.all() != null && !NativeUnixSupport.all().isEmpty()) {
            for (Descriptor<NativeUnixSupport> nativeUnixSupport : NativeUnixSupport.all()) {
                try {
                    nativeUnixSupports.add(nativeUnixSupport.newInstance(null, null));
                } catch (Throwable exc) {
                    logger.info("Failed to instantiate Native Unix Support - " + nativeUnixSupport.getDisplayName());
                }
            }
        }
        return nativeUnixSupports;
    }

    private List<NativeWindowsSupport> getAvailableNativeWindowSupports() {
        List<NativeWindowsSupport> nativeWindowsSupports = new ArrayList<NativeWindowsSupport>();
        if (NativeWindowsSupport.all() != null && !NativeWindowsSupport.all().isEmpty()) {
            for (Descriptor<NativeWindowsSupport> nativeWindowsSupport : NativeWindowsSupport.all()) {
                try {
                    nativeWindowsSupports.add(nativeWindowsSupport.newInstance(null, null));
                } catch (Throwable exc) {
                    logger.info("Failed to instantiate Native Window Support - " + nativeWindowsSupport.getDisplayName());
                }
            }
        }
        return nativeWindowsSupports;
    }

    private List<NativeMacSupport> getAvailableNativeMacSupports() {
        List<NativeMacSupport> nativeMacSupports = new ArrayList<NativeMacSupport>();
        if (NativeMacSupport.all() != null && !NativeMacSupport.all().isEmpty()) {
            for (Descriptor<NativeMacSupport> nativeMacSupport : NativeMacSupport.all()) {
                try {
                    nativeMacSupports.add(nativeMacSupport.newInstance(null, null));
                } catch (Throwable exc) {
                    logger.info("Failed to instantiate Native Mac Support - " + nativeMacSupport.getDisplayName());
                }
            }
        }
        return nativeMacSupports;
    }

    private List<NativeZfsSupport> getAvailableNativeZfsSupports() {
        List<NativeZfsSupport> nativeZfsSupports = new ArrayList<NativeZfsSupport>();
        if (NativeZfsSupport.all() != null && !NativeZfsSupport.all().isEmpty()) {
            for (Descriptor<NativeZfsSupport> nativeZfsSupport : NativeZfsSupport.all()) {
                try {
                    nativeZfsSupports.add(nativeZfsSupport.newInstance(null, null));
                } catch (Throwable exc) {
                    logger.info("Failed to instantiate Native Zfs Support - " + nativeZfsSupport.getDisplayName());
                }
            }
        }
        return nativeZfsSupports;
    }

    /**
     * Delay the instance creation until needed, else slave ClassLoader deserialization will try to
     * instantiate the instance and will fail to load the extension points.
     * @return
     */
    public static synchronized NativeUtils getInstance() {
        if (INSTANCE == null){
            INSTANCE = new NativeUtils();
        }
        return INSTANCE;
    }

    /**
     * Check if any Native Unix Support plugin is installed
     * @return
     */
    public boolean hasUnixSupport() {
        return nativeUnixSupport != null;
    }

    /**
     * Check if any Native Windows Support plugin is installed
     *
     * @return
     */
    public boolean hasWindowsSupport() {
        return nativeWindowsSupport != null;
    }

    /**
     * Check if any Native Mac Support plugin is installed
     *
     * @return
     */
    public boolean hasMacSupport() {
        return nativeMacSupport != null;
    }

    /**
     * Check if any Native ZFS Support plugin is installed
     *
     * @return
     */
    public boolean hasZfsSupport() {
        return nativeZfsSupport != null;
    }

    private void ensureUnixSupport(NativeFunction function) throws NativeAccessException {
        if (!hasUnixSupport()) {
            throw new NativeAccessException("Native Unix Support plugin not installed");
        }
        if (!nativeUnixSupport.hasSupportFor(function)) {
            throw new NativeAccessException("Installed Native Unix Support plugin does not support " + function);
        }
    }

    private void ensureWindowsSupport(NativeFunction function) throws NativeAccessException {
        if (!hasWindowsSupport()) {
            throw new NativeAccessException("Native Windows Support plugin not installed");
        }
        if (!nativeWindowsSupport.hasSupportFor(function)) {
            throw new NativeAccessException("Installed Native Windows Support plugin does not support " + function);
        }
    }

    private void ensureMacSupport(NativeFunction function) throws NativeAccessException {
        if (!hasMacSupport()) {
            throw new NativeAccessException("Native Mac Support plugin not installed");
        }
        if (!nativeMacSupport.hasSupportFor(function)) {
            throw new NativeAccessException("Installed Native Mac Support plugin does not support " + function);
        }
    }

    private void ensureZfsSupport(NativeFunction function) throws NativeAccessException {
        if (!hasZfsSupport()) {
            throw new NativeAccessException("Native ZFS Support plugin not installed");
        }
        if (!nativeZfsSupport.hasSupportFor(function)) {
            throw new NativeAccessException("Installed Native ZFS Support plugin does not support " + function);
        }
    }

    /**
     * Do the Unix style chmod (change file permission) on a File
     *
     * @param file
     * @param mask
     * @return true if the function executed successfully
     * @throws hudson.util.jna.Native.ExecutionError
     */
    public boolean chmod(File file, int mask) throws NativeAccessException {
        ensureUnixSupport(NativeFunction.CHMOD);
        return nativeUnixSupport.chmod(file, mask);
    }

    /**
     * Do the Unix style chown (change Owner permission) on a File
     *
     * @param file
     * @param mask
     * @return true if the function executed successfully
     * @throws hudson.util.jna.Native.ExecutionError
     */
    public boolean chown(File file, int uid, int gid) throws NativeAccessException {
        ensureUnixSupport(NativeFunction.CHOWN);
        return nativeUnixSupport.chown(file, uid, gid);

    }

    /**
     * Get the Unix style mode (file permission) of a file
     *
     * @param file
     * @return
     * @throws hudson.util.jna.Native.ExecutionError
     */
    public int mode(File file) throws NativeAccessException {
        ensureUnixSupport(NativeFunction.MODE);
        return nativeUnixSupport.mode(file);
    }

    /**
     * Get the name of the user who started this Java process
     *
     * @return
     * @throws hudson.util.jna.Native.NativeExecutionException
     */
    public String getProcessUser() throws NativeAccessException {
        ensureUnixSupport(NativeFunction.UNIX_USER);
        return nativeUnixSupport.getProcessUser();
    }

    /**
     * Make the file writable with native operation
     *
     * @param file
     * @return true if the operation is successful
     * @throws hudson.util.jna.Native.ExecutionError
     */
    public boolean makeFileWritable(File file) throws NativeAccessException {
        ensureUnixSupport(NativeFunction.FILE_WRITABLE);
        return nativeUnixSupport.makeFileWritable(file);
    }

    /**
     * Create Unix style symlink
     *
     * @param targetPath
     * @param file
     * @return true if the operation is successful
     * @throws hudson.util.jna.Native.ExecutionError
     */
    public boolean createSymlink(String targetPath, File file) throws NativeAccessException {
        ensureUnixSupport(NativeFunction.SYMLINK);
        return nativeUnixSupport.createSymlink(targetPath, file);
    }

    /**
     * Resolves symlink, if the given file is a symlink on a Unix System.
     * Otherwise return null.
     *
     * @param targetPath
     * @param file
     * @return String the resolved file path
     * @throws hudson.util.jna.Native.ExecutionError
     */
    public String resolveSymlink(File file) throws NativeAccessException {
        ensureUnixSupport(NativeFunction.RESOLVE_LINK);
        return nativeUnixSupport.resolveSymlink(file);
    }

    /**
     * Get the information about the System Memory
     *
     * @return
     * @throws hudson.util.jna.Native.ExecutionError
     */
    public NativeSystemMemory getSystemMemory() throws NativeAccessException {
        ensureUnixSupport(NativeFunction.SYSTEM_MEMORY);
        return nativeUnixSupport.getSystemMemory();
    }

    /**
     * Get the effective User ID on a Unix System
     *
     * @return
     * @throws hudson.util.jna.Native.ExecutionError
     */
    public int getEuid() throws NativeAccessException {
        ensureUnixSupport(NativeFunction.EUID);
        return nativeUnixSupport.getEuid();
    }

    /**
     * Get the effective Group ID on a Unix System
     *
     * @return
     * @throws hudson.util.jna.Native.ExecutionError
     */
    public int getEgid() throws NativeAccessException {
        ensureUnixSupport(NativeFunction.EGID);
        return nativeUnixSupport.getEgid();
    }

    /**
     * Check if this Unix user exists on the machine where this program runs
     *
     * @param userName
     * @return
     * @throws hudson.util.jna.Native.NativeExecutionException
     */
    public boolean checkUnixUser(String userName) throws NativeAccessException {
        ensureUnixSupport(NativeFunction.UNIX_USER);
        return nativeUnixSupport.checkUnixUser(userName);
    }

    /**
     * Check if this Unix group exists on the machine where this program runs
     *
     * @param userName
     * @return
     * @throws hudson.util.jna.Native.NativeExecutionException
     */
    public boolean checkUnixGroup(String groupName) throws NativeAccessException {
        ensureUnixSupport(NativeFunction.UNIX_GROUP);
        return nativeUnixSupport.checkUnixGroup(groupName);
    }

    /**
     * Authenticate using Using Unix Pluggable Authentication Modules (PAM)
     *
     * @param userName
     * @param password
     * @return List<String> list of groups to which this user belongs
     * @throws hudson.util.jna.Native.NativeExecutionException
     */
    public Set<String> pamAuthenticate(String serviceName, String userName, String password) throws NativeAccessException {
        ensureUnixSupport(NativeFunction.PAM);
        return nativeUnixSupport.pamAuthenticate(serviceName, userName, password);
    }

    /**
     * Check if PAM Authentication available in the machine where this program
     * runs
     *
     * @return Message corresponding to the availability of PAM
     * @throws hudson.util.jna.Native.NativeExecutionException
     */
    public String checkPamAuthentication() throws NativeAccessException {
        ensureUnixSupport(NativeFunction.PAM);
        return nativeUnixSupport.checkPamAuthentication();
    }

    /**
     * Restart current Java process (JVM in which this application is running)
     *
     * @throws hudson.util.jna.Native.NativeExecutionException
     */
    public void restartJavaProcess(Map<String, String> properties, boolean asDaemon) throws NativeAccessException {
        ensureUnixSupport(NativeFunction.JAVA_RESTART);
        nativeUnixSupport.restartJavaProcess(properties, asDaemon);
    }

    /**
     * Check if this Java process can be restarted
     *
     * @throws hudson.util.jna.Native.NativeExecutionException
     */
    public boolean canRestartJavaProcess() throws NativeAccessException {
        ensureUnixSupport(NativeFunction.JAVA_RESTART);
        return nativeUnixSupport.canRestartJavaProcess();
    }

    /**
     * Get the error associated with the last Native Unix Operation
     *
     * @return String error message
     */
    public String getLastUnixError() {
        if (!hasUnixSupport()) {
            return "Native Unix Support plugin not installed";
        }
        return nativeUnixSupport.getLastError();
    }

    /**
     * Check if .NET is installed on a the Windows machine
     *
     * @return true if .NET is installed.
     * @throws hudson.util.jna.Native.ExecutionError
     */
    public boolean isDotNetInstalled(int major, int minor) throws NativeAccessException {
        ensureWindowsSupport(NativeFunction.DOTNET);
        return nativeWindowsSupport.isDotNetInstalled(major, minor);
    }

    /**
     * Get all the native processes on a Windows System
     *
     * @return List of Native Window Processes
     * @throws hudson.util.jna.Native.ExecutionError
     */
    public List<NativeProcess> getWindowsProcesses() throws NativeAccessException {
        ensureWindowsSupport(NativeFunction.WINDOWS_PROCESS);
        return nativeWindowsSupport.getWindowsProcesses();
    }

    /**
     * Find the Native Process Id of the given java.lang.process
     *
     * @param process (java.lang.process)
     * @return pid, the Native Process ID
     */
    public int getWindowsProcessId(Process process) throws NativeAccessException {
        ensureWindowsSupport(NativeFunction.WINDOWS_PROCESS);
        return nativeWindowsSupport.getWindowsProcessId(process);
    }

    /**
     * Run the Windows program natively in an elevated privilege
     *
     * @param winExe, windows executable to run
     * @param args, arguments to pass
     * @param logFile, File where the logs of the process should go
     * @param pwd, Path of the working directory
     * @return int, process exit code
     * @throws hudson.util.jna.Native.NativeExecutionException
     */
    public int windowsExec(File winExe, String args, String logFile, File pwd) throws NativeAccessException {
        ensureWindowsSupport(NativeFunction.WINDOWS_EXEC);
        return nativeWindowsSupport.windowsExec(winExe, args, logFile, pwd);
    }

    /**
     * Move a Windows File using native win32 library
     *
     * @param fromFile
     * @param toFile
     * @return
     * @throws hudson.util.jna.Native.NativeExecutionException
     */
    public void windowsMoveFile(File fromFile, File toFile) throws NativeAccessException {
        ensureWindowsSupport(NativeFunction.WINDOWS_FILE_MOVE);
        nativeWindowsSupport.windowsMoveFile(fromFile, toFile);
    }

    /**
     * Get the error associated with the last Native Unix Operation
     *
     * @return String error message
     */
    public String getLastWindowsError() {
        if (!hasUnixSupport()) {
            return "Native Windows Support plugin not installed";
        }
        return nativeWindowsSupport.getLastError();
    }

    /**
     * Get the Native processes of a Mac System
     *
     * @return
     * @throws hudson.util.jna.Native.NativeExecutionException
     */
    public List<NativeProcess> getMacProcesses() throws NativeAccessException {
        ensureMacSupport(NativeFunction.MAC_PROCESS);
        return nativeMacSupport.getMacProcesses();
    }

    /**
     * Get the error associated with the last Native Unix Operation
     *
     * @return String error message
     */
    public String getLastMacError() {
        return nativeMacSupport.getLastError();
    }

    /**
     * Fetch the list of mounted ZFS roots
     *
     * @return
     * @throws hudson.util.jna.Native.NativeExecutionException
     */
    public List<NativeZfsFileSystem> getZfsRoots() throws NativeAccessException {
        ensureZfsSupport(NativeFunction.ZFS);
        return nativeZfsSupport.getZfsRoots();
    }

    /**
     * Find the ZFS File System by its mount point
     *
     * @return
     * @throws hudson.util.jna.Native.NativeExecutionException
     */
    public NativeZfsFileSystem getZfsByMountPoint(File mountPoint) throws NativeAccessException {
        ensureZfsSupport(NativeFunction.ZFS);
        return nativeZfsSupport.getZfsByMountPoint(mountPoint);
    }

    /**
     * Create ZFS File System corresponding to the mount name
     *
     * @param mountPoint
     * @return ZFS File System if created successfully
     * @throws hudson.util.jna.Native.NativeExecutionException
     */
    public NativeZfsFileSystem createZfs(String mountName) throws NativeAccessException {
        ensureZfsSupport(NativeFunction.ZFS);
        return nativeZfsSupport.createZfs(mountName);
    }

    /**
     * Open the target ZFS File System
     *
     * @param mountPoint
     * @return ZFS File System if opened successfully
     * @throws hudson.util.jna.Native.NativeExecutionException
     */
    public NativeZfsFileSystem openZfs(String target) throws NativeAccessException {
        ensureZfsSupport(NativeFunction.ZFS);
        return nativeZfsSupport.openZfs(target);
    }

    /**
     * Check if the named ZFS exists
     *
     * @param zfsName
     * @return
     * @throws hudson.util.jna.Native.NativeExecutionException
     */
    public boolean zfsExists(String zfsName) throws NativeAccessException {
        ensureZfsSupport(NativeFunction.ZFS);
        return nativeZfsSupport.zfsExists(zfsName);
    }

    /**
     * Get the error associated with the last Native Unix Operation
     *
     * @return String error message
     */
    public String getLastZfsError() {
        if (!hasZfsSupport()) {
            return "Native Unix Support plugin not installed";
        }
        return nativeZfsSupport.getLastError();
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.google.ads.googleads.v11.errors;

public final class OperationAccessDeniedErrorProto {
  private OperationAccessDeniedErrorProto() {}
  public static void registerAllExtensions(
      com.google.protobuf.ExtensionRegistryLite registry) {
  }

  public static void registerAllExtensions(
      com.google.protobuf.ExtensionRegistry registry) {
    registerAllExtensions(
        (com.google.protobuf.ExtensionRegistryLite) registry);
  }
  static final com.google.protobuf.Descriptors.Descriptor
    internal_static_google_ads_googleads_v11_errors_OperationAccessDeniedErrorEnum_descriptor;
  static final
    com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internal_static_google_ads_googleads_v11_errors_OperationAccessDeniedErrorEnum_fieldAccessorTable;

  public static com.google.protobuf.Descriptors.FileDescriptor
      getDescriptor() {
    return descriptor;
  }
  private static  com.google.protobuf.Descriptors.FileDescriptor
      descriptor;
  static {
    java.lang.String[] descriptorData = {
      "\nCgoogle/ads/googleads/v11/errors/operat" +
      "ion_access_denied_error.proto\022\037google.ad" +
      "s.googleads.v11.errors\"\353\003\n\036OperationAcce" +
      "ssDeniedErrorEnum\"\310\003\n\032OperationAccessDen" +
      "iedError\022\017\n\013UNSPECIFIED\020\000\022\013\n\007UNKNOWN\020\001\022\030" +
      "\n\024ACTION_NOT_PERMITTED\020\002\022\"\n\036CREATE_OPERA" +
      "TION_NOT_PERMITTED\020\003\022\"\n\036REMOVE_OPERATION" +
      "_NOT_PERMITTED\020\004\022\"\n\036UPDATE_OPERATION_NOT" +
      "_PERMITTED\020\005\022*\n&MUTATE_ACTION_NOT_PERMIT" +
      "TED_FOR_CLIENT\020\006\022-\n)OPERATION_NOT_PERMIT" +
      "TED_FOR_CAMPAIGN_TYPE\020\007\022#\n\037CREATE_AS_REM" +
      "OVED_NOT_PERMITTED\020\010\0220\n,OPERATION_NOT_PE" +
      "RMITTED_FOR_REMOVED_RESOURCE\020\t\022-\n)OPERAT" +
      "ION_NOT_PERMITTED_FOR_AD_GROUP_TYPE\020\n\022%\n" +
      "!MUTATE_NOT_PERMITTED_FOR_CUSTOMER\020\013B\377\001\n" +
      "#com.google.ads.googleads.v11.errorsB\037Op" +
      "erationAccessDeniedErrorProtoP\001ZEgoogle." +
      "golang.org/genproto/googleapis/ads/googl" +
      "eads/v11/errors;errors\242\002\003GAA\252\002\037Google.Ad" +
      "s.GoogleAds.V11.Errors\312\002\037Google\\Ads\\Goog" +
      "leAds\\V11\\Errors\352\002#Google::Ads::GoogleAd" +
      "s::V11::Errorsb\006proto3"
    };
    descriptor = com.google.protobuf.Descriptors.FileDescriptor
      .internalBuildGeneratedFileFrom(descriptorData,
        new com.google.protobuf.Descriptors.FileDescriptor[] {
        });
    internal_static_google_ads_googleads_v11_errors_OperationAccessDeniedErrorEnum_descriptor =
      getDescriptor().getMessageTypes().get(0);
    internal_static_google_ads_googleads_v11_errors_OperationAccessDeniedErrorEnum_fieldAccessorTable = new
      com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
        internal_static_google_ads_googleads_v11_errors_OperationAccessDeniedErrorEnum_descriptor,
        new java.lang.String[] { });
  }

  // @@protoc_insertion_point(outer_class_scope)
}


text:
<?php

namespace App\Controller;

use Cake\Controller\Controller;
use Cake\Event\Event;
use Cake\Database\Type;

/**
 * Application Controller
 *
 * Add your application-wide methods in the class below, your controllers
 * will inherit them.
 *
 * @link http://book.cakephp.org/3.0/en/controllers.html#the-app-controller
 */
class AppController extends Controller {

    public $UserInfo = array();
    public $helpers = [
        'Html' => [
            'className' => 'MyHtml'
        ],
        'Form' => [
            'className' => 'MyForm'
        ],
        'Paginator' => [
            'className' => 'MyPaginator'
        ],
        'Modal' => [
            'className' => 'MyModal'
        ],
        'Text',
        'Url'
    ];

    /**
     * Initialization hook method.
     *
     * Use this method to add common initialization code like loading components.
     *
     * @return void
     */
    public function initialize() {
        parent::initialize();

        $this->loadComponent('Cookie');
        $this->loadComponent('Flash');
        $this->loadComponent('Auth', [
            'loginRedirect' => [
                'controller' => 'Usuarios',
                'action' => 'index',
            ],
            'loginAction' => [
                'controller' => 'Usuarios',
                'action' => 'login',
                'plugin' => null
            ],
            'logoutRedirect' => '/',
            'authorize' => ['controller'],
            'authenticate' => [
                'Form' => [
                    'passwordHasher' => [
                        'className' => 'Default',
                    ],
                    'fields' => ['username' => 'usuario', 'password' => 'senha'],
                    'userModel' => 'Usuarios',
                    'scope' => ['Usuarios.status' => 1],
                ]
            ]
        ]);
    }

    public function isAuthorized($user) {
        return true;
    }

    public function beforeFilter(Event $event) {
        parent::beforeFilter($event);
        if (isset($this->request->params['prefix'])) {
            if (!in_array($this->request->params['prefix'], ['administrador', 'clientes'])) {
                $this->Auth->logout();
                $this->redirect(['controller' => 'Usuarios', 'action' => 'logout', 'prefix' => FALSE]);
            }
            $this->Auth->allow();
        } else {
            $this->Auth->allow();
        }
    }

}


text:
import os.path
import configparser
import feedparser
import sqlite3
import re
import requests
import urllib
import time

__auth_cookies = None
__config = None

class Entry:
    def __init__(self, guid, name):
        self.guid = guid
        self.name = name
        self.date = time.strftime("%Y/%m/%d")

def main():
    if not os.path.isfile('history.db'):
        initialize_sqlite()

    # Load config.cfg
    global __config
    __config = configparser.ConfigParser()
    __config.read('config.cfg')

    # List of patterns from file
    patterns = get_patterns()

    # Get login cookie
    global __auth_cookies
    __auth_cookies = qbt_login()

    # Store processed entries and batch add them to sqlite later
    new_entries = []

    while True:
        print("Checking feed...")

        # Get feed object from RSS url in config file
        feed = feedparser.parse(get_feed_url())

        # Go through each entry in feed
        for entry in feed['items']:
            for pattern in patterns:
                # Process entry if it matches one of the patterns
                if re.search(pattern, entry['title']) and is_new_entry(entry['guid']):
                    new_entry = Entry(entry['guid'], entry['title'])

                    # Always store GUID
                    new_entries.append(new_entry)

                    download_torrent(entry['link'])

                    print("New torrent: " + new_entry.name)
                    break

        if len(new_entries) > 0:
            # Add new entries to sqlite database
            add_to_history_many(new_entries)

            print()
            print("New entries: " + str(len(new_entries)))

            # Clear list before looping
            new_entries.clear()
        else:
            print("No new entries")

        try:
            # Sleep for 30min
            time.sleep(30 * 60)
        except KeyboardInterrupt:
            print("User Canceled")
            break

    print("Exiting...")

def add_to_history_many(entries):
    conn = get_database()

    c = conn.cursor()

    for entry in entries:
        c.execute("INSERT INTO feed_history (guid, name) VALUES (?, ?)", (entry.guid, entry.name))

    conn.commit()
    conn.close()

def download_torrent(magnet_link):
    headers = {'Content-Type': 'application/x-www-form-urlencoded',
               'Content-Length': '0'}

    r = requests.post("http://127.0.0.1:8080/command/download",
                      data="urls=" + urllib.parse.quote_plus(magnet_link),
                      headers=headers,
                      cookies=__auth_cookies)

    if r.status_code == 200:
        print("Added torrent successfully.")
    else:
        print("Couldn't add torrent. HTTP status code: " + str(r.status_code))
        return

def initialize_sqlite():
    """
    Creates the sqlite database file.
    """
    conn = get_database()

    query = '''CREATE TABLE feed_history (guid TEXT PRIMARY KEY NOT NULL, name TEXT NOT NULL, date DATETIME DEFAULT CURRENT_DATE)'''

    c = conn.cursor()
    c.execute(query)

    conn.commit()
    conn.close()

def is_new_entry(guid):
    conn = get_database()

    c = conn.cursor()
    c.execute("SELECT guid FROM feed_history WHERE guid=?", (guid,))

    return c.fetchone() is None

def get_database():
    """
    Get the sqlite connection for history database.
    """
    return sqlite3.connect('history.db')

def get_feed_url():
    """
    Get the RSS feed to watch from config.cfg file.
    """
    return __config['General']['Feed']

def get_patterns():
    """
    Get the patterns from config file to filter series.
    """
    filters = []
    filters_config = configparser.ConfigParser()
    filters_config.read('filters.cfg')

    for section in filters_config.sections():
        new_filter = filters_config[section]['Pattern']
        filters.append(new_filter)

    return filters

def qbt_login():
    headers = {'Content-Type': 'application/x-www-form-urlencoded',
               'Content-Length': '0'}

    username = __config['qBitorrent']['Username']
    password = __config['qBitorrent']['Password']
    r = requests.post("http://127.0.0.1:8080/login",
                      data="username=" + username + "&password=" + password,
                      headers=headers)

    if r.status_code == 200:
        print("Logged in successfully.")
    else:
        print("Couldn't login. HTTP status code: " + str(r.status_code))
        return

    return r.cookies

if __name__ == "__main__":
    main()


text:
<!DOCTYPe html>
<meta charset='utf-8'>
<title>drag and drop – feedback overlay of elements partly outside the viewport – 002</title>

Drag the blue box on the right. The drag placeholder should ideally be a blue square. It may optionally be a rectangle the same shape as the visible part of the blue box. No part of the UI should be dragged with the box.


text:
package com.daxslab.mail.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;

public class ConfirmationDialog {

    /**
     * Creates a customized confirmation dialog ({@link AlertDialog}).
     *
     * @param activity The activity this dialog is created for.
     * @param dialogId The id that was used with {@link Activity#showDialog(int)}
     * @param title The resource id of the text to display in the dialog title
     * @param message The text to display in the main dialog area
     * @param confirmButton The resource id of the text to display in the confirm button
     * @param cancelButton The resource id of the text to display in the cancel button
     * @param action The action to perform if the user presses the confirm button
     * @return A confirmation dialog with the supplied arguments
     */
    public static Dialog create(final Activity activity, final int dialogId, final int title,
                                final String message, final int confirmButton, final int cancelButton,
                                final Runnable action) {
        return create(activity, dialogId, title, message, confirmButton, cancelButton,
                      action, null);
    }

    /**
     * Creates a customized confirmation dialog ({@link AlertDialog}).
     *
     * @param activity The activity this dialog is created for.
     * @param dialogId The id that was used with {@link Activity#showDialog(int)}
     * @param title The resource id of the text to display in the dialog title
     * @param message The text to display in the main dialog area
     * @param confirmButton The resource id of the text to display in the confirm button
     * @param cancelButton The resource id of the text to display in the cancel button
     * @param action The action to perform if the user presses the confirm button
     * @param negativeAction The action to perform if the user presses the cancel button. Can be {@code null}.
     * @return A confirmation dialog with the supplied arguments
     */
    public static Dialog create(final Activity activity, final int dialogId, final int title,
                                final String message, final int confirmButton, final int cancelButton,
                                final Runnable action, final Runnable negativeAction) {

        final AlertDialog.Builder builder = new AlertDialog.Builder(activity);
        builder.setTitle(title);
        builder.setMessage(message);
        builder.setPositiveButton(confirmButton,
        new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                activity.dismissDialog(dialogId);
                action.run();
            }
        });
        builder.setNegativeButton(cancelButton,
        new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                activity.dismissDialog(dialogId);
                if (negativeAction != null) {
                    negativeAction.run();
                }
            }
        });
        return builder.create();
    }

    /**
     * Creates a customized confirmation dialog ({@link AlertDialog}).
     *
     * @param activity The activity this dialog is created for.
     * @param dialogId The id that was used with {@link Activity#showDialog(int)}
     * @param title The resource id of the text to display in the dialog title
     * @param message The resource id of text to display in the main dialog area
     * @param confirmButton The resource id of the text to display in the confirm button
     * @param cancelButton The resource id of the text to display in the cancel button
     * @param action The action to perform if the user presses the confirm button
     * @return A confirmation dialog with the supplied arguments
     * @see #create(Activity,int,int,String,int,int,Runnable, Runnable)
     */
    public static Dialog create(final Activity activity, final int dialogId, final int title,
                                final int message, final int confirmButton, final int cancelButton,
                                final Runnable action) {

        return create(activity, dialogId, title, activity.getString(message), confirmButton,
                      cancelButton, action, null);
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<GeocodeResponse>
 <status>OK</status>
 <result>
  <type>locality</type>
  <type>political</type>
  <formatted_address>Münchendorf, Austria</formatted_address>
  <address_component>
   <long_name>Münchendorf</long_name>
   <short_name>Münchendorf</short_name>
   <type>locality</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>Gemeinde Münchendorf</long_name>
   <short_name>Gemeinde Münchendorf</short_name>
   <type>administrative_area_level_3</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>Mödling District</long_name>
   <short_name>Mödling District</short_name>
   <type>administrative_area_level_2</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>Lower Austria</long_name>
   <short_name>Lower Austria</short_name>
   <type>administrative_area_level_1</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>Austria</long_name>
   <short_name>AT</short_name>
   <type>country</type>
   <type>political</type>
  </address_component>
  <geometry>
   <location>
    <lat>48.0296441</lat>
    <lng>16.3793614</lng>
   </location>
   <location_type>APPROXIMATE</location_type>
   <viewport>
    <southwest>
     <lat>48.0029401</lat>
     <lng>16.3518300</lng>
    </southwest>
    <northeast>
     <lat>48.0605800</lat>
     <lng>16.4168998</lng>
    </northeast>
   </viewport>
   <bounds>
    <southwest>
     <lat>48.0029401</lat>
     <lng>16.3518300</lng>
    </southwest>
    <northeast>
     <lat>48.0605800</lat>
     <lng>16.4168998</lng>
    </northeast>
   </bounds>
  </geometry>
  <place_id>ChIJN3RavIOtbUcRsDTmLVeXAAQ</place_id>
 </result>
</GeocodeResponse>


text:
module Admin4rails
  module DatagridHelper
    def datagrid(grid)
      datagrid_table(grid, html: { class: 'table table-striped dataTable' }) +
        content_tag(:div, class: 'row') do
          concat(content_tag(:div, class: 'col-xs-6') { datagrid_total(grid) })
          concat(content_tag(:div, class: 'col-xs-6') { datagrid_pager(grid) })
        end
    end

    private

    def datagrid_total(grid)
      content_tag(:div, class: 'dataTables_info') do
        pluralize(grid.assets.total_count, 'record')
      end
    end

    def datagrid_pager(grid)
      content_tag(:div, class: 'dataTables_paginate paging_bootstrap') do
        paginate grid.assets
      end
    end
  end
end


text:
class CreatePhotos < ActiveRecord::Migration
  def change
    create_table :photos do |t|
      t.integer :user_id, null: false
      t.string :image

      t.timestamps
    end
  end
end


text:
@echo off
:: Copyright (c) 2012 The Chromium Authors. All rights reserved.
:: Use of this source code is governed by a BSD-style license that can be
:: found in the LICENSE file.

:: This script will determine if python, git, or svn binaries need updates.  It
:: returns 123 if the user's shell must restart, otherwise !0 is failure

:: Sadly, we can't use SETLOCAL here otherwise it ERRORLEVEL is not correctly
:: returned.

set CHROME_INFRA_URL=https://storage.googleapis.com/chrome-infra/
:: It used to be %~dp0 but ADODB.Stream may fail to write to this directory if
:: the directory DACL is set to elevated integrity level.
set ZIP_DIR=%TEMP%

:: Get absolute root directory (.js scripts don't handle relative paths well).
pushd %~dp0..\..
set WIN_TOOLS_ROOT_DIR=%CD%
popd

if "%1" == "force" (
  set WIN_TOOLS_FORCE=1
  shift /1
)

:PYTHON_CHECK
if not exist "%WIN_TOOLS_ROOT_DIR%\python276_bin" goto :PY27_INSTALL
if not exist "%WIN_TOOLS_ROOT_DIR%\python.bat" goto :PY27_INSTALL
set ERRORLEVEL=0
goto :GIT_CHECK

:PY27_INSTALL
echo Installing python 2.7.6...
:: Cleanup python directory if it was existing.
set PYTHON_URL=%CHROME_INFRA_URL%python276_bin.zip
if exist "%WIN_TOOLS_ROOT_DIR%\python276_bin\." rd /q /s "%WIN_TOOLS_ROOT_DIR%\python276_bin"
if exist "%ZIP_DIR%\python276.zip" del "%ZIP_DIR%\python276.zip"
echo Fetching from %PYTHON_URL%
cscript //nologo //e:jscript "%~dp0get_file.js" %PYTHON_URL% "%ZIP_DIR%\python276_bin.zip"
if errorlevel 1 goto :PYTHON_FAIL
:: Will create python276_bin\...
cscript //nologo //e:jscript "%~dp0unzip.js" "%ZIP_DIR%\python276_bin.zip" "%WIN_TOOLS_ROOT_DIR%"
:: Create the batch files.
call copy /y "%~dp0python276.new.bat" "%WIN_TOOLS_ROOT_DIR%\python.bat" 1>nul
call copy /y "%~dp0pylint.new.bat" "%WIN_TOOLS_ROOT_DIR%\pylint.bat" 1>nul
del "%ZIP_DIR%\python276_bin.zip"
set ERRORLEVEL=0
goto :GIT_CHECK

:PYTHON_FAIL
echo ... Failed to checkout python automatically.
echo You should get the "prebaked" version at %PYTHON_URL%
set ERRORLEVEL=1
goto :END

:GIT_CHECK

:: must explicitly use FIND_EXE to prevent this from grabbing e.g. gnuwin32 or
:: msys versions.
set FIND_EXE=%SYSTEMROOT%\System32\find.exe

:: Check to see if we're on a 32 or 64 bit system
:: (parens) are necessary, otherwise batch puts an extra space after 32.
reg Query "HKLM\Hardware\Description\System\CentralProcessor\0" | %FIND_EXE% /i "x86" > NUL && (set OS_BITS=32) || (set OS_BITS=64)

"%WIN_TOOLS_ROOT_DIR%\python.bat" "%~dp0git_bootstrap.py" --bits "%OS_BITS%"
goto :END

:returncode
set WIN_TOOLS_ROOT_DIR=
exit /b %ERRORLEVEL%

:END
call :returncode %ERRORLEVEL%


text:
/*
 ONOS GUI -- Icon Service (theme) -- CSS file
 */

div.close-btn svg.embeddedIcon g.icon .glyph {
    fill: #333333;
}

/* Sortable table headers */
div.tableColSort svg.embeddedIcon .icon .glyph {
    fill: #353333;
}

/* --- Control Buttons --- */

/* INACTIVE */
svg.embeddedIcon g.icon use {
    fill: #e0dfd6;
}
/* note: no change for inactive buttons when hovered */

/* ACTIVE */
.ctrl-btns div.active svg.embeddedIcon g.icon use {
    fill: #939598;
}

svg.embeddedIcon g.icon.active:hover use {
    fill: #ce5b58;
}

/* CURRENT-VIEW */
svg.embeddedIcon g.icon.current-view rect {
    fill: #518ecc;
}
svg.embeddedIcon g.icon.current-view use {
    fill: white;
}

/* REFRESH */
svg.embeddedIcon g.icon.refresh use {
    fill: #cdeff2;
}
svg.embeddedIcon g.icon.refresh:hover use {
    fill: #ce5b58;
}
svg.embeddedIcon g.icon.refresh.active use {
    fill: #009fdb;
}
svg.embeddedIcon g.icon.refresh.active:hover use {
    fill: #ce5b58;
}

/* ========== DARK Theme ========== */

 div.close-btn svg.embeddedIcon g.icon .glyph {
    fill: #8d8d8d;
}

 div.tableColSort svg.embeddedIcon .icon .glyph {
    fill: #888888;
}

 /*svg.embeddedIcon .icon.active .glyph {
    fill: #04bf34;
}
 svg.embeddedIcon .icon.inactive .glyph {
    fill: #c0242b;
}*/

 table svg.embeddedIcon .icon .glyph {
    fill: #9999aa;
}

/*
svg.embeddedIcon g.icon .glyph {
    fill: #007dc4;
}

svg.embeddedIcon:hover g.icon .glyph {
    fill: #20b2ff;
}
*/

svg.embeddedIcon g.icon.devIcon_SWITCH .glyph {
    fill: #0071bd;;
}

svg.embeddedIcon g.icon.hostIcon_endstation .glyph {
    fill: #0071bd;;
}


text:
// Copyright 2011 Google Inc. All Rights Reserved.

package com.google.devtools.simple.runtime.components.android;

import com.google.devtools.simple.runtime.annotations.SimpleEvent;
import com.google.devtools.simple.runtime.annotations.SimpleFunction;
import com.google.devtools.simple.runtime.annotations.SimpleObject;
import com.google.devtools.simple.runtime.events.EventDispatcher;

import android.content.Intent;

/**
 * Abstract superclass for all of the "Picker" components.
 *
 */
@SimpleObject
public abstract class Picker extends ButtonBase implements ActivityResultListener {
  protected final ComponentContainer container;

  /* Used to identify the call to startActivityForResult. Will be passed back into the
  resultReturned() callback method. */
  protected int requestCode;

  public Picker(ComponentContainer container) {
    super(container);
    this.container = container;
  }

  /**
   *  Provides the Intent used to launch the picker activity.
   */
  protected abstract Intent getIntent();

  @Override
  public void click() {
    BeforePicking();
    if (requestCode == 0) { // only need to register once
      requestCode = container.$form().registerForActivityResult(this);
    }
    container.$context().startActivityForResult(getIntent(), requestCode);
  }

  // Functions

  /**
   * Opens the picker, as though the user clicked on it.
   */
  @SimpleFunction
  public void Open() {
    click();
  }

  // Events

  /**
   * Simple event to raise when the component is clicked but before the
   * picker activity is started.
   */
  @SimpleEvent
  public void BeforePicking() {
    EventDispatcher.dispatchEvent(this, "BeforePicking");
  }

  /**
   * Simple event to be raised after the picker activity returns its
   * result and the properties have been filled in.
   */
  @SimpleEvent
  public void AfterPicking() {
    EventDispatcher.dispatchEvent(this, "AfterPicking");
  }
}


text:
using Google.Api.Gax;
using Google.Api.Gax.ResourceNames;
using Google.Cloud.Spanner.Admin.Instance.V1;
using Google.Cloud.Spanner.Common.V1;
using Google.Cloud.Spanner.V1.Internal.Logging;
using Grpc.Core;
using System;

namespace Google.Cloud.Spanner.Data.CommonTesting;

/// <summary>
/// Base class for Spanner Test database.
/// </summary>
public abstract class SpannerTestDatabaseBase
{
    /// <summary>
    /// The Spanner Host name to connect to. It is read from the environment variable "TEST_SPANNER_HOST".
    /// </summary>
    public string SpannerHost { get; } = GetEnvironmentVariableOrDefault("TEST_SPANNER_HOST", null);

    /// <summary>
    /// The Spanner port number to connect to. It is read from the environment variable "TEST_SPANNER_PORT".
    /// </summary>
    public string SpannerPort { get; } = GetEnvironmentVariableOrDefault("TEST_SPANNER_PORT", null);

    /// <summary>
    /// The Spanner Instance name to connect to. It is read from the environment variable "TEST_SPANNER_INSTANCE".
    /// </summary>
    public string SpannerInstance { get; } = GetEnvironmentVariableOrDefault("TEST_SPANNER_INSTANCE", "spannerintegration");

    /// <summary>
    /// The generated name for the database.
    /// The derived class must provide its implementation to return the database name.
    /// </summary>
    public abstract string GeneratedDatabaseName { get; }

    /// <summary>
    /// The environment variable from which the Spanner database name is read.
    /// </summary>
    public abstract string SpannerDatabaseEnvVariable { get; }

    /// <summary>
    /// The Spanner Database name to connect to.
    /// </summary>
    public string SpannerDatabase { get; }

    // This is the simplest way of checking whether the environment variable was specified or not.
    // It's a little ugly, but simpler than the alternatives.
    /// <summary>
    /// Returns true if the database was created just for this test, or false if the database was an existing one
    /// specified through an environment variable.
    /// </summary>
    public bool Fresh => SpannerDatabase == GeneratedDatabaseName;

    /// <summary>
    /// Connection string including database.
    /// </summary>
    public string ConnectionString { get; }

    /// <summary>
    /// Connection string without the database.
    /// </summary>
    public string NoDbConnectionString { get; }

    /// <summary>
    /// The GCP Project ID to be used for the test database.
    /// </summary>
    public string ProjectId { get; }

    /// <summary>
    /// The fully-qualified database name.
    /// </summary>
    public DatabaseName DatabaseName { get; }

    internal SpannerClientCreationOptions SpannerClientCreationOptions { get; }

    protected SpannerTestDatabaseBase(string projectId, EmulatorDetection emulatorDetection)
    {
        TestLogger.Install();
        SpannerDatabase = GetEnvironmentVariableOrDefault(SpannerDatabaseEnvVariable, GeneratedDatabaseName);
        ProjectId = projectId;
        var builder = new SpannerConnectionStringBuilder
        {
            Host = SpannerHost,
            DataSource = $"projects/{ProjectId}/instances/{SpannerInstance}",
            EmulatorDetection = emulatorDetection
        };
        if (SpannerPort != null)
        {
            builder.Port = int.Parse(SpannerPort);
        }
        NoDbConnectionString = builder.ConnectionString;
        SpannerClientCreationOptions = new SpannerClientCreationOptions(builder);
        var databaseBuilder = builder.WithDatabase(SpannerDatabase);
        ConnectionString = databaseBuilder.ConnectionString;
        DatabaseName = databaseBuilder.DatabaseName;

        // We create database instance only on the emulator.
        // In production, we expect the instance to already exist.
        MaybeCreateInstanceOnEmulator(projectId);

        if (Fresh)
        {
            CreateDatabase();
            Logger.DefaultLogger.Debug($"Created database {SpannerDatabase}.");
        }
        else
        {
            Logger.DefaultLogger.Debug($"Using existing database {SpannerDatabase}");
        }
    }

    protected static string GetEnvironmentVariableOrDefault(string name, string defaultValue)
    {
        string value = Environment.GetEnvironmentVariable(name);
        return string.IsNullOrEmpty(value) ? defaultValue : value;
    }

    protected abstract void CreateDatabase();

    protected void MaybeCreateInstanceOnEmulator(string projectId)
    {
        if (SpannerClientCreationOptions.UsesEmulator)
        {
#if NETSTANDARD2_1
            // On .NET Core 3.1 (but not .NET 6) Grpc.Net.Client needs an additional switch
            // to allow an insecure channel in HTTP/2.
            AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
#endif
            // Try to create an instance on the emulator and ignore any AlreadyExists error.
            var adminClientBuilder = new InstanceAdminClientBuilder
            {
                EmulatorDetection = EmulatorDetection.EmulatorOnly
            };
            var instanceAdminClient = adminClientBuilder.Build();

            var instanceName = InstanceName.FromProjectInstance(projectId, SpannerInstance);
            try
            {
                instanceAdminClient.CreateInstance(new CreateInstanceRequest
                {
                    InstanceId = instanceName.InstanceId,
                    ParentAsProjectName = ProjectName.FromProject(projectId),
                    Instance = new Instance
                    {
                        InstanceName = instanceName,
                        ConfigAsInstanceConfigName = new InstanceConfigName(projectId, "emulator-config"),
                        DisplayName = "Test Instance",
                        NodeCount = 1,
                    },
                }).PollUntilCompleted();
            }
            catch (RpcException e) when (e.StatusCode == StatusCode.AlreadyExists)
            {
                // Ignore
            }
        }
    }

    /// <summary>
    /// Creates a <see cref="SpannerConnection"/> with a specific logger.
    /// </summary>
    /// <returns>The SpannerConnection.</returns>
    public SpannerConnection GetConnection(Logger logger, bool logCommitStats = false) =>
        new SpannerConnection(new SpannerConnectionStringBuilder(ConnectionString)
        {
            SessionPoolManager = SessionPoolManager.Create(new V1.SessionPoolOptions(), logger),
            LogCommitStats = logCommitStats
        });
}


text:
package org.redisson.executor;

import org.redisson.api.RedissonClient;
import org.redisson.api.annotation.RInject;

public class ScheduledLongRunnableTask implements Runnable {

    @RInject
    private RedissonClient redisson;
    private String objectName;

    public ScheduledLongRunnableTask() {
    }

    public ScheduledLongRunnableTask(String objectName) {
        super();
        this.objectName = objectName;
    }

    @Override
    public void run() {
        for (long i = 0; i < Long.MAX_VALUE; i++) {
            if (Thread.currentThread().isInterrupted()) {
                System.out.println("interrupted " + i);
                redisson.getBucket(objectName).set(i);
                return;
            }
        }
    }

}


text:
/* Adrian Rodriguez Bazaga
 * alu0100826456
 * Estructura de datos "pila"
 * Practica 3 - Algoritmos y Estructura de Datos Avanzadas
 */

#pragma once

#include "vector.cpp"

template<class Tdato> class stack_t
{
private:
	Vector<Tdato> vector_;													//Atributo: Vector que contiene los datos de la pila
	int top_;																//Atributo: Posición del elemento que está arriba de la pila

public:
	stack_t(void);															//Constructor por defecto
	~stack_t(void);															//Destructor

	void push(Tdato dato);													//Poner elemento en el top de la pila
	Tdato pop(void);														//Sacar elemento del top de la pila

	inline bool empty(void) { return (top_ == -1); }						//Comprobar si la pila está vacía

};

template <class Tdato> stack_t<Tdato>::stack_t(void):
	vector_(),
	top_(-1)
{}

template <class Tdato> stack_t<Tdato>::~stack_t(void)
{
	top_ = -1;
}

template <class Tdato> void stack_t<Tdato>::push(Tdato dato){
	top_ ++;
	vector_.push_back(dato);
}

template <class Tdato> Tdato stack_t<Tdato>::pop(void)
{
	try
	{
		if(empty())
		{
			throw("Error al extraer elemento de la pila, la pila está vacía");
		}
		Tdato aux = vector_.at(top_);
		top_ --;
		return aux;
	}
	catch(const char* msg)
	{
		cerr << msg << endl;
		exit(1);
	}
}


text:
#include "concurrent/aeron_counters_manager.h"
#include "aeron_driver_conductor_proxy.h"
#include "aeron_alloc.h"
#include "concurrent/aeron_thread.h"
#include "aeron_driver_conductor.h"

void aeron_driver_conductor_proxy_offer(aeron_driver_conductor_proxy_t *conductor_proxy, void *cmd)
{
    while (aeron_mpsc_concurrent_array_queue_offer(conductor_proxy->command_queue, cmd) != AERON_OFFER_SUCCESS)
    {
        aeron_counter_ordered_increment(conductor_proxy->fail_counter, 1);
        sched_yield();
    }
}

void aeron_driver_conductor_proxy_on_delete_cmd(
    aeron_driver_conductor_proxy_t *conductor_proxy, aeron_command_base_t *cmd)
{
    if (AERON_THREADING_MODE_SHARED == conductor_proxy->threading_mode)
    {
        /* should not get here! */
    }
    else
    {
        cmd->func = aeron_command_on_delete_cmd;
        cmd->item = NULL;

        aeron_driver_conductor_proxy_offer(conductor_proxy, cmd);
    }
}

void aeron_driver_conductor_proxy_on_create_publication_image_cmd(
    aeron_driver_conductor_proxy_t *conductor_proxy,
    int32_t session_id,
    int32_t stream_id,
    int32_t initial_term_id,
    int32_t active_term_id,
    int32_t term_offset,
    int32_t term_length,
    int32_t mtu_length,
    struct sockaddr_storage *control_address,
    struct sockaddr_storage *src_address,
    void *endpoint)
{
    if (AERON_THREADING_MODE_SHARED == conductor_proxy->threading_mode)
    {
        aeron_command_create_publication_image_t cmd =
            {
                .base = { .func = aeron_driver_conductor_on_create_publication_image, .item = NULL },
                .session_id = session_id,
                .stream_id = stream_id,
                .initial_term_id = initial_term_id,
                .active_term_id = active_term_id,
                .term_offset = term_offset,
                .term_length = term_length,
                .mtu_length = mtu_length,
                .endpoint = endpoint
            };

        memcpy(&cmd.control_address, control_address, sizeof(struct sockaddr_storage));
        memcpy(&cmd.src_address, src_address, sizeof(struct sockaddr_storage));

        aeron_driver_conductor_on_create_publication_image(conductor_proxy->conductor, &cmd);
    }
    else
    {
        aeron_command_create_publication_image_t *cmd;

        if (aeron_alloc((void **)&cmd, sizeof(aeron_command_create_publication_image_t)) < 0)
        {
            aeron_counter_ordered_increment(conductor_proxy->fail_counter, 1);
            return;
        }

        cmd->base.func = aeron_driver_conductor_on_create_publication_image;
        cmd->base.item = NULL;

        cmd->session_id = session_id;
        cmd->stream_id = stream_id;
        cmd->initial_term_id = initial_term_id;
        cmd->active_term_id = active_term_id;
        cmd->term_offset = term_offset;
        cmd->term_length = term_length;
        cmd->mtu_length = mtu_length;
        cmd->endpoint = endpoint;
        memcpy(&cmd->control_address, control_address, sizeof(struct sockaddr_storage));
        memcpy(&cmd->src_address, src_address, sizeof(struct sockaddr_storage));

        aeron_driver_conductor_proxy_offer(conductor_proxy, cmd);
    }
}

void aeron_driver_conductor_proxy_on_linger_buffer(
    aeron_driver_conductor_proxy_t *conductor_proxy, uint8_t *buffer)
{
    if (AERON_THREADING_MODE_SHARED == conductor_proxy->threading_mode)
    {
        aeron_free(buffer);
    }
    else
    {
        aeron_command_base_t *cmd;

        if (aeron_alloc((void **)&cmd, sizeof(aeron_command_base_t)) < 0)
        {
            aeron_counter_ordered_increment(conductor_proxy->fail_counter, 1);
            return;
        }

        cmd->func = aeron_driver_conductor_on_linger_buffer;
        cmd->item = buffer;

        aeron_driver_conductor_proxy_offer(conductor_proxy, cmd);
    }
}

void aeron_command_on_delete_cmd(void *clientd, void *cmd)
{
    aeron_command_base_t *command = (aeron_command_base_t *)cmd;

    aeron_free(command->item);
    aeron_free(cmd);
}


text:
layout: post
title: "[Tech] Git 2.23.0 출시: checkout 기능 분리(switch, restore)"
category: [tech]
tags: [git]
date: 2019-08-30 00:00:00
---

깃(Git) 2.23 버전이 지난 08월 16일 출시되었다.

![git 2.23.0
release](https://github.blog/wp-content/uploads/2019/08/62679250-c8510100-b968-11e9-9e6b-7e5fd1c16dfa.png?w=1200)

가장 눈에 띄는 특징은 `checkout` 의 기능이 각각 `switch` 와 `restore` 로
분리된 것이다.

기존의 `checkout` 은 브랜치를 생성()하거나 이동하거나 복원(Restore)하는
용도로 사용되었다.

2.23.0 이전
===========

-   브랜치 변경 및 생성

        usage: git checkout [<options>] <branch>
           or: git checkout [<options>] [<branch>] -- <file>...

            -q, --quiet           suppress progress reporting
            -b <branch>           create and checkout a new branch
            -B <branch>           create/reset and checkout a branch
            -l                    create reflog for new branch
            --detach              detach HEAD at named commit
            -t, --track           set upstream info for new branch
            --orphan <new-branch>
                                  new unparented branch
            -2, --ours            checkout our version for unmerged files
            -3, --theirs          checkout their version for unmerged files
            -f, --force           force checkout (throw away local modifications)
            -m, --merge           perform a 3-way merge with the new branch
            --overwrite-ignore    update ignored files (default)
            --conflict <style>    conflict style (merge or diff3)
            -p, --patch           select hunks interactively
            --ignore-skip-worktree-bits
                                  do not limit pathspecs to sparse entries only
            --ignore-other-worktrees
                                  do not check if another worktree is holding the given ref
            --recurse-submodules[=<checkout>]
                                  control recursive updating of submodules
            --progress            force progress reporting

-   복원(`git checkout — <file>`)

        On branch master
        Your branch is up to date with 'origin/master'.

        Changes not staged for commit:
          (use "git add/rm <file>..." to update what will be committed)
          (use "git checkout -- <file>..." to discard changes in working directory)

            deleted:    _posts/2019-08-29-git-2.23-release.adoc

        no changes added to commit (use "git add" and/or "git commit -a")

그런데 이것이 각각 분리된 것이다.

2.23.0 이후
===========

우선 업데이트 하는 방법은,

-   맥OS: brew

        $ brew update git

-   Linux(Ubuntu)

        $ git --version
        git version 2.17.1 // 현재 버전은 2.17.1

        $ sudo add-apt-repository ppa:git-core/ppa // Git PPA 추가
        [sudo] password for honeymon:
         The most current stable version of Git for Ubuntu.

        For release candidates, go to https://launchpad.net/~git-core/+archive/candidate .
         More info: https://launchpad.net/~git-core/+archive/ubuntu/ppa
        Press [ENTER] to continue or Ctrl-c to cancel adding it.

        $ sudo apt update && sudo apt upgrade
        // 생략
        $ sudo apt upgrade
        Reading package lists... Done
        Building dependency tree
        Reading state information... Done
        Calculating upgrade... Done
        The following NEW packages will be installed:
          libpcre2-8-0
        The following packages will be upgraded:
          git git-man gitk
        3 upgraded, 1 newly installed, 0 to remove and 0 not upgraded.
        Need to get 8,982 kB of archives.
        After this operation, 9,327 kB of additional disk space will be used.
        Do you want to continue? [Y/n] y

        // 생략

        $ git --version
        git version 2.23.0 // 2.23.0 설치

> **Note**
>
> 깃에 대한 PPA 저장소를 추가해야 최신버전을 설치할 수 있다.

`switch` 와 `restore` 동작 확인
===============================

> Git 2.23 brings a new pair of experimental commands to the suite of
> existing ones: git switch and git restore. These two are meant to
> eventually provide a better interface for the well-known git checkout.
> The new commands intend to each have a clear separation, neatly
> divvying up what the many responsibilities of git checkout, as we'll
> show below.
>
> If you've tried to list out what's possible with git checkout, you
> might have visited the documentation to figure it out. You might have
> seen the phrase, **"switch branches or restore working tree files"**
> and scratched your head. Huh?
>
> —  Taylor Blau Highlights from Git 2.23

> **Note**
>
> 브랜치를 변경(Switch) 하고 작업 파일을 복원(Restore) 한다.
>
> 이렇게 기억하면 된다.

`switch`: 브랜치를 변경한다.
----------------------------

브랜치를 (없는 경우 생성하면서) 변경할 수 있다.

-   브랜치 변경

        git:(master) $ git switch develop
        Switched to branch 'develop'
        git:(develop) $

-   브랜치 생성 및 변경

        git:(develop) git switch -c feature/git-switch
        Switched to a new branch 'feature/git-switch'

        git:(feature/git-switch)

이 외에도 다양한 선택사항이 존재한다. `git switch --help`로
확인가능하다.

`restore`: 작업중인 파일을 복원한다.
------------------------------------

    git:(develop) $ git status
    On branch develop
    Changes not staged for commit:
      (use "git add <file>..." to update what will be committed)
      (use "git restore <file>..." to discard changes in working directory)
        modified:   build.gradle // 변경한 파일이 있다. 위에서 git restore 로 변경사항을 되돌릴 수 있다고 알리고 있다.

    no changes added to commit (use "git add" and/or "git commit -a")
    git:(develop) $ git restore build.gradle  // 복구
    git:(develop) $ git status
    On branch develop
    nothing to commit, working tree clean
    git:(develop) $

정리
====

깃에서 다양한 역할을 수행하던 `checkout` 명령어가 보다 명확한 2개의
명령어로 분리되었다.

-   `switch`: 브랜치 변경

-   `restore`: 변경사항 복원

> **Note**
>
> 브랜치(Branch)를 가지로 쓸까말까 고민중…

참고
====

-   [Highlights from Git
    2.23](https://github.blog/2019-08-16-highlights-from-git-2-23/)

-   [Download for Linux and Unix](https://git-scm.com/download/linux)


text:
package org.elasticsearch.hadoop;

import java.io.File;

import org.apache.commons.logging.LogFactory;
import org.elasticsearch.hadoop.cfg.ConfigurationOptions;
import org.elasticsearch.hadoop.util.StringUtils;
import org.elasticsearch.hadoop.util.TestUtils;
import org.elasticsearch.hadoop.util.unit.Booleans;
import org.junit.rules.ExternalResource;

public class LocalEs extends ExternalResource {

    private static EsEmbeddedServer master;
    private static EsEmbeddedServer slave;

    public static final String CLUSTER_NAME = "ES-HADOOP-TEST";
    private static final String ES_HOME_PATH = "build/es.home";
    private static final String ES_DATA_PATH = "build/es.data";
    public static final String DATA_PORTS = "9500-9599";
    public static final String TRANSPORT_PORTS = "9600-9699";
    public static final String DATA_PORTS_SLAVE = "9700-9799";
    public static final String TRANSPORT_PORTS_SLAVE = "9800-9899";

    private boolean USE_SLAVE = false;
    private boolean disabled = false;

    @Override
    protected void before() throws Throwable {

        if (Booleans.parseBoolean(HdpBootstrap.hadoopConfig().get("test.disable.local.es"))) {
            disabled = true;
            LogFactory.getLog(getClass()).warn(
                    "local ES disable; assuming an external instance and bailing out...");
            return;
        }

        String host = HdpBootstrap.hadoopConfig().get(ConfigurationOptions.ES_NODES);
        String port = HdpBootstrap.hadoopConfig().get(ConfigurationOptions.ES_PORT);

        if (StringUtils.hasText(host)) {
            disabled = true;
            LogFactory.getLog(getClass()).warn("es.nodes/host specified; assuming an external instance and bailing out...");
            return;
        }

        // delete data path to start fresh
        TestUtils.delete(new File(ES_DATA_PATH));

        if (master == null) {
            System.out.println("Starting Elasticsearch Master...");
            master = new EsEmbeddedServer(CLUSTER_NAME, ES_HOME_PATH, ES_DATA_PATH, DATA_PORTS, TRANSPORT_PORTS, USE_SLAVE);
            master.start();
        }

        if (USE_SLAVE && slave == null) {
            System.out.println("Starting Elasticsearch Slave...");
            slave = new EsEmbeddedServer(CLUSTER_NAME, ES_HOME_PATH, ES_DATA_PATH, DATA_PORTS_SLAVE, TRANSPORT_PORTS_SLAVE, USE_SLAVE);
            slave.start();
        }
    }

    @Override
    protected void after() {
        if (master != null) {
            if (USE_SLAVE && slave != null) {
                System.out.println("Stopping Elasticsearch Slave...");
                slave.stop();
                slave = null;
            }

            System.out.println("Stopping Elasticsearch Master...");
            try {
                master.stop();
            } catch (Exception ex) {
                // ignore
            }
            master = null;

            // delete data folder
            TestUtils.delete(new File(ES_DATA_PATH));
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Text;

using Microsoft.Xna.Framework.Content;

namespace KiloWatt.Animation.Animation
{
  //  The AnimationSet is a dictionary of animations, which you
  //  can find by name (or by iteration). It is mostly used as a
  //  nice wrapper over AnimationDictionary and for file I/O.
  public class AnimationSet
  {
    public AnimationSet()
    {
    }

    public AnimationSet(AnimationDictionary animations)
    {
      animations_ = animations;
    }

    AnimationDictionary animations_ = new AnimationDictionary();
    public AnimationDictionary AnimationDictionary { get { return animations_; } }

    internal void Load(AnimationDictionary animations)
    {
      animations_ = animations;
    }

    //  Given a name, return the animation of that name, or null.
    public Animation AnimationByName(string name)
    {
      Animation oot;
      if (animations_.TryGetValue(name, out oot))
        return oot;
      return null;
    }

    //  Return the names of all animations.
    public IEnumerable<string> AnimationNames { get { return animations_.Keys; } }

    //  Return all animations.
    public IEnumerable<Animation> Animations { get { return animations_.Values; } }

    //  Return the number of animations.
    public int NumAnimations { get { return animations_.Count; } }

    //  Add an animation to the set. The name must be unique.
    public void AddAnimation(Animation anim)
    {
      Animation oot;
      if (animations_.TryGetValue(anim.Name, out oot))
        throw new System.ArgumentException(
            String.Format("An animation with the name {0} already exists in AnimationSet.AddAnimation()",
            anim.Name), "anim");
      animations_.Add(anim.Name, anim);
    }

    //  Remove a given animation (which must already be in the set).
    public void RemoveAnimation(Animation anim)
    {
      Animation oot;
      if (!animations_.TryGetValue(anim.Name, out oot))
        throw new System.ArgumentException(
            String.Format("An animation with the name {0} doesn't exist in AnimationSet.RemoveAnimation()",
            anim.Name), "anim");
      animations_.Remove(anim.Name);
    }
  }

  //  AnimationDictionary is the underlying storage for
  public class AnimationDictionary : Dictionary<string, Animation>
  {
  }

  //  File I/O
  public class AnimationSetReader : ContentTypeReader<AnimationSet>
  {
    public AnimationSetReader()
    {
    }

    protected override AnimationSet Read(ContentReader input, AnimationSet existingInstance)
    {
      if (existingInstance == null)
        existingInstance = new AnimationSet();
      AnimationDictionary animations = input.ReadObject<AnimationDictionary>();
      existingInstance.Load(animations);
      return existingInstance;
    }
  }

  //  File I/O
  public class AnimationDictionaryReader : ContentTypeReader<AnimationDictionary>
  {
    public AnimationDictionaryReader()
    {
    }

    protected override AnimationDictionary Read(ContentReader input, AnimationDictionary existingInstance)
    {
      if (existingInstance == null)
        existingInstance = new AnimationDictionary();
      int num = input.ReadInt32();
      for (int i = 0; i != num; ++i)
      {
        string name = input.ReadString();
        Animation anim = input.ReadObject<Animation>();
        existingInstance.Add(name, anim);
      }
      return existingInstance;
    }
  }
}


text:
package vtk.security.web.basic;

import org.springframework.beans.factory.annotation.Required;
import vtk.security.AuthenticationException;
import vtk.security.AuthenticationProcessingException;
import vtk.security.Principal;
import vtk.security.PrincipalImpl;
import vtk.security.store.MD5PasswordStore;

public class HttpBasicAuthenticationHandler extends
        AbstractHttpBasicAuthenticationHandler {

    private MD5PasswordStore principalStore = null;

    @Required
    public void setPrincipalStore(MD5PasswordStore principalStore) {
        this.principalStore = principalStore;
    }

    public void authenticateInternal(String uid, String password)
            throws AuthenticationProcessingException, AuthenticationException {
        Principal principal = new PrincipalImpl(uid, Principal.Type.USER);
        this.principalStore.authenticate(principal, password);
    }

}


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

    <title>Numeroo</title>
    <meta name="viewport" content="width=device-width target-densitydpi=device-dpi initial-scale=1 maximum-scale=1 user-scalable=0"/>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <link rel="stylesheet" type="text/css" href="css/main.css"/>
    <link rel="stylesheet" type="text/css" href="css/license.css"></link>
    <link rel="stylesheet" type="text/css" href="css/infodialog.css"></link>

.

.

.

New Game

Resume Game

Help

Easy

Normal

Hard

View Hint

Write Hint

Help

New Game

Choose Theme

Options

Start

    <canvas id="mainMenuCanvas" class="gridcanvas"></canvas>
    <canvas id="bottomcanvas" class="bottomcanvas"></canvas>
    <canvas id="highlightcanvas" class="bottomcanvas"></canvas>
    <canvas id="gridcanvas" class="gridcanvas"></canvas>
    <canvas id="topcanvas" class="topcanvas"></canvas>
    <canvas id="startNewGameCanvas" class="topcanvas" style="display: none"></canvas>

 i

          Memory Game for Older Kids is a game where player tries to find pair

          of cards which have same image.

          Author/Owner: Todd Brandt <todd.e.brandt@intel.com>

          Technical Details: This application is written using HTML5/css3/jquery javascript

          library and is distributed under Apache2.0 license.

          LIBRARIES

          jQuery JavaScript Library v1.7.2

          Copyright 2011, John Resig

          Dual licensed under the MIT or GPL Version 2 licenses.

          http://jquery.org/license

          FONTS

          Google web font - Sancreek

          http://www.google.com/webfonts/specimen/Sancreek

          SIL Open Font License, 1.1

          Romantiques

          Author: Diater Steffmann

          License: Freeware. Commercial use allowed.

          http://www.fontspace.com/dieter-steffmann/romantiques

          SOUNDS

          These files were created by Intel Corp. and are licensed under

          the Creative Commons Attribution 3.0 license http://creativecommons.org/licenses/by/3.0/us/

          FlipCard.wav,

          StartPage.wav,

          TheFinale.wav,

          WinLevel.wav,

          YouWin.wav

          IMAGES

          all images are created by Intel Corp.

          they are licensed under the Creative Commons Attribution 3.0 license

          http://creativecommons.org/licenses/by/3.0/us/

          KNOWN ISSUES

          1) Message to unlock all levels in order to play appears even after the levels have been unlocked.

Back

 x

        The object of the game is to place the numbers 1-9 in every square
        on a 9x9 grid, with no number repeating in any row, column, or 3x3 subgrid.

        Numbers are entered by clicking a square, then either clicking or using the
        keyboard to enter digits from 1-9. The arrow keys can be used to change
        which cell is selected. You can write hints for a square by clicking
        "Write Hint", or holding down the SHIFT key when clicking a square.
        When a row, column, or subgrid has been completely filled, its background
        is highlighted.

 x

YOU WIN!!!

Your Time: <t></t>