text:
// Copyright 2013 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.

package org.chromium.chromoting.jni;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.os.Looper;
import android.util.Log;

import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
import org.chromium.chromoting.CapabilityManager;
import org.chromium.chromoting.R;
import org.chromium.chromoting.SessionAuthenticator;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

/**
 * Initializes the Chromium remoting library, and provides JNI calls into it.
 * All interaction with the native code is centralized in this class.
 */
@JNINamespace("remoting")
public class JniInterface {
    /*
     * Library-loading state machine.
     */
    /** Whether the library has been loaded. Accessed on the UI thread. */
    private static boolean sLoaded = false;

    /** Used for authentication-related UX during connection. Accessed on the UI thread. */
    private static SessionAuthenticator sAuthenticator;

    /** Interface used for connection state notifications. */
    public interface ConnectionListener {
        /**
         * This enum must match the C++ enumeration remoting::protocol::ConnectionToHost::State.
         */
        public enum State {
            INITIALIZING(0),
            CONNECTING(1),
            AUTHENTICATED(2),
            CONNECTED(3),
            FAILED(4),
            CLOSED(5);

            private final int mValue;

            State(int value) {
                mValue = value;
            }

            public int value() {
                return mValue;
            }

            public static State fromValue(int value) {
                return values()[value];
            }
        }

        /**
         * This enum must match the C++ enumeration remoting::protocol::ErrorCode.
         */
        public enum Error {
            OK(0, 0),
            PEER_IS_OFFLINE(1, R.string.error_host_is_offline),
            SESSION_REJECTED(2, R.string.error_invalid_access_code),
            INCOMPATIBLE_PROTOCOL(3, R.string.error_incompatible_protocol),
            AUTHENTICATION_FAILED(4, R.string.error_invalid_access_code),
            CHANNEL_CONNECTION_ERROR(5, R.string.error_p2p_failure),
            SIGNALING_ERROR(6, R.string.error_p2p_failure),
            SIGNALING_TIMEOUT(7, R.string.error_p2p_failure),
            HOST_OVERLOAD(8, R.string.error_host_overload),
            UNKNOWN_ERROR(9, R.string.error_unexpected);

            private final int mValue;
            private final int mMessage;

            Error(int value, int message) {
                mValue = value;
                mMessage = message;
            }

            public int value() {
                return mValue;
            }

            public int message() {
                return mMessage;
            }

            public static Error fromValue(int value) {
                return values()[value];
            }
        }

        /**
         * Notified on connection state change.
         * @param state The new connection state.
         * @param error The error code, if state is STATE_FAILED.
         */
        void onConnectionState(State state, Error error);
    }

    /*
     * Connection-initiating state machine.
     */
    /** Whether the native code is attempting a connection. Accessed on the UI thread. */
    private static boolean sConnected = false;

    /** Notified upon successful connection or disconnection. Accessed on the UI thread. */
    private static ConnectionListener sConnectionListener = null;

    /**
     * Callback invoked on the graphics thread to repaint the desktop. Accessed on the UI and
     * graphics threads.
     */
    private static Runnable sRedrawCallback = null;

    /** Bitmap holding a copy of the latest video frame. Accessed on the UI and graphics threads. */
    private static Bitmap sFrameBitmap = null;

    /** Protects access to sFrameBitmap. */
    private static final Object sFrameLock = new Object();

    /** Position of cursor hot-spot. Accessed on the graphics thread. */
    private static Point sCursorHotspot = new Point();

    /** Bitmap holding the cursor shape. Accessed on the graphics thread. */
    private static Bitmap sCursorBitmap = null;

    /** Capability Manager through which capabilities and extensions are handled. */
    private static CapabilityManager sCapabilityManager = CapabilityManager.getInstance();

    /**
     * To be called once from the main Activity. Any subsequent calls will update the application
     * context, but not reload the library. This is useful e.g. when the activity is closed and the
     * user later wants to return to the application. Called on the UI thread.
     */
    public static void loadLibrary(Context context) {
        if (sLoaded) return;

        System.loadLibrary("remoting_client_jni");

        nativeLoadNative(context);
        sLoaded = true;
    }

    /** Performs the native portion of the initialization. */
    private static native void nativeLoadNative(Context context);

    /*
     * API/OAuth2 keys access.
     */
    public static native String nativeGetApiKey();
    public static native String nativeGetClientId();
    public static native String nativeGetClientSecret();

    /** Returns whether the client is connected. */
    public static boolean isConnected() {
        return sConnected;
    }

    /** Attempts to form a connection to the user-selected host. Called on the UI thread. */
    public static void connectToHost(String username, String authToken,
            String hostJid, String hostId, String hostPubkey, ConnectionListener listener,
            SessionAuthenticator authenticator) {
        disconnectFromHost();

        sConnectionListener = listener;
        sAuthenticator = authenticator;
        nativeConnect(username, authToken, hostJid, hostId, hostPubkey,
                sAuthenticator.getPairingId(hostId), sAuthenticator.getPairingSecret(hostId),
                sCapabilityManager.getLocalCapabilities());
        sConnected = true;
    }

    /** Performs the native portion of the connection. */
    private static native void nativeConnect(String username, String authToken, String hostJid,
            String hostId, String hostPubkey, String pairId, String pairSecret,
            String capabilities);

    /** Severs the connection and cleans up. Called on the UI thread. */
    public static void disconnectFromHost() {
        if (!sConnected) {
            return;
        }

        sConnectionListener.onConnectionState(ConnectionListener.State.CLOSED,
                ConnectionListener.Error.OK);

        disconnectFromHostWithoutNotification();
    }

    /** Same as disconnectFromHost() but without notifying the ConnectionListener. */
    private static void disconnectFromHostWithoutNotification() {
        if (!sConnected) {
            return;
        }

        nativeDisconnect();
        sConnectionListener = null;
        sConnected = false;

        // Drop the reference to free the Bitmap for GC.
        synchronized (sFrameLock) {
            sFrameBitmap = null;
        }
    }

    /** Performs the native portion of the cleanup. */
    private static native void nativeDisconnect();

    /** Called by native code whenever the connection status changes. Called on the UI thread. */
    @CalledByNative
    private static void onConnectionState(int stateCode, int errorCode) {
        ConnectionListener.State state = ConnectionListener.State.fromValue(stateCode);
        ConnectionListener.Error error = ConnectionListener.Error.fromValue(errorCode);
        sConnectionListener.onConnectionState(state, error);
        if (state == ConnectionListener.State.FAILED || state == ConnectionListener.State.CLOSED) {
            // Disconnect from the host here, otherwise the next time connectToHost() is called,
            // it will try to disconnect, triggering an incorrect status notification.
            disconnectFromHostWithoutNotification();
        }
    }

    /** Prompts the user to enter a PIN. Called on the UI thread. */
    @CalledByNative
    private static void displayAuthenticationPrompt(boolean pairingSupported) {
        sAuthenticator.displayAuthenticationPrompt(pairingSupported);
    }

    /**
     * Performs the native response to the user's PIN.
     * @param pin The entered PIN.
     * @param createPair Whether to create a new pairing for this client.
     * @param deviceName The device name to appear in the pairing registry. Only used if createPair
     *                   is true.
     */
    public static void handleAuthenticationResponse(String pin, boolean createPair,
            String deviceName) {
        assert sConnected;
        nativeAuthenticationResponse(pin, createPair, deviceName);
    }

    /** Native implementation of handleAuthenticationResponse(). */
    private static native void nativeAuthenticationResponse(String pin, boolean createPair,
            String deviceName);

    /** Saves newly-received pairing credentials to permanent storage. Called on the UI thread. */
    @CalledByNative
    private static void commitPairingCredentials(String host, String id, String secret) {
        sAuthenticator.commitPairingCredentials(host, id, secret);
    }

    /**
     * Moves the mouse cursor, possibly while clicking the specified (nonnegative) button. Called
     * on the UI thread.
     */
    public static void sendMouseEvent(int x, int y, int whichButton, boolean buttonDown) {
        if (!sConnected) {
            return;
        }

        nativeSendMouseEvent(x, y, whichButton, buttonDown);
    }

    /** Passes mouse information to the native handling code. */
    private static native void nativeSendMouseEvent(int x, int y, int whichButton,
            boolean buttonDown);

    /** Injects a mouse-wheel event with delta values. Called on the UI thread. */
    public static void sendMouseWheelEvent(int deltaX, int deltaY) {
        if (!sConnected) {
            return;
        }

        nativeSendMouseWheelEvent(deltaX, deltaY);
    }

    /** Passes mouse-wheel information to the native handling code. */
    private static native void nativeSendMouseWheelEvent(int deltaX, int deltaY);

    /**
     * Presses or releases the specified (nonnegative) key. Called on the UI thread. If scanCode
     * is not zero then keyCode is ignored.
     */
    public static boolean sendKeyEvent(int scanCode, int keyCode, boolean keyDown) {
        if (!sConnected) {
            return false;
        }

        return nativeSendKeyEvent(scanCode, keyCode, keyDown);
    }

    /**
     * Passes key press information to the native handling code.
     */
    private static native boolean nativeSendKeyEvent(int scanCode, int keyCode, boolean keyDown);

    /** Sends TextEvent to the host. Called on the UI thread. */
    public static void sendTextEvent(String text) {
        if (!sConnected) {
            return;
        }

        nativeSendTextEvent(text);
    }

    /** Passes text event information to the native handling code. */
    private static native void nativeSendTextEvent(String text);

    /**
     * Enables or disables the video channel. Called on the UI thread in response to Activity
     * lifecycle events.
     */
    public static void enableVideoChannel(boolean enable) {
        if (!sConnected) {
            return;
        }

        nativeEnableVideoChannel(enable);
    }

    /** Native implementation of enableVideoChannel() */
    private static native void nativeEnableVideoChannel(boolean enable);

    /**
     * Sets the redraw callback to the provided functor. Provide a value of null whenever the
     * window is no longer visible so that we don't continue to draw onto it. Called on the UI
     * thread.
     */
    public static void provideRedrawCallback(Runnable redrawCallback) {
        sRedrawCallback = redrawCallback;
    }

    /** Forces the native graphics thread to redraw to the canvas. Called on the UI thread. */
    public static boolean redrawGraphics() {
        if (!sConnected || sRedrawCallback == null) return false;

        nativeScheduleRedraw();
        return true;
    }

    /** Schedules a redraw on the native graphics thread. */
    private static native void nativeScheduleRedraw();

    /**
     * Performs the redrawing callback. This is a no-op if the window isn't visible. Called on the
     * graphics thread.
     */
    @CalledByNative
    private static void redrawGraphicsInternal() {
        Runnable callback = sRedrawCallback;
        if (callback != null) {
            callback.run();
        }
    }

    /**
     * Returns a bitmap of the latest video frame. Called on the native graphics thread when
     * DesktopView is repainted.
     */
    public static Bitmap getVideoFrame() {
        if (Looper.myLooper() == Looper.getMainLooper()) {
            Log.w("jniiface", "Canvas being redrawn on UI thread");
        }

        synchronized (sFrameLock) {
            return sFrameBitmap;
        }
    }

    /**
     * Sets a new video frame. Called on the native graphics thread when a new frame is allocated.
     */
    @CalledByNative
    private static void setVideoFrame(Bitmap bitmap) {
        if (Looper.myLooper() == Looper.getMainLooper()) {
            Log.w("jniiface", "Video frame updated on UI thread");
        }

        synchronized (sFrameLock) {
            sFrameBitmap = bitmap;
        }
    }

    /**
     * Creates a new Bitmap to hold video frame pixels. Called by native code which stores a global
     * reference to the Bitmap and writes the decoded frame pixels to it.
     */
    @CalledByNative
    private static Bitmap newBitmap(int width, int height) {
        return Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    }

    /**
     * Updates the cursor shape. This is called on the graphics thread when receiving a new cursor
     * shape from the host.
     */
    @CalledByNative
    public static void updateCursorShape(int width, int height, int hotspotX, int hotspotY,
                                         ByteBuffer buffer) {
        sCursorHotspot = new Point(hotspotX, hotspotY);

        int[] data = new int[width * height];
        buffer.order(ByteOrder.LITTLE_ENDIAN);
        buffer.asIntBuffer().get(data, 0, data.length);
        sCursorBitmap = Bitmap.createBitmap(data, width, height, Bitmap.Config.ARGB_8888);
    }

    /** Position of cursor hotspot within cursor image. Called on the graphics thread. */
    public static Point getCursorHotspot() {
        return sCursorHotspot;
    }

    /** Returns the current cursor shape. Called on the graphics thread. */
    public static Bitmap getCursorBitmap() {
        return sCursorBitmap;
    }

    //
    // Third Party Authentication
    //

    /** Pops up a third party login page to fetch the token required for authentication. */
    @CalledByNative
    public static void fetchThirdPartyToken(String tokenUrl, String clientId, String scope) {
        sAuthenticator.fetchThirdPartyToken(tokenUrl, clientId, scope);
    }

    /**
     * Notify the native code to continue authentication with the |token| and the |sharedSecret|.
     */
    public static void onThirdPartyTokenFetched(String token, String sharedSecret) {
        if (!sConnected) {
            return;
        }

        nativeOnThirdPartyTokenFetched(token, sharedSecret);
    }

    /** Passes authentication data to the native handling code. */
    private static native void nativeOnThirdPartyTokenFetched(String token, String sharedSecret);

    //
    // Host and Client Capabilities
    //

    /** Set the list of negotiated capabilities between host and client. Called on the UI thread. */
    @CalledByNative
    public static void setCapabilities(String capabilities) {
        sCapabilityManager.setNegotiatedCapabilities(capabilities);
    }

    //
    // Extension Message Handling
    //

    /** Passes on the deconstructed ExtensionMessage to the app. Called on the UI thread. */
    @CalledByNative
    public static void handleExtensionMessage(String type, String data) {
        sCapabilityManager.onExtensionMessage(type, data);
    }

    /** Sends an extension message to the Chromoting host. Called on the UI thread. */
    public static void sendExtensionMessage(String type, String data) {
        if (!sConnected) {
            return;
        }

        nativeSendExtensionMessage(type, data);
    }

    private static native void nativeSendExtensionMessage(String type, String data);
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>ChecksumFileModule</title>
<meta name="date" content="2014-10-29">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

modules

Class ChecksumFileModule

java.lang.Object

modules.AbstractModule

modules.AbstractFileDependentModule

modules.ChecksumFileModule

public class ChecksumFileModule
extends AbstractFileDependentModule

Field Summary

Fields inherited from class modules.AbstractModule

config, moduleName, version

Constructor Summary

Constructors

Constructor and Description

ChecksumFileModule()

Method Summary

All Methods Static Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

static byte[]
createChecksum(java.nio.file.Path filename,
              java.lang.String type)

ExtractionResult
extractInformation(java.nio.file.Path path)

static java.lang.String[]
getCryptoImpls(java.lang.String serviceType)

static java.lang.String
getMD5Checksum(java.nio.file.Path filename,
              java.lang.String type)

java.lang.String
getModuleDescription()

static void
main(java.lang.String[] args)

void
setModuleName()

By implementing this abstract method the name of the module is specified.

void
setVersion()

Methods inherited from class modules.AbstractFileDependentModule

extractFileDependentInformation

Methods inherited from class modules.AbstractModule

getConfig, getHash, isSelected, setConfig, setSelected, supportsThisOS, toString

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

ChecksumFileModule

public ChecksumFileModule()

Method Detail

setModuleName

public void setModuleName()

Description copied from class: AbstractModule

By implementing this abstract method the name of the module is specified.
 Write a method body like {this.moduleName = "NAME";}.

Specified by:

setModuleName in class AbstractModule

extractInformation

public ExtractionResult extractInformation(java.nio.file.Path path)

Specified by:

extractInformation in class AbstractFileDependentModule

setVersion

public void setVersion()

Specified by:

setVersion in class AbstractModule

createChecksum

public static byte[] createChecksum(java.nio.file.Path filename,
                                    java.lang.String type)
                             throws java.lang.Exception

Throws:

java.lang.Exception

getMD5Checksum

public static java.lang.String getMD5Checksum(java.nio.file.Path filename,
                                              java.lang.String type)
                                       throws java.lang.Exception

Throws:

java.lang.Exception

getModuleDescription

public java.lang.String getModuleDescription()

Specified by:

getModuleDescription in class AbstractModule

getCryptoImpls

public static java.lang.String[] getCryptoImpls(java.lang.String serviceType)

main

public static void main(java.lang.String[] args)

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

redpajama_set_name: RedPajamaGithub


text:
/**
 * @file
 * Apple HTTP Live Streaming Protocol Handler
 * http://tools.ietf.org/html/draft-pantos-http-live-streaming
 */

#include "libavutil/avstring.h"
#include "libavutil/time.h"
#include "avformat.h"
#include "internal.h"
#include "url.h"
#include "version.h"

/*
 * An apple http stream consists of a playlist with media segment files,
 * played sequentially. There may be several playlists with the same
 * video content, in different bandwidth variants, that are played in
 * parallel (preferably only one bandwidth variant at a time). In this case,
 * the user supplied the url to a main playlist that only lists the variant
 * playlists.
 *
 * If the main playlist doesn't point at any variants, we still create
 * one anonymous toplevel variant for this, to maintain the structure.
 */

struct segment {
    int64_t duration;
    char url[MAX_URL_SIZE];
};

struct variant {
    int bandwidth;
    char url[MAX_URL_SIZE];
};

typedef struct HLSContext {
    char playlisturl[MAX_URL_SIZE];
    int64_t target_duration;
    int start_seq_no;
    int finished;
    int n_segments;
    struct segment **segments;
    int n_variants;
    struct variant **variants;
    int cur_seq_no;
    URLContext *seg_hd;
    int64_t last_load_time;
} HLSContext;

static int read_chomp_line(AVIOContext *s, char *buf, int maxlen)
{
    int len = ff_get_line(s, buf, maxlen);
    while (len > 0 && av_isspace(buf[len - 1]))
        buf[--len] = '\0';
    return len;
}

static void free_segment_list(HLSContext *s)
{
    int i;
    for (i = 0; i < s->n_segments; i++)
        av_free(s->segments[i]);
    av_freep(&s->segments);
    s->n_segments = 0;
}

static void free_variant_list(HLSContext *s)
{
    int i;
    for (i = 0; i < s->n_variants; i++)
        av_free(s->variants[i]);
    av_freep(&s->variants);
    s->n_variants = 0;
}

struct variant_info {
    char bandwidth[20];
};

static void handle_variant_args(struct variant_info *info, const char *key,
                                int key_len, char **dest, int *dest_len)
{
    if (!strncmp(key, "BANDWIDTH=", key_len)) {
        *dest     =        info->bandwidth;
        *dest_len = sizeof(info->bandwidth);
    }
}

static int parse_playlist(URLContext *h, const char *url)
{
    HLSContext *s = h->priv_data;
    AVIOContext *in;
    int ret = 0, is_segment = 0, is_variant = 0, bandwidth = 0;
    int64_t duration = 0;
    char line[1024];
    const char *ptr;

    if ((ret = avio_open2(&in, url, AVIO_FLAG_READ,
                          &h->interrupt_callback, NULL)) < 0)
        return ret;

    read_chomp_line(in, line, sizeof(line));
    if (strcmp(line, "#EXTM3U"))
        return AVERROR_INVALIDDATA;

    free_segment_list(s);
    s->finished = 0;
    while (!avio_feof(in)) {
        read_chomp_line(in, line, sizeof(line));
        if (av_strstart(line, "#EXT-X-STREAM-INF:", &ptr)) {
            struct variant_info info = {{0}};
            is_variant = 1;
            ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_variant_args,
                               &info);
            bandwidth = atoi(info.bandwidth);
        } else if (av_strstart(line, "#EXT-X-TARGETDURATION:", &ptr)) {
            s->target_duration = atoi(ptr) * AV_TIME_BASE;
        } else if (av_strstart(line, "#EXT-X-MEDIA-SEQUENCE:", &ptr)) {
            s->start_seq_no = atoi(ptr);
        } else if (av_strstart(line, "#EXT-X-ENDLIST", &ptr)) {
            s->finished = 1;
        } else if (av_strstart(line, "#EXTINF:", &ptr)) {
            is_segment = 1;
            duration = atof(ptr) * AV_TIME_BASE;
        } else if (av_strstart(line, "#", NULL)) {
            continue;
        } else if (line[0]) {
            if (is_segment) {
                struct segment *seg = av_malloc(sizeof(struct segment));
                if (!seg) {
                    ret = AVERROR(ENOMEM);
                    goto fail;
                }
                seg->duration = duration;
                ff_make_absolute_url(seg->url, sizeof(seg->url), url, line);
                dynarray_add(&s->segments, &s->n_segments, seg);
                is_segment = 0;
            } else if (is_variant) {
                struct variant *var = av_malloc(sizeof(struct variant));
                if (!var) {
                    ret = AVERROR(ENOMEM);
                    goto fail;
                }
                var->bandwidth = bandwidth;
                ff_make_absolute_url(var->url, sizeof(var->url), url, line);
                dynarray_add(&s->variants, &s->n_variants, var);
                is_variant = 0;
            }
        }
    }
    s->last_load_time = av_gettime_relative();

fail:
    avio_close(in);
    return ret;
}

static int hls_close(URLContext *h)
{
    HLSContext *s = h->priv_data;

    free_segment_list(s);
    free_variant_list(s);
    ffurl_close(s->seg_hd);
    return 0;
}

static int hls_open(URLContext *h, const char *uri, int flags)
{
    HLSContext *s = h->priv_data;
    int ret, i;
    const char *nested_url;

    if (flags & AVIO_FLAG_WRITE)
        return AVERROR(ENOSYS);

    h->is_streamed = 1;

    if (av_strstart(uri, "hls+", &nested_url)) {
        av_strlcpy(s->playlisturl, nested_url, sizeof(s->playlisturl));
    } else if (av_strstart(uri, "hls://", &nested_url)) {
        av_log(h, AV_LOG_ERROR,
               "No nested protocol specified. Specify e.g. hls+http://%s\n",
               nested_url);
        ret = AVERROR(EINVAL);
        goto fail;
    } else {
        av_log(h, AV_LOG_ERROR, "Unsupported url %s\n", uri);
        ret = AVERROR(EINVAL);
        goto fail;
    }
    av_log(h, AV_LOG_WARNING,
           "Using the hls protocol is discouraged, please try using the "
           "hls demuxer instead. The hls demuxer should be more complete "
           "and work as well as the protocol implementation. (If not, "
           "please report it.) To use the demuxer, simply use %s as url.\n",
           s->playlisturl);

    if ((ret = parse_playlist(h, s->playlisturl)) < 0)
        goto fail;

    if (s->n_segments == 0 && s->n_variants > 0) {
        int max_bandwidth = 0, maxvar = -1;
        for (i = 0; i < s->n_variants; i++) {
            if (s->variants[i]->bandwidth > max_bandwidth || i == 0) {
                max_bandwidth = s->variants[i]->bandwidth;
                maxvar = i;
            }
        }
        av_strlcpy(s->playlisturl, s->variants[maxvar]->url,
                   sizeof(s->playlisturl));
        if ((ret = parse_playlist(h, s->playlisturl)) < 0)
            goto fail;
    }

    if (s->n_segments == 0) {
        av_log(h, AV_LOG_WARNING, "Empty playlist\n");
        ret = AVERROR(EIO);
        goto fail;
    }
    s->cur_seq_no = s->start_seq_no;
    if (!s->finished && s->n_segments >= 3)
        s->cur_seq_no = s->start_seq_no + s->n_segments - 3;

    return 0;

fail:
    hls_close(h);
    return ret;
}

static int hls_read(URLContext *h, uint8_t *buf, int size)
{
    HLSContext *s = h->priv_data;
    const char *url;
    int ret;
    int64_t reload_interval;

start:
    if (s->seg_hd) {
        ret = ffurl_read(s->seg_hd, buf, size);
        if (ret > 0)
            return ret;
    }
    if (s->seg_hd) {
        ffurl_close(s->seg_hd);
        s->seg_hd = NULL;
        s->cur_seq_no++;
    }
    reload_interval = s->n_segments > 0 ?
                      s->segments[s->n_segments - 1]->duration :
                      s->target_duration;
retry:
    if (!s->finished) {
        int64_t now = av_gettime_relative();
        if (now - s->last_load_time >= reload_interval) {
            if ((ret = parse_playlist(h, s->playlisturl)) < 0)
                return ret;
            /* If we need to reload the playlist again below (if
             * there's still no more segments), switch to a reload
             * interval of half the target duration. */
            reload_interval = s->target_duration / 2;
        }
    }
    if (s->cur_seq_no < s->start_seq_no) {
        av_log(h, AV_LOG_WARNING,
               "skipping %d segments ahead, expired from playlist\n",
               s->start_seq_no - s->cur_seq_no);
        s->cur_seq_no = s->start_seq_no;
    }
    if (s->cur_seq_no - s->start_seq_no >= s->n_segments) {
        if (s->finished)
            return AVERROR_EOF;
        while (av_gettime_relative() - s->last_load_time < reload_interval) {
            if (ff_check_interrupt(&h->interrupt_callback))
                return AVERROR_EXIT;
            av_usleep(100*1000);
        }
        goto retry;
    }
    url = s->segments[s->cur_seq_no - s->start_seq_no]->url,
    av_log(h, AV_LOG_DEBUG, "opening %s\n", url);
    ret = ffurl_open(&s->seg_hd, url, AVIO_FLAG_READ,
                     &h->interrupt_callback, NULL);
    if (ret < 0) {
        if (ff_check_interrupt(&h->interrupt_callback))
            return AVERROR_EXIT;
        av_log(h, AV_LOG_WARNING, "Unable to open %s\n", url);
        s->cur_seq_no++;
        goto retry;
    }
    goto start;
}

URLProtocol ff_hls_protocol = {
    .name           = "hls",
    .url_open       = hls_open,
    .url_read       = hls_read,
    .url_close      = hls_close,
    .flags          = URL_PROTOCOL_FLAG_NESTED_SCHEME,
    .priv_data_size = sizeof(HLSContext),
};


text:
package org.zstack.network.l2.vxlan.vxlanNetworkPool;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.zstack.core.cloudbus.CloudBus;
import org.zstack.core.db.DatabaseFacade;
import org.zstack.header.Component;
import org.zstack.header.apimediator.ApiMessageInterceptionException;
import org.zstack.header.apimediator.GlobalApiMessageInterceptor;
import org.zstack.header.message.APIMessage;
import org.zstack.header.network.l2.*;
import org.zstack.header.network.l3.APICreateL3NetworkMsg;
import org.zstack.identity.AccountManager;
import org.zstack.query.QueryFacade;
import org.zstack.utils.Utils;
import org.zstack.utils.gson.JSONObjectUtil;
import org.zstack.utils.logging.CLogger;

import java.util.Arrays;
import java.util.List;

/**
 * Created by weiwang on 03/03/2017.
 */
public class VxlanNetworkPoolFactory implements L2NetworkFactory, Component, GlobalApiMessageInterceptor {
    private static CLogger logger = Utils.getLogger(VxlanNetworkPoolFactory.class);
    static L2NetworkType type = new L2NetworkType(VxlanNetworkPoolConstant.VXLAN_NETWORK_POOL_TYPE);

    @Autowired
    private DatabaseFacade dbf;
    @Autowired
    private CloudBus bus;
    @Autowired
    private QueryFacade qf;
    @Autowired
    private VxlanNetworkChecker vxlanInterceptor;
    @Autowired
    private AccountManager acntMgr;

    @Override
    public L2NetworkType getType() {
        return type;
    }

    @Override
    @Transactional
    public L2NetworkInventory createL2Network(L2NetworkVO ovo, APICreateL2NetworkMsg msg) {
        VxlanNetworkPoolVO vo = new VxlanNetworkPoolVO(ovo);
        if (vo.getPhysicalInterface() == null) {
            vo.setPhysicalInterface("");
        }
        vo = dbf.persistAndRefresh(vo);
        acntMgr.createAccountResourceRef(msg.getSession().getAccountUuid(), vo.getUuid(), VxlanNetworkPoolVO.class);

        L2VxlanNetworkPoolInventory inv = L2VxlanNetworkPoolInventory.valueOf(vo);
        String info = String.format("successfully create L2VxlanNetworkPool, %s", JSONObjectUtil.toJsonString(inv));
        logger.debug(info);
        return inv;
    }

    @Override
    public L2Network getL2Network(L2NetworkVO vo) {
        return new VxlanNetworkPool(vo);
    }

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

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

    @Override
    public List<Class> getMessageClassToIntercept() {
        return Arrays.asList(APIAttachL2NetworkToClusterMsg.class, APICreateL3NetworkMsg.class);
    }

    @Override
    public APIMessage intercept(APIMessage msg) throws ApiMessageInterceptionException {
        vxlanInterceptor.intercept(msg);
        return msg;
    }

    @Override
    public InterceptorPosition getPosition() {
        return InterceptorPosition.FRONT;
    }
}


text:
namespace Microsoft.Azure.Management.DataLake.Store.Models
{
    using Microsoft.Azure;
    using Microsoft.Azure.Management;
    using Microsoft.Azure.Management.DataLake;
    using Microsoft.Azure.Management.DataLake.Store;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Converters;
    using System.Runtime;
    using System.Runtime.Serialization;

    /// <summary>
    /// Defines values for EncryptionState.
    /// </summary>
    [JsonConverter(typeof(StringEnumConverter))]
    public enum EncryptionState
    {
        [EnumMember(Value = "Enabled")]
        Enabled,
        [EnumMember(Value = "Disabled")]
        Disabled
    }
    internal static class EncryptionStateEnumExtension
    {
        internal static string ToSerializedValue(this EncryptionState? value)  =>
            value == null ? null : ((EncryptionState)value).ToSerializedValue();

        internal static string ToSerializedValue(this EncryptionState value)
        {
            switch( value )
            {
                case EncryptionState.Enabled:
                    return "Enabled";
                case EncryptionState.Disabled:
                    return "Disabled";
            }
            return null;
        }

        internal static EncryptionState? ParseEncryptionState(this string value)
        {
            switch( value )
            {
                case "Enabled":
                    return EncryptionState.Enabled;
                case "Disabled":
                    return EncryptionState.Disabled;
            }
            return null;
        }
    }
}


text:
@implementation NMSSHSession (OP)

+(NSString*)commandForOP:(OperatingSystem)op shutdownType:(ShutdownType)shutdowntype {
    switch (shutdowntype) {
        case kShutdown:
            switch (op) {
                case kMacOSX:
                    return @"osascript -e 'tell application \"System Events\" to shut down'";
                    break;
                case kLinux:
                    return @"sudo shutdown -h now";
                    break;
                case kSynology:
                    return @"poweroff";
                    break;

                default:
                    return nil;
                    break;
            }
            break;

        case kHibernate:
            switch (op) {
                case kMacOSX:
                    return @"osascript -e 'tell application \"System Events\" to sleep'";
                    break;
                case kLinux:
                    return @"sudo pm-hibernate";
                    break;

                default:
                    return nil;
                    break;
            }
            break;

        default:
            return nil;
            break;
    }

}

+(NSArray*)systemTypes {
    return [[NSArray alloc] initWithObjects:@"Mac OS X",@"Linux",@"Synology NAS", nil];
}

@end


text:
"use strict";

var fs        = require("fs");
var path      = require("path");
var Sequelize = require("sequelize");
//var GetUsers = require("./User.js")
var sequelize = new Sequelize(process.env.POSTGRESQL_LOCAL_DB, "", "", {
    host: process.env.POSTGRESQL_LOCAL_HOST,
    dialect: 'postgres',
    freezeTableName: true,
    define: {
        timestamps: false
    },
    pool: {
        max: 9,
        min: 0,
        idle: 10000
    }
});

var db = {};

fs
    .readdirSync(__dirname)
    .filter(function(file) {
        return (file.indexOf(".") !== 0) && (file !== "index.js");

    })
    .forEach(function(file) {
        var model = sequelize["import"](path.join(__dirname, file));
        db[model.name] = model;
        console.log(model);
    });

// Object.keys(db).forEach(function(modelName) {
//     if ("associate" in db[modelName]) {
//         db[modelName].associate(db);
//     }
// });
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;
//var myusers = GetUsers(sequelize, Sequelize.DataTypes);
//module.exports = {
    //db: db,
    //myusers: myusers


text:
#ifndef __Ch7_AIFlocking_h__
#define __Ch7_AIFlocking_h__

#include "Ch7_LineOfSight.h"

class Ch7_AIFlocking : public Ch7_LineOfSight
{
	public :

		SCENE_FUNC ( Ch7_AIFlocking );

	protected :

		virtual KDbool		init ( KDvoid );

		virtual KDvoid		step ( KDfloat fDelta );

		virtual KDvoid		setGameAreaSize ( KDvoid );

		virtual KDvoid		addActor ( KDvoid );

		virtual KDvoid		addEnemies ( KDvoid );

		virtual KDvoid		followActorWithEnemies ( KDvoid );

		KDvoid				processBoids ( KDvoid );

		b2Vec2				boidRule1 ( GameActor* pBoid );
		b2Vec2				boidRule2 ( GameActor* pBoid );
		b2Vec2				boidRule3 ( GameActor* pBoid );
};

#endif	// __Ch7_AIFlocking_h__


text:
/*
 * Created by IntelliJ IDEA.
 * User: yole
 * Date: 31.07.2006
 * Time: 13:24:17
 */
package com.intellij.openapi.vcs.impl;

import com.intellij.lifecycle.PeriodicalTasksCloser;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.components.ProjectComponent;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.editor.colors.EditorColorsListener;
import com.intellij.openapi.editor.colors.EditorColorsManager;
import com.intellij.openapi.editor.colors.EditorColorsScheme;
import com.intellij.openapi.editor.event.EditorFactoryAdapter;
import com.intellij.openapi.editor.event.EditorFactoryEvent;
import com.intellij.openapi.editor.event.EditorFactoryListener;
import com.intellij.openapi.editor.ex.DocumentBulkUpdateListener;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.impl.DirectoryIndex;
import com.intellij.openapi.startup.StartupManager;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vcs.*;
import com.intellij.openapi.vcs.ex.LineStatusTracker;
import com.intellij.openapi.vcs.history.VcsRevisionNumber;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileAdapter;
import com.intellij.openapi.vfs.VirtualFileEvent;
import com.intellij.openapi.vfs.VirtualFileManager;
import com.intellij.testFramework.LightVirtualFile;
import com.intellij.util.Consumer;
import com.intellij.util.concurrency.QueueProcessorRemovePartner;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.HashMap;
import com.intellij.util.messages.MessageBusConnection;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.Map;

public class LineStatusTrackerManager implements ProjectComponent, LineStatusTrackerManagerI {
  private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.vcs.impl.LineStatusTrackerManager");

  @NonNls protected static final String IGNORE_CHANGEMARKERS_KEY = "idea.ignore.changemarkers";

  @NotNull public final Object myLock = new Object();

  @NotNull private final Project myProject;
  @NotNull private final ProjectLevelVcsManager myVcsManager;
  @NotNull private final VcsBaseContentProvider myStatusProvider;
  @NotNull private final Application myApplication;
  @NotNull private final FileEditorManager myFileEditorManager;
  @NotNull private final Disposable myDisposable;

  @NotNull private final Map<Document, LineStatusTracker> myLineStatusTrackers;

  @NotNull private final QueueProcessorRemovePartner<Document, BaseRevisionLoader> myPartner;
  private long myLoadCounter;

  public static LineStatusTrackerManagerI getInstance(final Project project) {
    return PeriodicalTasksCloser.getInstance().safeGetComponent(project, LineStatusTrackerManagerI.class);
  }

  public LineStatusTrackerManager(@NotNull final Project project,
                                  @NotNull final ProjectLevelVcsManager vcsManager,
                                  @NotNull final VcsBaseContentProvider statusProvider,
                                  @NotNull final Application application,
                                  @NotNull final FileEditorManager fileEditorManager,
                                  @SuppressWarnings("UnusedParameters") DirectoryIndex makeSureIndexIsInitializedFirst) {
    myLoadCounter = 0;
    myProject = project;
    myVcsManager = vcsManager;
    myStatusProvider = statusProvider;
    myApplication = application;
    myFileEditorManager = fileEditorManager;

    myLineStatusTrackers = new HashMap<Document, LineStatusTracker>();
    myPartner = new QueueProcessorRemovePartner<Document, BaseRevisionLoader>(myProject, new Consumer<BaseRevisionLoader>() {
      @Override
      public void consume(BaseRevisionLoader baseRevisionLoader) {
        baseRevisionLoader.run();
      }
    });

    MessageBusConnection busConnection = project.getMessageBus().connect();
    busConnection.subscribe(DocumentBulkUpdateListener.TOPIC, new DocumentBulkUpdateListener.Adapter() {
      @Override
      public void updateStarted(@NotNull final Document doc) {
        final LineStatusTracker tracker = getLineStatusTracker(doc);
        if (tracker != null) tracker.startBulkUpdate();
      }

      @Override
      public void updateFinished(@NotNull final Document doc) {
        final LineStatusTracker tracker = getLineStatusTracker(doc);
        if (tracker != null) tracker.finishBulkUpdate();
      }
    });
    busConnection.subscribe(LineStatusTrackerSettingListener.TOPIC, new LineStatusTrackerSettingListener() {
      @Override
      public void settingsUpdated() {
        synchronized (myLock) {
          LineStatusTracker.Mode mode = getMode();
          for (LineStatusTracker tracker : myLineStatusTrackers.values()) {
            tracker.setMode(mode);
          }
        }
      }
    });

    myDisposable = new Disposable() {
      @Override
      public void dispose() {
        synchronized (myLock) {
          for (final LineStatusTracker tracker : myLineStatusTrackers.values()) {
            tracker.release();
          }

          myLineStatusTrackers.clear();
          myPartner.clear();
        }
      }
    };
    Disposer.register(myProject, myDisposable);
  }

  @Override
  public void projectOpened() {
    StartupManager.getInstance(myProject).registerPreStartupActivity(new Runnable() {
      @Override
      public void run() {
        final MyFileStatusListener fileStatusListener = new MyFileStatusListener();
        final EditorFactoryListener editorFactoryListener = new MyEditorFactoryListener();
        final MyVirtualFileListener virtualFileListener = new MyVirtualFileListener();
        final EditorColorsListener editorColorsListener = new MyEditorColorsListener();

        final FileStatusManager fsManager = FileStatusManager.getInstance(myProject);
        fsManager.addFileStatusListener(fileStatusListener, myDisposable);

        final EditorFactory editorFactory = EditorFactory.getInstance();
        editorFactory.addEditorFactoryListener(editorFactoryListener, myDisposable);

        final VirtualFileManager virtualFileManager = VirtualFileManager.getInstance();
        virtualFileManager.addVirtualFileListener(virtualFileListener, myDisposable);

        final EditorColorsManager editorColorsManager = EditorColorsManager.getInstance();
        editorColorsManager.addEditorColorsListener(editorColorsListener, myDisposable);
      }
    });
  }

  @Override
  public void projectClosed() {
  }

  @Override
  @NonNls
  @NotNull
  public String getComponentName() {
    return "LineStatusTrackerManager";
  }

  @Override
  public void initComponent() {
  }

  @Override
  public void disposeComponent() {
  }

  public boolean isDisabled() {
    return !myProject.isOpen() || myProject.isDisposed();
  }

  @Override
  public LineStatusTracker getLineStatusTracker(final Document document) {
    synchronized (myLock) {
      if (isDisabled()) return null;

      return myLineStatusTrackers.get(document);
    }
  }

  private void resetTrackers() {
    synchronized (myLock) {
      if (isDisabled()) return;

      if (LOG.isDebugEnabled()) {
        LOG.debug("resetTrackers");
      }

      for (LineStatusTracker tracker : ContainerUtil.newArrayList(myLineStatusTrackers.values())) {
        resetTracker(tracker.getDocument(), tracker.getVirtualFile(), tracker);
      }

      final VirtualFile[] openFiles = myFileEditorManager.getOpenFiles();
      for (final VirtualFile openFile : openFiles) {
        resetTracker(openFile, true);
      }
    }
  }

  private void resetTracker(@NotNull final VirtualFile virtualFile) {
    resetTracker(virtualFile, false);
  }

  private void resetTracker(@NotNull final VirtualFile virtualFile, boolean insertOnly) {
    final Document document = FileDocumentManager.getInstance().getCachedDocument(virtualFile);
    if (document == null) {
      if (LOG.isDebugEnabled()) {
        LOG.debug("resetTracker: no cached document for " + virtualFile.getPath());
      }
      return;
    }

    synchronized (myLock) {
      if (isDisabled()) return;

      final LineStatusTracker tracker = myLineStatusTrackers.get(document);
      if (insertOnly && tracker != null) return;
      resetTracker(document, virtualFile, tracker);
    }
  }

  private void resetTracker(@NotNull Document document, @NotNull VirtualFile virtualFile, @Nullable LineStatusTracker tracker) {
    final boolean editorOpened = myFileEditorManager.isFileOpen(virtualFile);
    final boolean shouldBeInstalled = editorOpened && shouldBeInstalled(virtualFile);

    if (LOG.isDebugEnabled()) {
      LOG.debug("resetTracker: shouldBeInstalled - " + shouldBeInstalled + ", tracker - " + (tracker == null ? "null" : "found"));
    }

    if (tracker != null && shouldBeInstalled) {
      refreshTracker(tracker);
    }
    else if (tracker != null) {
      releaseTracker(document);
    }
    else if (shouldBeInstalled) {
      installTracker(virtualFile, document);
    }
  }

  private boolean shouldBeInstalled(@Nullable final VirtualFile virtualFile) {
    if (isDisabled()) return false;

    if (virtualFile == null || virtualFile instanceof LightVirtualFile) return false;
    if (!virtualFile.isInLocalFileSystem()) return false;
    final FileStatusManager statusManager = FileStatusManager.getInstance(myProject);
    if (statusManager == null) return false;
    final AbstractVcs activeVcs = myVcsManager.getVcsFor(virtualFile);
    if (activeVcs == null) {
      if (LOG.isDebugEnabled()) {
        LOG.debug("shouldBeInstalled: for file " + virtualFile.getPath() + " failed: no active VCS");
      }
      return false;
    }
    final FileStatus status = statusManager.getStatus(virtualFile);
    if (status == FileStatus.NOT_CHANGED || status == FileStatus.ADDED || status == FileStatus.UNKNOWN || status == FileStatus.IGNORED) {
      if (LOG.isDebugEnabled()) {
        LOG.debug("shouldBeInstalled: for file " + virtualFile.getPath() + " skipped: status=" + status);
      }
      return false;
    }
    return true;
  }

  private void refreshTracker(@NotNull LineStatusTracker tracker) {
    synchronized (myLock) {
      if (isDisabled()) return;

      startAlarm(tracker.getDocument(), tracker.getVirtualFile());
    }
  }

  private void releaseTracker(@NotNull final Document document) {
    synchronized (myLock) {
      if (isDisabled()) return;

      myPartner.remove(document);
      final LineStatusTracker tracker = myLineStatusTrackers.remove(document);
      if (tracker != null) {
        tracker.release();
      }
    }
  }

  private void installTracker(@NotNull final VirtualFile virtualFile, @NotNull final Document document) {
    synchronized (myLock) {
      if (isDisabled()) return;

      if (myLineStatusTrackers.containsKey(document)) return;
      assert !myPartner.containsKey(document);

      final LineStatusTracker tracker = LineStatusTracker.createOn(virtualFile, document, myProject, getMode());
      myLineStatusTrackers.put(document, tracker);

      startAlarm(document, virtualFile);
    }
  }

  @NotNull
  private static LineStatusTracker.Mode getMode() {
    VcsApplicationSettings vcsApplicationSettings = VcsApplicationSettings.getInstance();
    if (!vcsApplicationSettings.SHOW_LST_GUTTER_MARKERS) return LineStatusTracker.Mode.SILENT;
    return vcsApplicationSettings.SHOW_WHITESPACES_IN_LST ? LineStatusTracker.Mode.SMART : LineStatusTracker.Mode.DEFAULT;
  }

  private void startAlarm(@NotNull final Document document, @NotNull final VirtualFile virtualFile) {
    synchronized (myLock) {
      myPartner.add(document, new BaseRevisionLoader(document, virtualFile));
    }
  }

  private class BaseRevisionLoader implements Runnable {
    @NotNull private final VirtualFile myVirtualFile;
    @NotNull private final Document myDocument;

    private BaseRevisionLoader(@NotNull final Document document, @NotNull final VirtualFile virtualFile) {
      myDocument = document;
      myVirtualFile = virtualFile;
    }

    @Override
    public void run() {
      if (isDisabled()) return;

      if (!myVirtualFile.isValid()) {
        if (LOG.isDebugEnabled()) {
          LOG.debug("BaseRevisionLoader: for file " + myVirtualFile.getPath() + " failed: virtual file not valid");
        }
        reportTrackerBaseLoadFailed();
        return;
      }

      final Pair<VcsRevisionNumber, String> baseRevision = myStatusProvider.getBaseRevision(myVirtualFile);
      if (baseRevision == null) {
        if (LOG.isDebugEnabled()) {
          LOG.debug("BaseRevisionLoader: for file " + myVirtualFile.getPath() + " failed: null returned for base revision");
        }
        reportTrackerBaseLoadFailed();
        return;
      }

      // loads are sequential (in single threaded QueueProcessor);
      // so myLoadCounter can't take less value for greater base revision -> the only thing we want from it
      final LineStatusTracker.RevisionPack revisionPack = new LineStatusTracker.RevisionPack(myLoadCounter, baseRevision.first);
      myLoadCounter++;

      final String converted = StringUtil.convertLineSeparators(baseRevision.second);
      final Runnable runnable = new Runnable() {
        @Override
        public void run() {
          synchronized (myLock) {
            if (LOG.isDebugEnabled()) {
              LOG.debug("BaseRevisionLoader: initializing tracker for file " + myVirtualFile.getPath());
            }
            final LineStatusTracker tracker = myLineStatusTrackers.get(myDocument);
            if (tracker != null) {
              tracker.initialize(converted, revisionPack);
            }
          }
        }
      };
      nonModalAliveInvokeLater(runnable);
    }

    private void nonModalAliveInvokeLater(@NotNull Runnable runnable) {
      myApplication.invokeLater(runnable, ModalityState.NON_MODAL, new Condition() {
        @Override
        public boolean value(final Object ignore) {
          return isDisabled();
        }
      });
    }

    private void reportTrackerBaseLoadFailed() {
      synchronized (myLock) {
        releaseTracker(myDocument);
      }
    }
  }

  private class MyFileStatusListener implements FileStatusListener {
    @Override
    public void fileStatusesChanged() {
      resetTrackers();
    }

    @Override
    public void fileStatusChanged(@NotNull VirtualFile virtualFile) {
      resetTracker(virtualFile);
    }
  }

  private class MyEditorFactoryListener extends EditorFactoryAdapter {
    @Override
    public void editorCreated(@NotNull EditorFactoryEvent event) {
      // note that in case of lazy loading of configurables, this event can happen
      // outside of EDT, so the EDT check mustn't be done here
      Editor editor = event.getEditor();
      if (editor.getProject() != null && editor.getProject() != myProject) return;
      final Document document = editor.getDocument();
      final VirtualFile virtualFile = FileDocumentManager.getInstance().getFile(document);
      if (virtualFile == null) return;
      if (shouldBeInstalled(virtualFile)) {
        installTracker(virtualFile, document);
      }
    }

    @Override
    public void editorReleased(@NotNull EditorFactoryEvent event) {
      final Editor editor = event.getEditor();
      if (editor.getProject() != null && editor.getProject() != myProject) return;
      final Document doc = editor.getDocument();
      final Editor[] editors = event.getFactory().getEditors(doc, myProject);
      if (editors.length == 0) {
        releaseTracker(doc);
      }
    }
  }

  private class MyVirtualFileListener extends VirtualFileAdapter {
    @Override
    public void beforeContentsChange(@NotNull VirtualFileEvent event) {
      if (event.isFromRefresh()) {
        resetTracker(event.getFile());
      }
    }
  }

  private class MyEditorColorsListener implements EditorColorsListener {
    @Override
    public void globalSchemeChange(EditorColorsScheme scheme) {
      resetTrackers();
    }
  }
}


text:
using Xunit;

namespace System.Collections.Tests
{
    public class ArrayList_CapacityTests
    {
        #region "Test Data - Keep the data close to tests so it can vary independently from other tests"

        static string[] strHeroes =
            {
                "Aquaman",
                "Atom",
                "Batman",
                "Black Canary",
                "Captain America",
                "Captain Atom",
                "Catwoman",
                "Cyborg",
                "Flash",
                "Green Arrow",
                "Green Lantern",
                "Hawkman",
                "Huntress",
                "Ironman",
                "Nightwing",
                "Robin",
                "SpiderMan",
                "Steel",
                "Superman",
                "Thor",
                "Wildcat",
                "Wonder Woman",
            };

        #endregion

        [Fact]
        public void TestGetBasic()
        {
            // Construct ArrayList.
            ArrayList arrList = new ArrayList((ICollection)strHeroes);
            Assert.NotNull(arrList);

            // []  Obtain list capacity.
            Assert.True(arrList.Capacity >= arrList.Count);
        }

        [Fact]
        public void TestSetBasic()
        {
            ArrayList arrList = null;

            //
            // Construct array list.
            //
            arrList = new ArrayList((ICollection)strHeroes);

            //
            // []  Set and verify list capacity.
            //
            int nCapacity = 2 * arrList.Capacity;
            arrList.Capacity = nCapacity;
            Assert.Equal(nCapacity, arrList.Capacity);

            //
            // []  Bogus negative argument.
            //
            Assert.Throws<ArgumentOutOfRangeException>(() => { arrList.Capacity = -1000; });

            //
            // []  Bogus super large capacity.
            //
            Assert.Throws<OutOfMemoryException>(() => { arrList.Capacity = Int32.MaxValue; });

            //[] Team Review feedback - set capacity to a value less than the count
            arrList = new ArrayList();
            for (int i = 0; i < 10; i++)
                arrList.Add(i);

            Assert.Throws<ArgumentOutOfRangeException>(() => { arrList.Capacity = arrList.Count - 1; });

            //
            // []  Set Capacity equal to 0
            //
            arrList = new ArrayList(1);

            arrList.Capacity = 0;
            Assert.Equal(4, arrList.Capacity);

            for (int i = 0; i < 32; i++)
                arrList.Add(-i);

            for (int i = 0; i < 32; i++)
                Assert.Equal(-i, (int)arrList[i]);
        }
    }
}


text:
/**
 * game-interface
 * audio-resource-test
 */
test.runnerAudioResource = function () {
  test.heading('AudioResource Class', function () {
    test.paragraph('');

    test.heading('CONSTRUCTOR', function () {
      test.example('objects created should be an instance of AudioResource', true, function () {
        return new AudioResource('!') instanceof AudioResource;
      });
      test.example('should make sure new operator used', Error('new operator required'), function () {
        AudioResource();
      });
      test.example('resource name required', Error('error creating AudioResource: resource string required'), function () {
        new AudioResource();
      });
    });
    test.heading('PROPERTIES', function () {
      test.heading('resourceName', function () {
        test.paragraph('resource file name');
        test.example('returns value set in constructer', 'picture', function () {
          return new AudioResource('picture').resourceName;
        });
      });
    });
    test.heading('METHODS', function () {
      test.heading('load', function () {
        test.paragraph('Load resource and invoke callback when done');
        test.example('callback function required', Error('callback required'), function () {
          new AudioResource('me').load();
        });
        test.example('returns error when resource not found', test.asyncResponse(Error('audio resource "me" not found')), function (testNode, returnResponse) {
          new AudioResource('me').load(function(err){
            returnResponse(testNode, err);
          });
        });
      });
      test.heading('play', function () {
        test.paragraph('bool indicates if resource is loaded');
        test.example('resource must be loaded', Error('audio resource "me" not loaded'), function () {
          new AudioResource('me').play();
        });
      });
    });
  });
};


text:
package com.adms.cs.dao.impl;

import org.springframework.stereotype.Repository;

import com.adms.common.dao.generic.impl.GenericDaoHibernate;
import com.adms.cs.dao.CategoryDataDao;
import com.adms.entity.cs.CategoryData;

@Repository("categoryDataDao")
public class CategoryDataDaoImpl extends GenericDaoHibernate<CategoryData, Long> implements CategoryDataDao {

	public CategoryDataDaoImpl() {
		super(CategoryData.class);
	}
}


text:
<?php

namespace alsaqqa\metronic\widgets;

use Yii;

/**
 * DetailView displays the detail of a single data [[model]].
 *
 * DetailView is best used for displaying a model in a regular format (e.g. each model attribute
 * is displayed as a row in a table.) The model can be either an instance of [[Model]]
 * or an associative array.
 *
 * DetailView uses the [[attributes]] property to determines which model attributes
 * should be displayed and how they should be formatted.
 *
 * A typical usage of DetailView is as follows:
 *
 * ~~~
 * echo DetailView::widget([
 *     'model' => $model,
 *     'attributes' => [
 *         'title',             // title attribute (in plain text)
 *         'description:html',  // description attribute in HTML
 *         [                    // the owner name of the model
 *             'label' => 'Owner',
 *             'value' => $model->owner->name,
 *         ],
 *     ],
 * ]);
 * ~~~
 */
class DetailView extends \yii\widgets\DetailView
{
    /**
     * @var string|callback the template used to render a single attribute. If a string, the token `{label}`
     * and `{value}` will be replaced with the label and the value of the corresponding attribute.
     * If a callback (e.g. an anonymous function), the signature must be as follows:
     *
     * ~~~
     * function ($attribute, $index, $widget)
     * ~~~
     *
     * where `$attribute` refer to the specification of the attribute being rendered, `$index` is the zero-based
     * index of the attribute in the [[attributes]] array, and `$widget` refers to this widget instance.
     */
    public $template = '

{label}

{value}

';
}