text:
package com.microsoft.azure.management.resources;

import com.microsoft.azure.management.apigeneration.Fluent;
import com.microsoft.azure.management.resources.fluentcore.arm.collection.SupportsGettingById;
import com.microsoft.azure.management.resources.fluentcore.arm.collection.SupportsListingByGroup;
import com.microsoft.azure.management.resources.fluentcore.arm.collection.SupportsListingInGroupByTag;
import com.microsoft.azure.management.resources.fluentcore.arm.models.HasManager;
import com.microsoft.azure.management.resources.fluentcore.collection.SupportsCreating;
import com.microsoft.azure.management.resources.fluentcore.collection.SupportsDeletingById;
import com.microsoft.azure.management.resources.fluentcore.collection.SupportsListing;
import com.microsoft.azure.management.resources.implementation.ResourceManager;

import java.util.List;

/**
 * Entry point to generic resources management API.
 */
@Fluent
public interface GenericResources extends
        SupportsListing<GenericResource>,
        SupportsListingByGroup<GenericResource>,
        SupportsListingInGroupByTag<GenericResource>,
        SupportsGettingById<GenericResource>,
        SupportsCreating<GenericResource.DefinitionStages.Blank>,
        SupportsDeletingById,
        HasManager<ResourceManager> {
    /**
     * Checks if a resource exists in a resource group.
     *
     * @param resourceGroupName the resource group's name
     * @param resourceProviderNamespace the resource provider's namespace
     * @param parentResourcePath the parent's resource path
     * @param resourceType the type of the resource
     * @param resourceName the name of the resource
     * @param apiVersion the API version
     * @return true if the resource exists; false otherwise
     */
    boolean checkExistence(
            String resourceGroupName,
            String resourceProviderNamespace,
            String parentResourcePath,
            String resourceType,
            String resourceName,
            String apiVersion);

    /**
     * Checks if a resource exists.
     *
     * @param id the ID of the resource.
     * @return true if the resource exists; false otherwise
     */
    boolean checkExistenceById(String id);

    /**
     * Returns a resource belonging to a resource group.
     *
     * @param resourceGroupName The name of the resource group. The name is case insensitive.
     * @param resourceProviderNamespace Resource identity.
     * @param parentResourcePath Resource identity.
     * @param resourceType Resource identity.
     * @param resourceName Resource identity.
     * @param apiVersion the String value
     * @return the generic resource
     */
    GenericResource get(
            String resourceGroupName,
            String resourceProviderNamespace,
            String parentResourcePath,
            String resourceType,
            String resourceName,
            String apiVersion);

    /**
     * Returns a resource belonging to a resource group.
     * @param resourceGroupName the resource group name
     * @param providerNamespace the provider namespace
     * @param resourceType the resource type
     * @param resourceName the name of the resource
     * @return the generic resource
     */
    GenericResource get(
            String resourceGroupName,
            String providerNamespace,
            String resourceType,
            String resourceName);

    /**
     * Move resources from one resource group to another.
     *
     * @param sourceResourceGroupName Source resource group name
     * @param targetResourceGroup target resource group, can be in a different subscription
     * @param resources the list of IDs of the resources to move
     */
    void moveResources(String sourceResourceGroupName, ResourceGroup targetResourceGroup, List<String> resources);

    /**
     * Delete resource and all of its child resources.
     *
     * @param resourceGroupName The name of the resource group. The name is case insensitive.
     * @param resourceProviderNamespace Resource identity.
     * @param parentResourcePath Resource identity.
     * @param resourceType Resource identity.
     * @param resourceName Resource identity.
     * @param apiVersion the String value
     */
    void delete(String resourceGroupName, String resourceProviderNamespace, String parentResourcePath, String resourceType, String resourceName, String apiVersion);
}


text:
package io.druid.granularity;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Preconditions;
import com.google.common.primitives.Longs;
import org.joda.time.DateTime;

import java.nio.ByteBuffer;

public class DurationGranularity extends BaseQueryGranularity
{
  private final long length;
  private final long origin;

  @JsonCreator
  public DurationGranularity(
    @JsonProperty("duration") long duration,
    @JsonProperty("origin") DateTime origin
  )
  {
    this(duration, origin == null ? 0 : origin.getMillis());
  }

  public DurationGranularity(long millis, long origin)
  {
    Preconditions.checkArgument(millis > 0, "duration should be greater than 0!");
    this.length = millis;
    this.origin = origin % length;
  }

  @JsonProperty("duration")
  public long getDuration()
  {
    return length;
  }

  @JsonProperty("origin")
  public DateTime getOrigin()
  {
    return new DateTime(origin);
  }

  public long getOriginMillis()
  {
    return origin;
  }

  @Override
  public long next(long t)
  {
    return t + getDurationMillis();
  }

  @Override
  public long truncate(final long t)
  {
    final long duration = getDurationMillis();
    long offset = t % duration - origin % duration;
    if(offset < 0) {
      offset += duration;
    }
    return t - offset;
  }

  @Override
  public byte[] cacheKey()
  {
    return ByteBuffer.allocate(2 * Longs.BYTES).putLong(length).putLong(origin).array();
  }

  public long getDurationMillis()
  {
    return length;
  }

  @Override
  public boolean equals(Object o)
  {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }

    DurationGranularity that = (DurationGranularity) o;

    if (length != that.length) {
      return false;
    }
    if (origin != that.origin) {
      return false;
    }

    return true;
  }

  @Override
  public int hashCode()
  {
    int result = (int) (length ^ (length >>> 32));
    result = 31 * result + (int) (origin ^ (origin >>> 32));
    return result;
  }

  @Override
  public String toString()
  {
    return "DurationGranularity{" +
           "length=" + length +
           ", origin=" + origin +
           '}';
  }
}

redpajama_set_name: RedPajamaGithub


text:
import moment from 'moment';

class EventsCreateController {

    constructor($stateParams) {
        this.params = $stateParams;
    }
}

export default EventsCreateController;


text:
from kivy.uix.popup import *
from kivy.properties import StringProperty
from kivy.clock import Clock

import audio as a_m

from pentai.base.pente_exceptions import *
import pentai.base.logger as log
from pentai.base.defines import *

class BasePopup(Popup):
    """ There should only be one active popup at a time. """

    my_active = None

    def __init__(self, *args, **kwargs):
        super(BasePopup, self).__init__(*args, **kwargs)
        if BasePopup.my_active:
            log.error("More than one popup attempted")
            raise MultiplePopupsException()

    @staticmethod
    def confirm():
        if BasePopup.my_active != None:
            BasePopup.my_active.ok_confirm()

    def ok_confirm(self):
        if BasePopup.my_active != None:
            a_m.instance.click()
            BasePopup.my_active = None
            self.dismiss()
        return True

    @staticmethod
    def is_active():
        return not BasePopup.my_active is None

    @staticmethod
    def clear():
        a = BasePopup.my_active
        BasePopup.my_active = None
        a.dismiss()

    def on_open(self):
        existing = BasePopup.my_active
        if existing and existing != self:
            log.error("More than one popup attempted")
            raise MultiplePopupsException()
        BasePopup.my_active = self

class MessagePopup(BasePopup):
    """ Message Popup is for errors and help so far.
        Click anywhere to dismiss. """

    def __init__(self, timeout_val=None, *args, **kwargs):
        self.auto_dismiss = True
        self.going = False

        if timeout_val:
            Clock.schedule_once(self.timeout, timeout_val)
        super(MessagePopup, self).__init__(*args, **kwargs)

    def on_touch_down(self, touch):
        if not touch.is_mouse_scrolling:
            self.going = True
            return True
        return super(BasePopup, self).on_touch_down(touch)

    def on_touch_up(self, touch):
        if not touch.is_mouse_scrolling:
            if self.going:
                self.ok_confirm()
            self.going = not self.going
            return True
        return super(BasePopup, self).on_touch_up(touch)

    def timeout(self, dt):
        self.ok_confirm()

class ConfirmPopup(BasePopup):
    """ ConfirmPopup is for True/False confirmation popup with a message """
    confirm_prompt = StringProperty("")

    def __init__(self, message, action, *args, **kwargs):
        self.auto_dismiss = False
        self.title = "" # I don't like the default :)
        self.confirm_prompt = message
        self.action = action
        super(ConfirmPopup, self).__init__(*args, **kwargs)

    bypass = True

    @staticmethod
    def create_and_open(message, action, force=False, *args, **kwargs):
        if ConfirmPopup.bypass and not force:
            action()
            return
        if BasePopup.my_active == None:
            # TODO: Do we dismiss any existing popup?
            BasePopup.my_active = \
                ConfirmPopup(*args, message=message,
                        action=action, **kwargs)
            BasePopup.my_active.open()

    def ok_confirm(self):
        if super(ConfirmPopup, self).ok_confirm():
            self.action()


text:
package com.google.android.exoplayer2;

import android.annotation.TargetApi;
import android.content.Context;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.MediaCodec;
import android.media.MediaFormat;
import android.support.annotation.IntDef;
import android.view.Surface;
import com.google.android.exoplayer2.PlayerMessage.Target;
import com.google.android.exoplayer2.util.Util;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.UUID;

/**
 * Defines constants used by the library.
 */
@SuppressWarnings("InlinedApi")
public final class C {

  private C() {}

  /**
   * Special constant representing a time corresponding to the end of a source. Suitable for use in
   * any time base.
   */
  public static final long TIME_END_OF_SOURCE = Long.MIN_VALUE;

  /**
   * Special constant representing an unset or unknown time or duration. Suitable for use in any
   * time base.
   */
  public static final long TIME_UNSET = Long.MIN_VALUE + 1;

  /**
   * Represents an unset or unknown index.
   */
  public static final int INDEX_UNSET = -1;

  /**
   * Represents an unset or unknown position.
   */
  public static final int POSITION_UNSET = -1;

  /**
   * Represents an unset or unknown length.
   */
  public static final int LENGTH_UNSET = -1;

  /** Represents an unset or unknown percentage. */
  public static final int PERCENTAGE_UNSET = -1;

  /**
   * The number of microseconds in one second.
   */
  public static final long MICROS_PER_SECOND = 1000000L;

  /**
   * The number of nanoseconds in one second.
   */
  public static final long NANOS_PER_SECOND = 1000000000L;

  /**
   * The name of the ASCII charset.
   */
  public static final String ASCII_NAME = "US-ASCII";
  /**
   * The name of the UTF-8 charset.
   */
  public static final String UTF8_NAME = "UTF-8";

  /**
   * The name of the UTF-16 charset.
   */
  public static final String UTF16_NAME = "UTF-16";

  /**
   * The name of the serif font family.
   */
  public static final String SERIF_NAME = "serif";

  /**
   * The name of the sans-serif font family.
   */
  public static final String SANS_SERIF_NAME = "sans-serif";

  /**
   * Crypto modes for a codec.
   */
  @Retention(RetentionPolicy.SOURCE)
  @IntDef({CRYPTO_MODE_UNENCRYPTED, CRYPTO_MODE_AES_CTR, CRYPTO_MODE_AES_CBC})
  public @interface CryptoMode {}
  /**
   * @see MediaCodec#CRYPTO_MODE_UNENCRYPTED
   */
  public static final int CRYPTO_MODE_UNENCRYPTED = MediaCodec.CRYPTO_MODE_UNENCRYPTED;
  /**
   * @see MediaCodec#CRYPTO_MODE_AES_CTR
   */
  public static final int CRYPTO_MODE_AES_CTR = MediaCodec.CRYPTO_MODE_AES_CTR;
  /**
   * @see MediaCodec#CRYPTO_MODE_AES_CBC
   */
  public static final int CRYPTO_MODE_AES_CBC = MediaCodec.CRYPTO_MODE_AES_CBC;

  /**
   * Represents an unset {@link android.media.AudioTrack} session identifier. Equal to
   * {@link AudioManager#AUDIO_SESSION_ID_GENERATE}.
   */
  public static final int AUDIO_SESSION_ID_UNSET = AudioManager.AUDIO_SESSION_ID_GENERATE;

  /** Represents an audio encoding, or an invalid or unset value. */
  @Retention(RetentionPolicy.SOURCE)
  @IntDef({
    Format.NO_VALUE,
    ENCODING_INVALID,
    ENCODING_PCM_8BIT,
    ENCODING_PCM_16BIT,
    ENCODING_PCM_24BIT,
    ENCODING_PCM_32BIT,
    ENCODING_PCM_FLOAT,
    ENCODING_AC3,
    ENCODING_E_AC3,
    ENCODING_DTS,
    ENCODING_DTS_HD,
    ENCODING_DOLBY_TRUEHD
  })
  public @interface Encoding {}

  /**
   * Represents a PCM audio encoding, or an invalid or unset value.
   */
  @Retention(RetentionPolicy.SOURCE)
  @IntDef({Format.NO_VALUE, ENCODING_INVALID, ENCODING_PCM_8BIT, ENCODING_PCM_16BIT,
      ENCODING_PCM_24BIT, ENCODING_PCM_32BIT, ENCODING_PCM_FLOAT})
  public @interface PcmEncoding {}
  /** @see AudioFormat#ENCODING_INVALID */
  public static final int ENCODING_INVALID = AudioFormat.ENCODING_INVALID;
  /** @see AudioFormat#ENCODING_PCM_8BIT */
  public static final int ENCODING_PCM_8BIT = AudioFormat.ENCODING_PCM_8BIT;
  /** @see AudioFormat#ENCODING_PCM_16BIT */
  public static final int ENCODING_PCM_16BIT = AudioFormat.ENCODING_PCM_16BIT;
  /** PCM encoding with 24 bits per sample. */
  public static final int ENCODING_PCM_24BIT = 0x80000000;
  /** PCM encoding with 32 bits per sample. */
  public static final int ENCODING_PCM_32BIT = 0x40000000;
  /** @see AudioFormat#ENCODING_PCM_FLOAT */
  public static final int ENCODING_PCM_FLOAT = AudioFormat.ENCODING_PCM_FLOAT;
  /** @see AudioFormat#ENCODING_AC3 */
  public static final int ENCODING_AC3 = AudioFormat.ENCODING_AC3;
  /** @see AudioFormat#ENCODING_E_AC3 */
  public static final int ENCODING_E_AC3 = AudioFormat.ENCODING_E_AC3;
  /** @see AudioFormat#ENCODING_DTS */
  public static final int ENCODING_DTS = AudioFormat.ENCODING_DTS;
  /** @see AudioFormat#ENCODING_DTS_HD */
  public static final int ENCODING_DTS_HD = AudioFormat.ENCODING_DTS_HD;
  /** @see AudioFormat#ENCODING_DOLBY_TRUEHD */
  public static final int ENCODING_DOLBY_TRUEHD = AudioFormat.ENCODING_DOLBY_TRUEHD;

  /**
   * @see AudioFormat#CHANNEL_OUT_7POINT1_SURROUND
   */
  @SuppressWarnings("deprecation")
  public static final int CHANNEL_OUT_7POINT1_SURROUND = Util.SDK_INT < 23
      ? AudioFormat.CHANNEL_OUT_7POINT1 : AudioFormat.CHANNEL_OUT_7POINT1_SURROUND;

  /**
   * Stream types for an {@link android.media.AudioTrack}.
   */
  @Retention(RetentionPolicy.SOURCE)
  @IntDef({STREAM_TYPE_ALARM, STREAM_TYPE_DTMF, STREAM_TYPE_MUSIC, STREAM_TYPE_NOTIFICATION,
      STREAM_TYPE_RING, STREAM_TYPE_SYSTEM, STREAM_TYPE_VOICE_CALL, STREAM_TYPE_USE_DEFAULT})
  public @interface StreamType {}
  /**
   * @see AudioManager#STREAM_ALARM
   */
  public static final int STREAM_TYPE_ALARM = AudioManager.STREAM_ALARM;
  /**
   * @see AudioManager#STREAM_DTMF
   */
  public static final int STREAM_TYPE_DTMF = AudioManager.STREAM_DTMF;
  /**
   * @see AudioManager#STREAM_MUSIC
   */
  public static final int STREAM_TYPE_MUSIC = AudioManager.STREAM_MUSIC;
  /**
   * @see AudioManager#STREAM_NOTIFICATION
   */
  public static final int STREAM_TYPE_NOTIFICATION = AudioManager.STREAM_NOTIFICATION;
  /**
   * @see AudioManager#STREAM_RING
   */
  public static final int STREAM_TYPE_RING = AudioManager.STREAM_RING;
  /**
   * @see AudioManager#STREAM_SYSTEM
   */
  public static final int STREAM_TYPE_SYSTEM = AudioManager.STREAM_SYSTEM;
  /**
   * @see AudioManager#STREAM_VOICE_CALL
   */
  public static final int STREAM_TYPE_VOICE_CALL = AudioManager.STREAM_VOICE_CALL;
  /**
   * @see AudioManager#USE_DEFAULT_STREAM_TYPE
   */
  public static final int STREAM_TYPE_USE_DEFAULT = AudioManager.USE_DEFAULT_STREAM_TYPE;
  /**
   * The default stream type used by audio renderers.
   */
  public static final int STREAM_TYPE_DEFAULT = STREAM_TYPE_MUSIC;

  /**
   * Content types for {@link com.google.android.exoplayer2.audio.AudioAttributes}.
   */
  @Retention(RetentionPolicy.SOURCE)
  @IntDef({CONTENT_TYPE_MOVIE, CONTENT_TYPE_MUSIC, CONTENT_TYPE_SONIFICATION, CONTENT_TYPE_SPEECH,
      CONTENT_TYPE_UNKNOWN})
  public @interface AudioContentType {}
  /**
   * @see android.media.AudioAttributes#CONTENT_TYPE_MOVIE
   */
  public static final int CONTENT_TYPE_MOVIE = android.media.AudioAttributes.CONTENT_TYPE_MOVIE;
  /**
   * @see android.media.AudioAttributes#CONTENT_TYPE_MUSIC
   */
  public static final int CONTENT_TYPE_MUSIC = android.media.AudioAttributes.CONTENT_TYPE_MUSIC;
  /**
   * @see android.media.AudioAttributes#CONTENT_TYPE_SONIFICATION
   */
  public static final int CONTENT_TYPE_SONIFICATION =
      android.media.AudioAttributes.CONTENT_TYPE_SONIFICATION;
  /**
   * @see android.media.AudioAttributes#CONTENT_TYPE_SPEECH
   */
  public static final int CONTENT_TYPE_SPEECH =
      android.media.AudioAttributes.CONTENT_TYPE_SPEECH;
  /**
   * @see android.media.AudioAttributes#CONTENT_TYPE_UNKNOWN
   */
  public static final int CONTENT_TYPE_UNKNOWN =
      android.media.AudioAttributes.CONTENT_TYPE_UNKNOWN;

  /**
   * Flags for {@link com.google.android.exoplayer2.audio.AudioAttributes}.
   * <p>
   * Note that {@code FLAG_HW_AV_SYNC} is not available because the player takes care of setting the
   * flag when tunneling is enabled via a track selector.
   */
  @Retention(RetentionPolicy.SOURCE)
  @IntDef(flag = true, value = {FLAG_AUDIBILITY_ENFORCED})
  public @interface AudioFlags {}
  /**
   * @see android.media.AudioAttributes#FLAG_AUDIBILITY_ENFORCED
   */
  public static final int FLAG_AUDIBILITY_ENFORCED =
      android.media.AudioAttributes.FLAG_AUDIBILITY_ENFORCED;

  /**
   * Usage types for {@link com.google.android.exoplayer2.audio.AudioAttributes}.
   */
  @Retention(RetentionPolicy.SOURCE)
  @IntDef({USAGE_ALARM, USAGE_ASSISTANCE_ACCESSIBILITY, USAGE_ASSISTANCE_NAVIGATION_GUIDANCE,
      USAGE_ASSISTANCE_SONIFICATION, USAGE_GAME, USAGE_MEDIA, USAGE_NOTIFICATION,
      USAGE_NOTIFICATION_COMMUNICATION_DELAYED, USAGE_NOTIFICATION_COMMUNICATION_INSTANT,
      USAGE_NOTIFICATION_COMMUNICATION_REQUEST, USAGE_NOTIFICATION_EVENT,
      USAGE_NOTIFICATION_RINGTONE, USAGE_UNKNOWN, USAGE_VOICE_COMMUNICATION,
      USAGE_VOICE_COMMUNICATION_SIGNALLING})
  public @interface AudioUsage {}
  /**
   * @see android.media.AudioAttributes#USAGE_ALARM
   */
  public static final int USAGE_ALARM = android.media.AudioAttributes.USAGE_ALARM;
  /**
   * @see android.media.AudioAttributes#USAGE_ASSISTANCE_ACCESSIBILITY
   */
  public static final int USAGE_ASSISTANCE_ACCESSIBILITY =
      android.media.AudioAttributes.USAGE_ASSISTANCE_ACCESSIBILITY;
  /**
   * @see android.media.AudioAttributes#USAGE_ASSISTANCE_NAVIGATION_GUIDANCE
   */
  public static final int USAGE_ASSISTANCE_NAVIGATION_GUIDANCE =
      android.media.AudioAttributes.USAGE_ASSISTANCE_NAVIGATION_GUIDANCE;
  /**
   * @see android.media.AudioAttributes#USAGE_ASSISTANCE_SONIFICATION
   */
  public static final int USAGE_ASSISTANCE_SONIFICATION =
      android.media.AudioAttributes.USAGE_ASSISTANCE_SONIFICATION;
  /**
   * @see android.media.AudioAttributes#USAGE_GAME
   */
  public static final int USAGE_GAME = android.media.AudioAttributes.USAGE_GAME;
  /**
   * @see android.media.AudioAttributes#USAGE_MEDIA
   */
  public static final int USAGE_MEDIA = android.media.AudioAttributes.USAGE_MEDIA;
  /**
   * @see android.media.AudioAttributes#USAGE_NOTIFICATION
   */
  public static final int USAGE_NOTIFICATION = android.media.AudioAttributes.USAGE_NOTIFICATION;
  /**
   * @see android.media.AudioAttributes#USAGE_NOTIFICATION_COMMUNICATION_DELAYED
   */
  public static final int USAGE_NOTIFICATION_COMMUNICATION_DELAYED =
      android.media.AudioAttributes.USAGE_NOTIFICATION_COMMUNICATION_DELAYED;
  /**
   * @see android.media.AudioAttributes#USAGE_NOTIFICATION_COMMUNICATION_INSTANT
   */
  public static final int USAGE_NOTIFICATION_COMMUNICATION_INSTANT =
      android.media.AudioAttributes.USAGE_NOTIFICATION_COMMUNICATION_INSTANT;
  /**
   * @see android.media.AudioAttributes#USAGE_NOTIFICATION_COMMUNICATION_REQUEST
   */
  public static final int USAGE_NOTIFICATION_COMMUNICATION_REQUEST =
      android.media.AudioAttributes.USAGE_NOTIFICATION_COMMUNICATION_REQUEST;
  /**
   * @see android.media.AudioAttributes#USAGE_NOTIFICATION_EVENT
   */
  public static final int USAGE_NOTIFICATION_EVENT =
      android.media.AudioAttributes.USAGE_NOTIFICATION_EVENT;
  /**
   * @see android.media.AudioAttributes#USAGE_NOTIFICATION_RINGTONE
   */
  public static final int USAGE_NOTIFICATION_RINGTONE =
      android.media.AudioAttributes.USAGE_NOTIFICATION_RINGTONE;
  /**
   * @see android.media.AudioAttributes#USAGE_UNKNOWN
   */
  public static final int USAGE_UNKNOWN = android.media.AudioAttributes.USAGE_UNKNOWN;
  /**
   * @see android.media.AudioAttributes#USAGE_VOICE_COMMUNICATION
   */
  public static final int USAGE_VOICE_COMMUNICATION =
      android.media.AudioAttributes.USAGE_VOICE_COMMUNICATION;
  /**
   * @see android.media.AudioAttributes#USAGE_VOICE_COMMUNICATION_SIGNALLING
   */
  public static final int USAGE_VOICE_COMMUNICATION_SIGNALLING =
      android.media.AudioAttributes.USAGE_VOICE_COMMUNICATION_SIGNALLING;

  /**
   * Flags which can apply to a buffer containing a media sample.
   */
  @Retention(RetentionPolicy.SOURCE)
  @IntDef(flag = true, value = {BUFFER_FLAG_KEY_FRAME, BUFFER_FLAG_END_OF_STREAM,
      BUFFER_FLAG_ENCRYPTED, BUFFER_FLAG_DECODE_ONLY})
  public @interface BufferFlags {}
  /**
   * Indicates that a buffer holds a synchronization sample.
   */
  public static final int BUFFER_FLAG_KEY_FRAME = MediaCodec.BUFFER_FLAG_KEY_FRAME;
  /**
   * Flag for empty buffers that signal that the end of the stream was reached.
   */
  public static final int BUFFER_FLAG_END_OF_STREAM = MediaCodec.BUFFER_FLAG_END_OF_STREAM;
  /**
   * Indicates that a buffer is (at least partially) encrypted.
   */
  public static final int BUFFER_FLAG_ENCRYPTED = 0x40000000;
  /**
   * Indicates that a buffer should be decoded but not rendered.
   */
  public static final int BUFFER_FLAG_DECODE_ONLY = 0x80000000;

  /**
   * Video scaling modes for {@link MediaCodec}-based {@link Renderer}s.
   */
  @Retention(RetentionPolicy.SOURCE)
  @IntDef(value = {VIDEO_SCALING_MODE_SCALE_TO_FIT, VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING})
  public @interface VideoScalingMode {}
  /**
   * @see MediaCodec#VIDEO_SCALING_MODE_SCALE_TO_FIT
   */
  public static final int VIDEO_SCALING_MODE_SCALE_TO_FIT =
      MediaCodec.VIDEO_SCALING_MODE_SCALE_TO_FIT;
  /**
   * @see MediaCodec#VIDEO_SCALING_MODE_SCALE_TO_FIT
   */
  public static final int VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING =
      MediaCodec.VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING;
  /**
   * A default video scaling mode for {@link MediaCodec}-based {@link Renderer}s.
   */
  public static final int VIDEO_SCALING_MODE_DEFAULT = VIDEO_SCALING_MODE_SCALE_TO_FIT;

  /**
   * Track selection flags.
   */
  @Retention(RetentionPolicy.SOURCE)
  @IntDef(flag = true, value = {SELECTION_FLAG_DEFAULT, SELECTION_FLAG_FORCED,
      SELECTION_FLAG_AUTOSELECT})
  public @interface SelectionFlags {}
  /**
   * Indicates that the track should be selected if user preferences do not state otherwise.
   */
  public static final int SELECTION_FLAG_DEFAULT = 1;
  /**
   * Indicates that the track must be displayed. Only applies to text tracks.
   */
  public static final int SELECTION_FLAG_FORCED = 2;
  /**
   * Indicates that the player may choose to play the track in absence of an explicit user
   * preference.
   */
  public static final int SELECTION_FLAG_AUTOSELECT = 4;

  /**
   * Represents an undetermined language as an ISO 639 alpha-3 language code.
   */
  public static final String LANGUAGE_UNDETERMINED = "und";

  /**
   * Represents a streaming or other media type.
   */
  @Retention(RetentionPolicy.SOURCE)
  @IntDef({TYPE_DASH, TYPE_SS, TYPE_HLS, TYPE_OTHER})
  public @interface ContentType {}
  /**
   * Value returned by {@link Util#inferContentType(String)} for DASH manifests.
   */
  public static final int TYPE_DASH = 0;
  /**
   * Value returned by {@link Util#inferContentType(String)} for Smooth Streaming manifests.
   */
  public static final int TYPE_SS = 1;
  /**
   * Value returned by {@link Util#inferContentType(String)} for HLS manifests.
   */
  public static final int TYPE_HLS = 2;
  /**
   * Value returned by {@link Util#inferContentType(String)} for files other than DASH, HLS or
   * Smooth Streaming manifests.
   */
  public static final int TYPE_OTHER = 3;

  /**
   * A return value for methods where the end of an input was encountered.
   */
  public static final int RESULT_END_OF_INPUT = -1;
  /**
   * A return value for methods where the length of parsed data exceeds the maximum length allowed.
   */
  public static final int RESULT_MAX_LENGTH_EXCEEDED = -2;
  /**
   * A return value for methods where nothing was read.
   */
  public static final int RESULT_NOTHING_READ = -3;
  /**
   * A return value for methods where a buffer was read.
   */
  public static final int RESULT_BUFFER_READ = -4;
  /**
   * A return value for methods where a format was read.
   */
  public static final int RESULT_FORMAT_READ = -5;

  /**
   * A data type constant for data of unknown or unspecified type.
   */
  public static final int DATA_TYPE_UNKNOWN = 0;
  /**
   * A data type constant for media, typically containing media samples.
   */
  public static final int DATA_TYPE_MEDIA = 1;
  /**
   * A data type constant for media, typically containing only initialization data.
   */
  public static final int DATA_TYPE_MEDIA_INITIALIZATION = 2;
  /**
   * A data type constant for drm or encryption data.
   */
  public static final int DATA_TYPE_DRM = 3;
  /**
   * A data type constant for a manifest file.
   */
  public static final int DATA_TYPE_MANIFEST = 4;
  /**
   * A data type constant for time synchronization data.
   */
  public static final int DATA_TYPE_TIME_SYNCHRONIZATION = 5;
  /** A data type constant for ads loader data. */
  public static final int DATA_TYPE_AD = 6;
  /**
   * Applications or extensions may define custom {@code DATA_TYPE_*} constants greater than or
   * equal to this value.
   */
  public static final int DATA_TYPE_CUSTOM_BASE = 10000;

  /**
   * A type constant for tracks of unknown type.
   */
  public static final int TRACK_TYPE_UNKNOWN = -1;
  /**
   * A type constant for tracks of some default type, where the type itself is unknown.
   */
  public static final int TRACK_TYPE_DEFAULT = 0;
  /**
   * A type constant for audio tracks.
   */
  public static final int TRACK_TYPE_AUDIO = 1;
  /**
   * A type constant for video tracks.
   */
  public static final int TRACK_TYPE_VIDEO = 2;
  /**
   * A type constant for text tracks.
   */
  public static final int TRACK_TYPE_TEXT = 3;
  /**
   * A type constant for metadata tracks.
   */
  public static final int TRACK_TYPE_METADATA = 4;
  /**
   * A type constant for a dummy or empty track.
   */
  public static final int TRACK_TYPE_NONE = 5;
  /**
   * Applications or extensions may define custom {@code TRACK_TYPE_*} constants greater than or
   * equal to this value.
   */
  public static final int TRACK_TYPE_CUSTOM_BASE = 10000;

  /**
   * A selection reason constant for selections whose reasons are unknown or unspecified.
   */
  public static final int SELECTION_REASON_UNKNOWN = 0;
  /**
   * A selection reason constant for an initial track selection.
   */
  public static final int SELECTION_REASON_INITIAL = 1;
  /**
   * A selection reason constant for an manual (i.e. user initiated) track selection.
   */
  public static final int SELECTION_REASON_MANUAL = 2;
  /**
   * A selection reason constant for an adaptive track selection.
   */
  public static final int SELECTION_REASON_ADAPTIVE = 3;
  /**
   * A selection reason constant for a trick play track selection.
   */
  public static final int SELECTION_REASON_TRICK_PLAY = 4;
  /**
   * Applications or extensions may define custom {@code SELECTION_REASON_*} constants greater than
   * or equal to this value.
   */
  public static final int SELECTION_REASON_CUSTOM_BASE = 10000;

  /**
   * A default size in bytes for an individual allocation that forms part of a larger buffer.
   */
  public static final int DEFAULT_BUFFER_SEGMENT_SIZE = 64 * 1024;

  /**
   * A default size in bytes for a video buffer.
   */
  public static final int DEFAULT_VIDEO_BUFFER_SIZE = 200 * DEFAULT_BUFFER_SEGMENT_SIZE;

  /**
   * A default size in bytes for an audio buffer.
   */
  public static final int DEFAULT_AUDIO_BUFFER_SIZE = 54 * DEFAULT_BUFFER_SEGMENT_SIZE;

  /**
   * A default size in bytes for a text buffer.
   */
  public static final int DEFAULT_TEXT_BUFFER_SIZE = 2 * DEFAULT_BUFFER_SEGMENT_SIZE;

  /**
   * A default size in bytes for a metadata buffer.
   */
  public static final int DEFAULT_METADATA_BUFFER_SIZE = 2 * DEFAULT_BUFFER_SEGMENT_SIZE;

  /**
   * A default size in bytes for a muxed buffer (e.g. containing video, audio and text).
   */
  public static final int DEFAULT_MUXED_BUFFER_SIZE = DEFAULT_VIDEO_BUFFER_SIZE
      + DEFAULT_AUDIO_BUFFER_SIZE + DEFAULT_TEXT_BUFFER_SIZE;

  /**
   * "cenc" scheme type name as defined in ISO/IEC 23001-7:2016.
   */
  public static final String CENC_TYPE_cenc = "cenc";

  /**
   * "cbc1" scheme type name as defined in ISO/IEC 23001-7:2016.
   */
  public static final String CENC_TYPE_cbc1 = "cbc1";

  /**
   * "cens" scheme type name as defined in ISO/IEC 23001-7:2016.
   */
  public static final String CENC_TYPE_cens = "cens";

  /**
   * "cbcs" scheme type name as defined in ISO/IEC 23001-7:2016.
   */
  public static final String CENC_TYPE_cbcs = "cbcs";

  /**
   * The Nil UUID as defined by
   * <a href="https://tools.ietf.org/html/rfc4122#section-4.1.7">RFC4122</a>.
   */
  public static final UUID UUID_NIL = new UUID(0L, 0L);

  /**
   * UUID for the W3C
   * <a href="https://w3c.github.io/encrypted-media/format-registry/initdata/cenc.html">Common PSSH
   * box</a>.
   */
  public static final UUID COMMON_PSSH_UUID = new UUID(0x1077EFECC0B24D02L, 0xACE33C1E52E2FB4BL);

  /**
   * UUID for the ClearKey DRM scheme.
   * <p>
   * ClearKey is supported on Android devices running Android 5.0 (API Level 21) and up.
   */
  public static final UUID CLEARKEY_UUID = new UUID(0xE2719D58A985B3C9L, 0x781AB030AF78D30EL);

  /**
   * UUID for the Widevine DRM scheme.
   * <p>
   * Widevine is supported on Android devices running Android 4.3 (API Level 18) and up.
   */
  public static final UUID WIDEVINE_UUID = new UUID(0xEDEF8BA979D64ACEL, 0xA3C827DCD51D21EDL);

  /**
   * UUID for the PlayReady DRM scheme.
   * <p>
   * PlayReady is supported on all AndroidTV devices. Note that most other Android devices do not
   * provide PlayReady support.
   */
  public static final UUID PLAYREADY_UUID = new UUID(0x9A04F07998404286L, 0xAB92E65BE0885F95L);

  /**
   * The type of a message that can be passed to a video {@link Renderer} via {@link
   * ExoPlayer#createMessage(Target)}. The message payload should be the target {@link Surface}, or
   * null.
   */
  public static final int MSG_SET_SURFACE = 1;

  /**
   * A type of a message that can be passed to an audio {@link Renderer} via {@link
   * ExoPlayer#createMessage(Target)}. The message payload should be a {@link Float} with 0 being
   * silence and 1 being unity gain.
   */
  public static final int MSG_SET_VOLUME = 2;

  /**
   * A type of a message that can be passed to an audio {@link Renderer} via {@link
   * ExoPlayer#createMessage(Target)}. The message payload should be an {@link
   * com.google.android.exoplayer2.audio.AudioAttributes} instance that will configure the
   * underlying audio track. If not set, the default audio attributes will be used. They are
   * suitable for general media playback.
   *
   * <p>Setting the audio attributes during playback may introduce a short gap in audio output as
   * the audio track is recreated. A new audio session id will also be generated.
   *
   * <p>If tunneling is enabled by the track selector, the specified audio attributes will be
   * ignored, but they will take effect if audio is later played without tunneling.
   *
   * <p>If the device is running a build before platform API version 21, audio attributes cannot be
   * set directly on the underlying audio track. In this case, the usage will be mapped onto an
   * equivalent stream type using {@link Util#getStreamTypeForAudioUsage(int)}.
   *
   * <p>To get audio attributes that are equivalent to a legacy stream type, pass the stream type to
   * {@link Util#getAudioUsageForStreamType(int)} and use the returned {@link C.AudioUsage} to build
   * an audio attributes instance.
   */
  public static final int MSG_SET_AUDIO_ATTRIBUTES = 3;

  /**
   * The type of a message that can be passed to a {@link MediaCodec}-based video {@link Renderer}
   * via {@link ExoPlayer#createMessage(Target)}. The message payload should be one of the integer
   * scaling modes in {@link C.VideoScalingMode}.
   *
   * <p>Note that the scaling mode only applies if the {@link Surface} targeted by the renderer is
   * owned by a {@link android.view.SurfaceView}.
   */
  public static final int MSG_SET_SCALING_MODE = 4;

  /**
   * Applications or extensions may define custom {@code MSG_*} constants that can be passed to
   * {@link Renderer}s. These custom constants must be greater than or equal to this value.
   */
  public static final int MSG_CUSTOM_BASE = 10000;

  /**
   * The stereo mode for 360/3D/VR videos.
   */
  @Retention(RetentionPolicy.SOURCE)
  @IntDef({
      Format.NO_VALUE,
      STEREO_MODE_MONO,
      STEREO_MODE_TOP_BOTTOM,
      STEREO_MODE_LEFT_RIGHT,
      STEREO_MODE_STEREO_MESH
  })
  public @interface StereoMode {}
  /**
   * Indicates Monoscopic stereo layout, used with 360/3D/VR videos.
   */
  public static final int STEREO_MODE_MONO = 0;
  /**
   * Indicates Top-Bottom stereo layout, used with 360/3D/VR videos.
   */
  public static final int STEREO_MODE_TOP_BOTTOM = 1;
  /**
   * Indicates Left-Right stereo layout, used with 360/3D/VR videos.
   */
  public static final int STEREO_MODE_LEFT_RIGHT = 2;
  /**
   * Indicates a stereo layout where the left and right eyes have separate meshes,
   * used with 360/3D/VR videos.
   */
  public static final int STEREO_MODE_STEREO_MESH = 3;

  /**
   * Video colorspaces.
   */
  @Retention(RetentionPolicy.SOURCE)
  @IntDef({Format.NO_VALUE, COLOR_SPACE_BT709, COLOR_SPACE_BT601, COLOR_SPACE_BT2020})
  public @interface ColorSpace {}
  /**
   * @see MediaFormat#COLOR_STANDARD_BT709
   */
  public static final int COLOR_SPACE_BT709 = MediaFormat.COLOR_STANDARD_BT709;
  /**
   * @see MediaFormat#COLOR_STANDARD_BT601_PAL
   */
  public static final int COLOR_SPACE_BT601 = MediaFormat.COLOR_STANDARD_BT601_PAL;
  /**
   * @see MediaFormat#COLOR_STANDARD_BT2020
   */
  public static final int COLOR_SPACE_BT2020 = MediaFormat.COLOR_STANDARD_BT2020;

  /**
   * Video color transfer characteristics.
   */
  @Retention(RetentionPolicy.SOURCE)
  @IntDef({Format.NO_VALUE, COLOR_TRANSFER_SDR, COLOR_TRANSFER_ST2084, COLOR_TRANSFER_HLG})
  public @interface ColorTransfer {}
  /**
   * @see MediaFormat#COLOR_TRANSFER_SDR_VIDEO
   */
  public static final int COLOR_TRANSFER_SDR = MediaFormat.COLOR_TRANSFER_SDR_VIDEO;
  /**
   * @see MediaFormat#COLOR_TRANSFER_ST2084
   */
  public static final int COLOR_TRANSFER_ST2084 = MediaFormat.COLOR_TRANSFER_ST2084;
  /**
   * @see MediaFormat#COLOR_TRANSFER_HLG
   */
  public static final int COLOR_TRANSFER_HLG = MediaFormat.COLOR_TRANSFER_HLG;

  /**
   * Video color range.
   */
  @Retention(RetentionPolicy.SOURCE)
  @IntDef({Format.NO_VALUE, COLOR_RANGE_LIMITED, COLOR_RANGE_FULL})
  public @interface ColorRange {}
  /**
   * @see MediaFormat#COLOR_RANGE_LIMITED
   */
  public static final int COLOR_RANGE_LIMITED = MediaFormat.COLOR_RANGE_LIMITED;
  /**
   * @see MediaFormat#COLOR_RANGE_FULL
   */
  public static final int COLOR_RANGE_FULL = MediaFormat.COLOR_RANGE_FULL;

  /**
   * Priority for media playback.
   *
   * <p>Larger values indicate higher priorities.
   */
  public static final int PRIORITY_PLAYBACK = 0;

  /**
   * Priority for media downloading.
   *
   * <p>Larger values indicate higher priorities.
   */
  public static final int PRIORITY_DOWNLOAD = PRIORITY_PLAYBACK - 1000;

  /**
   * Converts a time in microseconds to the corresponding time in milliseconds, preserving
   * {@link #TIME_UNSET} and {@link #TIME_END_OF_SOURCE} values.
   *
   * @param timeUs The time in microseconds.
   * @return The corresponding time in milliseconds.
   */
  public static long usToMs(long timeUs) {
    return (timeUs == TIME_UNSET || timeUs == TIME_END_OF_SOURCE) ? timeUs : (timeUs / 1000);
  }

  /**
   * Converts a time in milliseconds to the corresponding time in microseconds, preserving
   * {@link #TIME_UNSET} values and {@link #TIME_END_OF_SOURCE} values.
   *
   * @param timeMs The time in milliseconds.
   * @return The corresponding time in microseconds.
   */
  public static long msToUs(long timeMs) {
    return (timeMs == TIME_UNSET || timeMs == TIME_END_OF_SOURCE) ? timeMs : (timeMs * 1000);
  }

  /**
   * Returns a newly generated {@link android.media.AudioTrack} session identifier.
   */
  @TargetApi(21)
  public static int generateAudioSessionIdV21(Context context) {
    return ((AudioManager) context.getSystemService(Context.AUDIO_SERVICE))
        .generateAudioSessionId();
  }

}


text:
{-# LANGUAGE CPP #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}

import Control.Concurrent.MVar
import Control.Exception as E ( catch, SomeException )
  -- Prelude of GHC 7.4 also has @catch@, so we disambiguate with E.catch
import Control.Monad          ( unless )
import Control.Monad.IO.Class ( liftIO )

import Data.List (sort)
#if !(MIN_VERSION_base(4,8,0))
import Data.Functor           ( (<$) )
import Data.Monoid            ( mempty )
#endif

import System.Directory       ( createDirectory, withCurrentDirectory )
import System.FilePath
import System.IO.Silently     ( capture )
import System.IO.Temp

import Test.Tasty hiding (defaultMain)
import Test.Tasty.HUnit
import Test.Tasty.Options
import Test.Tasty.Runners
import Test.Tasty.Silver
import Test.Tasty.Silver.Advanced
import Test.Tasty.Silver.Filter (checkRF)
import Test.Tasty.Silver.Interactive
import Test.Tasty.Silver.Internal

touch :: FilePath -> IO ()
touch f = writeFile f ""

main :: IO ()
main = defaultMain $ testGroup "tests" $
  testShowDiff :
  testFindByExt :
  testWithResource :
  testCheckRF :
  -- Andreas, 2021-09-18
  -- @testGolden@ always fails, would need @--accept@ mode.
  -- testGolden :
  []

testFindByExt :: TestTree
testFindByExt =
  testCase "findByExtension" $
    withSystemTempDirectory "golden-test" $ \basedir -> do
     withCurrentDirectory basedir $ do
      -- Andreas 2021-09-07: setCurrentDirectory would affect other tests!

      createDirectory ("d1")
      createDirectory ("d1" </> "d2")
      touch ("d1" </> "d2" </> "h1.c")      -- match
      touch ("d1" </> "d2" </> "h1.exe")
      touch ("d1" </> "d2" </> "h1")
      touch ("d1" </> "g1.c")               -- match
      touch ("f1.c")                        -- match
      touch ("f2.h")                        -- match
      touch ("f2.exe")

      files <- findByExtension [".c", ".h"] "."
      sort files @?= sort
        [ "./d1/d2/h1.c"
        , "./d1/g1.c"
        , "./f1.c"
        , "./f2.h"
        ]

testShowDiff :: TestTree
testShowDiff =
  testCase "showDiff" $
    withSystemTempDirectory "golden-test" $ \ dir -> do
      let
        goldenFile  = dir </> "golden.txt"
        goldenValue = "golden value"
        actualFile  = dir </> "actual.txt"
        actualValue = "actual value"
        tree        = goldenVsFile "showDiff-internal" goldenFile actualFile $
                        writeFile actualFile actualValue
      writeFile goldenFile goldenValue
      writeFile actualFile actualValue
      do
          -- let io = defaultMain tree
          let io = runTestsInteractive (const False) mempty tree
          (out, success) <- capture $ E.catch (True <$ io) $ \ (e :: SomeException) -> do
             print e
             return False
          -- unless success $ putStr out
          putStr out
          assertBool "Test should succeed." success

-- UNUSED, but KEEP!
-- testGolden :: TestTree
-- testGolden =
--   goldenTest1
--     "wrongOutput"
--     (return $ Just "golden value")
--     (return "actual value")
--     (DiffText Nothing)   -- always fail
--     ShowText
--     (const $ return ())  -- keep the golden file no matter what

-- | Check if resources are properly initialized.
testWithResource :: TestTree
testWithResource =
  testCase "withResource" $
    -- The @AcceptTests True@ option automatically replaces the golden value.
    case tryIngredients [consoleTestReporter] (singleOption $ AcceptTests True) tree of
      Just r' -> do
        (out, success) <- capture r'
        unless success $ putStr out
        assertBool "Test should succeed." success
      Nothing -> assertFailure "Test broken"
  where
    tree   = withResource acq free test
    -- Resource acquisition.
    acq    = newMVar True
    -- Resource release.
    free v = swapMVar v False >> return ()
    -- Test using resource.
    test v = goldenTest1 "check res"
               (return Nothing)           -- get the golden value
               (liftIO $ testAction v)    -- get the tested value
               (\ _ _ -> Equal)           -- comparison function (always succeed)
               (\ _   -> ShowText mempty) -- show the golden/actual value
               (\ x   -> assertBool "Incorrect result" x)  -- update the golden file
    -- Actual test: check whether the MVar contains True.
    testAction v = do
      assertBool "Resource not initialized." =<< readMVar =<< v
      return True

testCheckRF :: TestTree
testCheckRF =
  testGroup "Filter.checkRF"
    [ testCase "empty1a" $ checkRF True  [] "/"     @?= True
    , testCase "empty1b" $ checkRF False [] "/"     @?= False
    , testCase "empty2a" $ checkRF True  [] "/sdfg" @?= True
    , testCase "empty2b" $ checkRF False [] "/sdfg" @?= False
    ]


text:
<?php

namespace Kunstmaan\FormBundle\Tests\Form;

use Kunstmaan\FormBundle\Entity\FormSubmissionFieldTypes\TextFormSubmissionField;
use Kunstmaan\FormBundle\Form\TextFormSubmissionType;
use Symfony\Component\Form\Test\TypeTestCase;

/**
 * Class TextFormSubmissionTypeTest
 */
class TextFormSubmissionTypeTest extends TypeTestCase
{
    public function testFormType()
    {
        $formData = [
            'value' => 'ball of string',
        ];

        $form = $this->factory->create(TextFormSubmissionType::class);

        $object = new TextFormSubmissionField();
        $object->setValue('ball of string');

        $form->submit($formData);

        $this->assertTrue($form->isSynchronized());
        $this->assertTrue($form->isValid());
        $this->assertEquals($object, $form->getData());

        $view = $form->createView();
        $children = $view->children;

        foreach (array_keys($formData) as $key) {
            $this->assertArrayHasKey($key, $children);
        }
    }
}


text:
#pragma once
#include "../detail/type_mat4x4.hpp"

namespace glm
{
	/// @ingroup core_matrix
	/// @{

	/// 4 columns of 4 components matrix of single-precision floating-point numbers.
	///
	/// @see GLSL 4.20.8 specification, section 4.1.6 Matrices
	typedef mat<4, 4, float, defaultp>			mat4x4;

	/// 4 columns of 4 components matrix of single-precision floating-point numbers.
	///
	/// @see GLSL 4.20.8 specification, section 4.1.6 Matrices
	typedef mat<4, 4, float, defaultp>			mat4;

	/// @}
}//namespace glm


text:
package org.ooc.compiler;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.StringTokenizer;

import org.ooc.ShellUtils;
import org.ooc.backends.BackendFactory;
import org.ooc.backends.ProjectInfo;
import org.ooc.errors.SourceContext;
import org.ooc.gui.SyntaxTreeWindow;

/**
 *
 * @author Amos Wenger
 */
public class CommandLineInterface {

	protected static String OOC_DIST = System.getenv("OOC_DIST");

    /**
     * @param args the command line arguments
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {

    	findDist();

        if(args.length < 1) {
            System.out.println("ooc: no files.");
            System.exit(1);
        }

        List<String> dynamicLibs = new ArrayList<String> ();
        List<String> unitList = new ArrayList<String> ();
        boolean daemon = false;
        boolean run = false;
        boolean timing = false;
        boolean ignoreUnknownArgs = false;
        int daemonPort = -1;

        boolean gui = false;

        BuildProperties props = new BuildProperties();

        for(String arg: args) {
        	if(arg.startsWith("-")) {
        		String option = arg.substring(1);
        		if(option.startsWith("locale")) {

        			Locale.setDefault(new Locale(arg.substring(arg.indexOf('=') + 1)));

        		} else if(option.startsWith("gui")) {

        			gui = true;

        		} else if(option.startsWith("backend=")) {

        			props.backend = BackendFactory.getBackend(option.substring("backend=".length()).trim());

        		} else if(option.startsWith("daemon")) {

        			daemon = true;
        			int index = arg.indexOf(':');
        			if(index != -1) {
        				daemonPort = Integer.parseInt(arg.substring(index + 1));
        			}

        		} else if(option.startsWith("sourcepath")) {

        			String sourcePathOption = arg.substring(arg.indexOf('=') + 1);
        			StringTokenizer tokenizer = new StringTokenizer(sourcePathOption, File.pathSeparator);
        			while(tokenizer.hasMoreTokens()) {
        				props.sourcePath.add(tokenizer.nextToken());
        			}

        		} else if(option.startsWith("outpath")) {

        			props.outPath = arg.substring(arg.indexOf('=') + 1);

        		} else if(option.startsWith("incpath")) {

        			props.incPath.add(arg.substring(arg.indexOf('=') + 1));

        		} else if(option.startsWith("I")) {

        			props.incPath.add(arg.substring(2));

        		} else if(option.startsWith("libpath")) {

        			props.libPath.add(arg.substring(arg.indexOf('=') + 1));

        		} else if(option.startsWith("L")) {

        			props.libPath.add(arg.substring(2));

        		} else if(option.startsWith("l")) {

        			dynamicLibs.add(arg.substring(2));

        		} else if(option.startsWith("freeargs")) {

        			ignoreUnknownArgs = true;

        		} else if(option.equals("noclean")) {

        			props.clean = false;

        		} else if(option.equals("shout")) {

        			props.shout = true;

        		} else if(option.equals("timing") || option.equals("t")) {

        			timing = true;

        		} else if(option.equals("debug") || option.equals("g")) {

        			props.debug = true;

        		} else if(option.equals("verbose") || option.equals("v")) {

        			props.verbose = true;

        		} else if(option.equals("run") || option.equals("r")) {

        			run = true;

        		} else if(option.equals("V") || option.equals("-version") || option.equals("version")) {

        			CompilerVersion.printVersion();
        			System.exit(0);

        		} else if(option.equals("h") || option.equals("-help") || option.equals("help")) {

        			Help.printHelp();
        			System.exit(0);

        		} else if(option.equals("help-backends") || option.equals("-help-backends")) {

        			Help.printHelpBackends();
        			System.exit(0);

        		} else if(option.equals("help-gcc") || option.equals("-help-gcc")) {

        			Help.printHelpGcc();
        			System.exit(0);

        		} else if(option.equals("help-make") || option.equals("-help-make")) {

        			Help.printHelpMake();
        			System.exit(0);

        		} else if(option.equals("help-none") || option.equals("-help-none")) {

        			Help.printHelpNone();
        			System.exit(0);

        		} else {

        			System.err.println("Unrecognized option: '"+arg+"'");
        			if(!ignoreUnknownArgs) System.exit(1);

        		}
        	} else {
        		unitList.add(arg);
        	}
        }

        if(daemon) {

        	if(!unitList.isEmpty()) {
        		System.err.println("Shouldn't specify a list of files to compile when starting in daemon mode ('-daemon' option)");
        		System.exit(1);
        	}
        	if(daemonPort == -1) {
        		System.err.println("Should specify a port when starting in daemon mode ('-daemon' option)");
        		System.exit(1);
        	}
        	new CompilerDaemon(daemonPort);

        } else {

        	ProjectInfo projInfo = new ProjectInfo(props);
			projInfo.dynamicLibraries.addAll(dynamicLibs);
        	Compiler compiler = new Compiler();
        	int returnCode = 0;

        	props.sourcePath.add("./");

            if(gui) {

            	SyntaxTreeWindow window = new SyntaxTreeWindow(props.sourcePath, unitList, projInfo);
            	System.out.println("Launching the gui....");
            	window.show();

            } else {

            	long t1 = System.currentTimeMillis();

	        	for(String unitName: unitList) {

	            	returnCode = compiler.compile(projInfo, unitName);
	                if(returnCode != 0) {
	                	break;
	                }
	            }

	        	long t2 = System.currentTimeMillis();

	        	if(timing) {
	        		System.out.println("Finished compilation in "+(t2-t1)+"ms.");
	        	}

	        	if(run && returnCode == 0) {
	        		ProcessBuilder pb = new ProcessBuilder();
	            	for(SourceContext source: projInfo.executables.values()) {
	            		String execPath = "./" + source.source.getInfo().simpleName;

	            		if(props.verbose) {
	            			System.out.println("Launching '"+execPath+"'...");
	            		}

						Process p = pb.command(execPath).start();
						ProcessUtils.redirectIO(p);
						int status = p.waitFor();

						if(props.verbose) {
							System.out.println("Exited with status "+status);
						}

	            	}
	            }

            }

        	System.exit(returnCode);

        }

        System.exit(0);

    }

	protected static void findDist() throws IOException {

		/**
		 * First try: assume we're launched with java -jar bin/ooc.jar and
		 * try to find ourselves in the classpath.
		 */
		if(OOC_DIST == null || OOC_DIST.trim().isEmpty()) {
	    	StringTokenizer st = new StringTokenizer(System.getProperty("java.class.path"), File.pathSeparator);
	    	while(st.hasMoreElements()) {
	    		String path = st.nextToken();
	    		if(path.contains("ooc.jar")) {
	    			OOC_DIST = new File(path).getCanonicalPath();
	    			OOC_DIST = new File(OOC_DIST).getParentFile().getParent();
	    			break;
	    		}
	    	}
    	}

		Map<String, String> env = System.getenv();

		/**
		 * Second try: assume we're launched as GCJ-compiled executable, and
		 * try to get our path from the "_" environment variable, which seems to
		 * be set by bash under Gentoo and by MSYS 1.0.11/whatever under MinGW/WinXP
		 */
    	if(OOC_DIST == null || OOC_DIST.trim().isEmpty()) {
    		Object curr = env.get("_");
    		if(curr != null) {
    			File file = new File(curr.toString().trim());
    			if(file.getPath().endsWith("ooc") || file.getPath().endsWith("ooc.exe")) {
    				String canonicalPath = file.getCanonicalPath();
    				OOC_DIST = new File(canonicalPath).getParentFile().getParent();
    			}
    		}
    	}

		/**
		 * Third try: assume we're launched as GCJ-compiled executable, and
		 * try to get the PATH environment variable, and look us in here.
		 */
    	if(OOC_DIST == null || OOC_DIST.trim().isEmpty()) {

    		File bin = ShellUtils.findExecutable("ooc");
    		if(bin == null) {
    			bin = ShellUtils.findExecutable("ooc.exe");
    		}

    		if(bin != null) {
    			String canonicalPath = bin.getCanonicalPath();
				OOC_DIST = new File(canonicalPath).getParentFile().getParent();
    		}

    	}

    	if(OOC_DIST == null || OOC_DIST.trim().isEmpty()) {
    		// If still null, wasn't found.
    		System.out.println("ERROR: You need to set the OOC_DIST environment " +
    				"variable to where you have installed ooc. (example: export OOC_DIST=/opt/ooc)");
    		System.exit(1);
    	}
	}

    /**
     * @return the emplacement of the ooc distribution directory, as specified
     * either by the OOC_DIST environment variable, or guessed via the classpath
     */
	public static String getOocDist() {

		return OOC_DIST;

	}

}


text:
class CCancelDoc : public CDocument
{
protected: // create from serialization only
	CCancelDoc();
	DECLARE_DYNCREATE(CCancelDoc)

// Attributes
public:

// Operations
public:

// Overrides
	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CCancelDoc)
	public:
	virtual BOOL OnNewDocument();
	virtual void Serialize(CArchive& ar);
	//}}AFX_VIRTUAL

// Implementation
public:
	virtual ~CCancelDoc();
#ifdef _DEBUG
	virtual void AssertValid() const;
	virtual void Dump(CDumpContext& dc) const;
#endif

protected:

// Generated message map functions
protected:
	//{{AFX_MSG(CCancelDoc)
		// NOTE - the ClassWizard will add and remove member functions here.
		//    DO NOT EDIT what you see in these blocks of generated code !
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};

/////////////////////////////////////////////////////////////////////////////


text:
// Axis Scale Grab Action|SecondaryControllerGrabActions|60030
namespace VRTK.SecondaryControllerGrabActions
{
    using UnityEngine;

    /// <summary>
    /// The Axis Scale Grab Action provides a mechanism to scale objects when they are grabbed with a secondary controller.
    /// </summary>
    /// <example>
    /// `VRTK/Examples/043_Controller_SecondaryControllerActions` demonstrates the ability to grab an object with one controller and scale it by grabbing and pulling with the second controller.
    /// </example>
    public class VRTK_AxisScaleGrabAction : VRTK_BaseGrabAction
    {
        [Tooltip("The distance the secondary controller must move away from the original grab position before the secondary controller auto ungrabs the object.")]
        public float ungrabDistance = 1f;
        [Tooltip("If checked the current X Axis of the object won't be scaled")]
        public bool lockXAxis = false;
        [Tooltip("If checked the current Y Axis of the object won't be scaled")]
        public bool lockYAxis = false;
        [Tooltip("If checked the current Z Axis of the object won't be scaled")]
        public bool lockZAxis = false;
        [Tooltip("If checked all the axes will be scaled together (unless locked)")]
        public bool uniformScaling = false;

        private Vector3 initialScale;
        private float initalLength;
        private float initialScaleFactor;

        /// <summary>
        /// The Initalise method is used to set up the state of the secondary action when the object is initially grabbed by a secondary controller.
        /// </summary>
        /// <param name="currentGrabbdObject">The Interactable Object script for the object currently being grabbed by the primary controller.</param>
        /// <param name="currentPrimaryGrabbingObject">The Interact Grab script for the object that is associated with the primary controller.</param>
        /// <param name="currentSecondaryGrabbingObject">The Interact Grab script for the object that is associated with the secondary controller.</param>
        /// <param name="primaryGrabPoint">The point on the object where the primary controller initially grabbed the object.</param>
        /// <param name="secondaryGrabPoint">The point on the object where the secondary controller initially grabbed the object.</param>
        public override void Initialise(VRTK_InteractableObject currentGrabbdObject, VRTK_InteractGrab currentPrimaryGrabbingObject, VRTK_InteractGrab currentSecondaryGrabbingObject, Transform primaryGrabPoint, Transform secondaryGrabPoint)
        {
            base.Initialise(currentGrabbdObject, currentPrimaryGrabbingObject, currentSecondaryGrabbingObject, primaryGrabPoint, secondaryGrabPoint);
            initialScale = currentGrabbdObject.transform.localScale;
            initalLength = (grabbedObject.transform.position - secondaryGrabbingObject.transform.position).magnitude;
            initialScaleFactor = currentGrabbdObject.transform.localScale.x / initalLength;
        }

        /// <summary>
        /// The ProcessUpdate method runs in every Update on the Interactable Object whilst it is being grabbed by a secondary controller.
        /// </summary>
        public override void ProcessUpdate()
        {
            CheckForceStopDistance(ungrabDistance);
        }

        /// <summary>
        /// The ProcessFixedUpdate method runs in every FixedUpdate on the Interactable Object whilst it is being grabbed by a secondary controller and performs the scaling action.
        /// </summary>
        public override void ProcessFixedUpdate()
        {
            if (initialised)
            {
                if (uniformScaling)
                {
                    UniformScale();
                }
                else
                {
                    NonUniformScale();
                }
            }
        }

        private void ApplyScale(Vector3 newScale)
        {
            var existingScale = grabbedObject.transform.localScale;

            float finalScaleX = (lockXAxis ? existingScale.x : newScale.x);
            float finalScaleY = (lockYAxis ? existingScale.y : newScale.y);
            float finalScaleZ = (lockZAxis ? existingScale.z : newScale.z);

            if (finalScaleX > 0 && finalScaleY > 0 && finalScaleZ > 0)
            {
                grabbedObject.transform.localScale = new Vector3(finalScaleX, finalScaleY, finalScaleZ); ;
            }
        }

        private void NonUniformScale()
        {
            Vector3 initialRotatedPosition = grabbedObject.transform.rotation * grabbedObject.transform.position;
            Vector3 initialSecondGrabRotatedPosition = grabbedObject.transform.rotation * secondaryInitialGrabPoint.position;
            Vector3 currentSecondGrabRotatedPosition = grabbedObject.transform.rotation * secondaryGrabbingObject.transform.position;

            float newScaleX = CalculateAxisScale(initialRotatedPosition.x, initialSecondGrabRotatedPosition.x, currentSecondGrabRotatedPosition.x);
            float newScaleY = CalculateAxisScale(initialRotatedPosition.y, initialSecondGrabRotatedPosition.y, currentSecondGrabRotatedPosition.y);
            float newScaleZ = CalculateAxisScale(initialRotatedPosition.z, initialSecondGrabRotatedPosition.z, currentSecondGrabRotatedPosition.z);

            var newScale = new Vector3(newScaleX, newScaleY, newScaleZ) + initialScale;
            ApplyScale(newScale);
        }

        private void UniformScale()
        {
            float adjustedLength = (grabbedObject.transform.position - secondaryGrabbingObject.transform.position).magnitude;
            float adjustedScale = initialScaleFactor * adjustedLength;

            var newScale = new Vector3(adjustedScale, adjustedScale, adjustedScale);
            ApplyScale(newScale);
        }

        private float CalculateAxisScale(float centerPosition, float initialPosition, float currentPosition)
        {
            float distance = currentPosition - initialPosition;
            distance = (centerPosition < initialPosition ? distance : -distance);
            return distance;
        }
    }
}


text:
package hu.vitamas.enotesz.view;

import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;

import hu.vitamas.enotesz.model.ListRecord;

/**
 * I's class help making {@link ListView}.
 *
 * @author vitozy
 *
 */
public class ListViewHelper {

	/**
	 * Adds icon to the items of a ListVew object.
	 *
	 * @param listView the listview to concat icon
	 * @param image the icon name in images resources folder without .png extension
	 */
	public static void addIconToItems(ListView<ListRecord> listView, String image) {
		listView.setCellFactory(param -> new ListCell<ListRecord>() {
            private ImageView imageView = new ImageView();
            @Override
            public void updateItem(ListRecord rec, boolean empty) {
                super.updateItem(rec, empty);
                if (empty) {
                    setText(null);
                    setGraphic(null);
                } else {
                	imageView.setImage(new Image(ListViewHelper.class.getResource("/images/" + image + ".png").toString()));
                    setText(rec.getTitle());
                    setGraphic(imageView);
                }
            }
        });
	}
}


text:
function ZmSalesDemoZimlet() {
}

ZmSalesDemoZimlet.prototype = new ZmZimletBase();
ZmSalesDemoZimlet.prototype.constructor = ZmSalesDemoZimlet;

ZmSalesDemoZimlet.prototype.init =
function() {
	this.zimletBaseUrl = this.getResource("templates/SalesDemo.template").replace("/templates/SalesDemo.template", "");
	var model = new ZmSalesDemoItemModel(this);
	this.items = model.items;
	this._setRegExps();
};

ZmSalesDemoZimlet.prototype.toolTipPoppedUp =
function(spanElement, matchedText, context, canvas) {
	matchedText = matchedText.toLowerCase();
	var templateId = this.items[matchedText].tooltipTemplateId;
	if(templateId == "") {
		canvas.innerHTML = "This is where Tooltip data is shown";
		return;
	}
	canvas.innerHTML = AjxTemplate.expand(
			"com_zimbra_salesdemo.templates.SalesDemo#"+templateId, {zimletBaseUrl:this.zimletBaseUrl});

};

ZmSalesDemoZimlet.prototype.clicked =
function(span, matchedText) {
	matchedText = matchedText.toLowerCase();
	var item = this.items[matchedText];
	if(!item || !item.dialogTemplateId) {
		return;
	}
	var templateId = item.dialogTemplateId;
	var dialogContent = "Zimlet Dialog Content";
	if(item.dialogTemplateId != "") {
		dialogContent = AjxTemplate.expand(
			"com_zimbra_salesdemo.templates.SalesDemo#"+templateId, {zimletBaseUrl:this.zimletBaseUrl});
	}
	var msgDialog = appCtxt.getMsgDialog();
	msgDialog.setTitle(matchedText);
	msgDialog.reset();
	msgDialog.setContent(dialogContent);
	msgDialog.popup();
};

 //----------------
ZmSalesDemoZimlet.prototype.getActionMenu =
function(matchedText, span, context) {
	matchedText = matchedText.toLowerCase();
	var contextMenuObj = this.items[matchedText].contextMenuObj;
	if(contextMenuObj) {
		return this._zimletContext._contentActionMenu = contextMenuObj;
	}
	var contextMenuItems = this.items[matchedText].contextMenuItems;
	var menu = new ZmActionMenu({parent:DwtShell.getShell(window), menuItems:ZmOperation.NONE});
	var len = contextMenuItems.length;
	for(var i=0; i< len;i++){
		var item = contextMenuItems[i];
		menu.createMenuItem(id, {image:item.icon, text:item.name});
	}
	this.items[matchedText].contextMenu = menu;
	return this._zimletContext._contentActionMenu = menu;
};

/**
 * Called by the framework when generating the span for in-context link.
 *
 */
ZmSalesDemoZimlet.prototype.match =
function(line, startIndex) {
	var a = this._regexps;
	var ret = null;
	for (var i = 0; i < a.length; ++i) {
		var re = a[i];
		re.lastIndex = startIndex;
		var m = re.exec(line);
		if (m && m[0] != "") {
			if (!ret || m.index < ret.index) {
				ret = m;
				ret.matchLength = m[0].length;
				return ret;
			}
		}
	}
	return ret;
};

 /**
 *  Creates list of regular expressions to match
 */
ZmSalesDemoZimlet.prototype._setRegExps =
function() {
	this._regexps = [];
	for(var i in this.items) {
		 this._regexps.push(new RegExp(i, "ig"));
	}
};

ZmSalesDemoZimlet.prototype.generateSpan =
function(html, idx, obj, spanId, context) {
	var matchedText = obj.toLowerCase();
	var span = ZmObjectHandler.prototype.generateSpan.apply(this, arguments);
	if(this.firstItemSinceMsgOpened) {
		var item = this.items[matchedText];
		if(item && item.showToolbar) {
			this._addSalesZimletBar(matchedText, item);
			this.firstItemSinceMsgOpened = false;
		}
	}
	return span;
};

ZmSalesDemoZimlet.prototype.onMsgView =
function() {
	this.firstItemSinceMsgOpened = true;
};

//------ toolbar
ZmSalesDemoZimlet.prototype._addSalesZimletBar =
function(matchedText, item) {
	var viewId = appCtxt.getCurrentViewId();
	if (viewId == "CLV" && appCtxt.getSettings().getSetting("READING_PANE_LOCATION").value == "off") {
		setTimeout(AjxCallback.simpleClosure(this._do_addsalesZimletBar, this, "CV", matchedText, item), 1000);
	} else {
		this._do_addsalesZimletBar(viewId, matchedText, item);
	}
};

ZmSalesDemoZimlet.prototype._do_addsalesZimletBar =
function(viewId, matchedText, item) {
	this.salesZimlet_bar_expanded = false;
	var viewType = appCtxt.getViewTypeFromId(viewId);
	if (viewType != ZmId.VIEW_MSG) {
		var infoBar = document.getElementById(["zv__MSG__",viewId,"_infoBar"].join(""));
	} else {
		var infoBar = document.getElementById(["zv__",viewId,"__MSG_infoBar"].join(""));
	}
	if (!infoBar) {
		return;
	}
	if (this._previousParentNode && document.getElementById("salesZimlet_bar_frame")) {
		this._previousParentNode.removeChild(document.getElementById("salesZimlet_bar_frame"));
	}
	this._previousParentNode = infoBar.parentNode;
	var newNode = document.createElement("div");
	newNode.style.width = "100%";
	newNode.id = "salesZimlet_bar_frame";
	newNode.innerHTML = this._getSalesBarWidgetHtml(item);
	infoBar.parentNode.insertBefore(newNode, infoBar.nextSibling);

	this.changeOpac(0, newNode.style);
	this.opacity("salesZimlet_bar_frame", 0, 100, 500);
	this._addWidgetsToSalesBar(item);
};

ZmSalesDemoZimlet.prototype._addWidgetsToSalesBar =
function(item) {
	var templateId = item.toolbarTemplateId;
	var resultsContent = "Toolbar content is displayed here";
	if(templateId != "") {
		resultsContent = AjxTemplate.expand("com_zimbra_salesdemo.templates.SalesDemo#"+templateId, {zimletBaseUrl:this.zimletBaseUrl});
	}
	var resultsDiv = document.getElementById("salesZimlet_bar_resultsMainDiv");
	 if(resultsDiv) {
		 resultsDiv.innerHTML = resultsContent;
	 }
	var btn = new DwtButton({parent:this.getShell()});
	btn.setText("Search");
	btn.setImage("Search");
	var div = document.getElementById("salesZimlet_bar_searchBtn");
	if(div) {
		div.appendChild(btn.getHtmlElement());
	}
	var toolbarButtons = item.toolbarButtons;
	if(toolbarButtons && (toolbarButtons instanceof Array)) {
		var len = toolbarButtons.length;
		for(var i=0; i < len && i < 5; i++) {
			var tbObj = toolbarButtons[i];
			var btn = new DwtButton({parent:this.getShell()});
			btn.setText(tbObj.name);
			btn.setImage(tbObj.icon);
			var div = document.getElementById("salesZimlet_bar_btn"+(i+1));
			if(div) {
				div.appendChild(btn.getHtmlElement());
			}
		}
	}

	var callback = AjxCallback.simpleClosure(this._salesZimletBarExpandBtnListener, this);
	document.getElementById("salesZimlet_bar_mainHandler").onclick = callback;
};

ZmSalesDemoZimlet.prototype._salesZimletBarExpandBtnListener =
function() {
	if (!this.salesZimlet_bar_expanded) {
		document.getElementById("salesZimlet_expandCollapseIconDiv").className = "ImgHeaderExpanded";
		document.getElementById("salesZimlet_bar_generalToolbar").style.display = "block";
		document.getElementById("salesZimlet_bar_resultsMainDiv").style.display = "block";

		document.getElementById("salesZimlet_bar_msgCell").style.display = "none";
		this.salesZimlet_bar_expanded = true;
	} else {
		document.getElementById("salesZimlet_expandCollapseIconDiv").className = "ImgHeaderCollapsed";
		document.getElementById("salesZimlet_bar_generalToolbar").style.display = "none";
		document.getElementById("salesZimlet_bar_resultsMainDiv").style.display = "none";
		document.getElementById("salesZimlet_bar_msgCell").style.display = "block";

		this.salesZimlet_bar_expanded = false;
	}
};
ZmSalesDemoZimlet.prototype._getSalesBarWidgetHtml =
function(item) {
	var toolbarIcon = item.toolbarIcon;
	if(!toolbarIcon) {
		toolbarIcon = "";
	} else {
		toolbarIcon = "Img"+toolbarIcon;
	}
	var toolbarName = item.toolbarName ? item.toolbarName : "Sales Toolbar";
	var html = new Array();
	var i = 0;

	html[i++] = "
";
	html[i++] = "

";
	html[i++] = ["

	",
		"

		",
		"","
","	",
		"	",toolbarName,"	",
		"

	"].join("");
	html[i++] = "";
	html[i++] = "
";
	html[i++] = "
";
	html[i++] = "
<input type=text id='salesZimlet_bar_searchField' />		";
	html[i++] = "

";
	html[i++] = "

";
	html[i++] = "
";
	html[i++] = "
";
	//html[i++] = this._getNoSearchResultSalesoundHtml();
	html[i++] = "
";
	return html.join("");
};

ZmSalesDemoZimlet.prototype.opacity =
function(id, opacStart, opacEnd, millisec) {
	//speed for each frame
	var speed = Math.round(millisec / 100);
	var timer = 0;
	var styleObj = document.getElementById(id).style;
	//determine the direction for the blending, if start and end are the same nothing happens
	if (opacStart > opacEnd) {
		for (i = opacStart; i >= opacEnd; i--) {
			setTimeout(AjxCallback.simpleClosure(this.changeOpac, this, i, styleObj), (timer * speed));
			timer++;
		}
	} else if (opacStart < opacEnd) {
		for (i = opacStart; i <= opacEnd; i++)
		{
			setTimeout(AjxCallback.simpleClosure(this.changeOpac, this, i, styleObj), (timer * speed));
			timer++;
		}
	}
};

//change the opacity for different browsers
ZmSalesDemoZimlet.prototype.changeOpac =
function(opacity, styleObj) {
	styleObj.opacity = (opacity / 100);
	styleObj.MozOpacity = (opacity / 100);
	styleObj.KhtmlOpacity = (opacity / 100);
	styleObj.filter = "alpha(opacity=" + opacity + ")";
};


text:
<?xml version="1.0" encoding="UTF-8"?>
<ivy-module version="2.0" xmlns:e="http://ant.apache.org/ivy/extra">
	<info organisation="com.typesafe.sbtrc" module="sbt-rc-ui-interface-0-13" revision="1.0-c50ddab5e1332398049a2a649261e1ca24577479" status="release" publication="20140812134846">
		<description>
		sbt-rc-ui-interface-0-13
		</description>
	</info>
	<configurations>
		<conf name="compile" visibility="public" description=""/>
		<conf name="runtime" visibility="public" description="" extends="compile"/>
		<conf name="test" visibility="public" description="" extends="runtime"/>
		<conf name="provided" visibility="public" description=""/>
		<conf name="optional" visibility="public" description=""/>

		<conf name="sources" visibility="public" description=""/>
		<conf name="docs" visibility="public" description=""/>
		<conf name="pom" visibility="public" description=""/>
	</configurations>
	<publications>
		<artifact name="sbt-rc-ui-interface-0-13" type="jar" ext="jar" conf="compile"/>
		<artifact name="sbt-rc-ui-interface-0-13" type="src" ext="jar" conf="sources" e:classifier="sources"/>
	</publications>
	<dependencies>
		<dependency org="org.scala-sbt" name="sbt" rev="0.13.5" conf="provided->default(compile)"/>
		<dependency org="org.scala-lang" name="scala-library" rev="2.10.4" conf="provided->default(compile)"/>
		<dependency org="com.novocode" name="junit-interface" rev="0.7" conf="test->default(compile)"/>
		<exclude org="org.scala-lang" module="scala-library" artifact="*" type="jar" ext="*" matcher="exact"/>
		<exclude org="org.scala-lang" module="scala-compiler" artifact="*" type="jar" ext="*" matcher="exact"/>
		<override org="org.scala-lang" module="scala-library" matcher="exact" rev="2.10.4"/>
		<override org="org.scala-lang" module="scala-compiler" matcher="exact" rev="2.10.4"/>
	</dependencies>
</ivy-module>


text: Reddit Client written in Kotlin. [Work in Progress]


text:
var loadingTextInterval;
var waitingForDataInterval;

function showHome(){
	console.log("showing home");
	$("#screen").fadeOut(0);
	clearInterval(loadingTextInterval);
	clearInterval(waitingForDataInterval);
	$("#screen").html(' ');
	$("#screen").load("home.html");
	$("#screen").css({"visibility":"visible"});
	$("#screen").fadeIn(1000);
}

function checkForData(){

	if(localStorage.getItem("ServerIP") == null){
		showSettings();
	}

	var iteratePostitionLoading = 0;
	var loadingTextInterval = setInterval(function(){
		var loadingText = ["Welcome...", "We are currently searching your directories.", "This may take a while, depending on the ammount.", "Please wait."];

		if(iteratePostitionLoading > (loadingText.length - 1)){
			iteratePostitionLoading = 0;
		}
		$("#loadingText").hide();

		$("#loadingText").html(loadingText[iteratePostitionLoading]);

		$("#loadingText").fadeIn(2500);

		$("#loadingText").fadeOut(2500);

		iteratePostitionLoading++;

	}, 5000);
	var waitingForDataInterval = setInterval(function(){
		if(sessionStorage.finishedReceiving == "true"){

			clearInterval(loadingTextInterval);
			$("#loader").html(' ');

			$(document).ready(function() {
			  var htmlCodeDesk = "";
			  var htmlCodeMob = "";
			  var noCoverDesk = "";
			  var noCoverMob = "";
			  $.each(series, function(index, val){
			  	if(val.info.Response == "True"){

			  		var imageUrl = val.info.Poster.replace("http://ia.media-imdb.com/images/M", "https://images-na.ssl-images-amazon.com/images/M");
			  		if(imageUrl.indexOf("N/A") > -1){
			  			imageUrl = "/img/cover.png";
			  			var desk = '\

\
					                \

' + val.info.Title + '
\

\
				              		';
				    	var mob = '

' + val.info.Title + '

';
			  			noCoverMob = noCoverMob + mob;
			  			noCoverDesk = noCoverDesk + desk;
			  		} else {
			  			var desk = '\

\
					                \

' + val.info.Title + '
\

\
				              		';
				    	var mob = '

' + val.info.Title + '

';
			  			htmlCodeDesk = htmlCodeDesk + desk;
				    	htmlCodeMob = htmlCodeMob + mob;
			  		}

				}
			  });
			  	$('#sposters-desk').html(htmlCodeDesk);
			  	$('#sposters-mob').html(htmlCodeMob);
			  	$('#snoposters-desk').html(noCoverDesk);
			  	$('#snoposters-mob').html(noCoverMob);

			  	var htmlCodeDesk = "";
				  var htmlCodeMob = "";
				  var noCoverDesk = "";
				  var noCoverMob = "";
				  $.each(movies, function(index, val){
				  	if(val.info.Response == "True"){

				  		var imageUrl = val.info.Poster.replace("http://ia.media-imdb.com/images/M", "https://images-na.ssl-images-amazon.com/images/M");
				  		if(imageUrl.indexOf("N/A") > -1){
				  			imageUrl = "/img/cover.png";
				  			var desk = '\

\
						                \

' + val.info.Title + '
\

\
					              		';
					    	var mob = '

' + val.info.Title + '

';
				  			noCoverMob = noCoverMob + mob;
				  			noCoverDesk = noCoverDesk + desk;
				  		} else {
				  			var desk = '
\
						                \

' + val.info.Title + '
\

';
					    	var mob = '

' + val.info.Title + '

';
				  			htmlCodeDesk = htmlCodeDesk + desk;
					    	htmlCodeMob = htmlCodeMob + mob;
				  		}

					}
				  });
				  	$('#mposters-desk').html(htmlCodeDesk);
				  	$('#mposters-mob').html(htmlCodeMob);
				  	$('#mnoposters-desk').html(noCoverDesk);
				  	$('#mnoposters-mob').html(noCoverMob);
			  });

			$("#movies").fadeIn();
			$("#series").fadeIn();
			clearInterval(waitingForDataInterval);
		} else {
			if(sessionStorage.parsing == "true"){
				var totalFiles = parseInt(sessionStorage.totalFiles);
				var parsedFiles = parseInt(sessionStorage.parsedFiles);
				var calculatePercentage = Math.round((parsedFiles / totalFiles) * 100);
				if(calculatePercentage >= 0){
					$("#loaderBar").show();
					$("#percentageFinished").show();
				} else {
					$("#loaderBar").hide();
					$("#percentageFinished").hide();
				}

				$("#loaderBar").css( "width", calculatePercentage + "%" );
				$("#percentageFinished").html("PARSING: " + calculatePercentage + '%');

			} else if(sessionStorage.receiving == "true"){
				var totalToReceive = parseInt(sessionStorage.totalFound);
				var received = parseInt(sessionStorage.totalSend);
				var calculatePercentage = Math.round((received / totalToReceive) * 100);
				if(calculatePercentage >= 0){
					$("#loaderBar").show();
					$("#percentageFinished").show();
				} else {
					$("#loaderBar").hide();
					$("#percentageFinished").hide();
				}

				$("#loaderBar").css( "width", calculatePercentage + "%" );
				$("#percentageFinished").html("RECEIVING: " + calculatePercentage + '%');

				if(calculatePercentage >= 100){
					sessionStorage.finishedReceiving = true;
				}
			}

		}
	}, 100);

	setInterval(function(){

		if(sessionStorage.cannotConnect == "true"){
			$('#noconnection').show();
			$("#loader").hide();
			$("#loaderBar").hide();
			$("#percentageFinished").hide();
		} else {
			$("#loader").show();
			$("#loaderBar").show();
			$("#percentageFinished").show();
			$('#noconnection').hide();
		}
	}, 500);

}


text:
module Azure::ServiceFabric::V6_3_0_9
  module Models
    #
    # Describes the mechanism for performing a scaling operation.
    #
    class ScalingMechanismDescription

      include MsRestAzure

      @@discriminatorMap = Hash.new
      @@discriminatorMap["PartitionInstanceCount"] = "PartitionInstanceCountScaleMechanism"
      @@discriminatorMap["AddRemoveIncrementalNamedPartition"] = "AddRemoveIncrementalNamedPartitionScalingMechanism"

      def initialize
        @Kind = "ScalingMechanismDescription"
      end

      attr_accessor :Kind

      #
      # Mapper for ScalingMechanismDescription class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'ScalingMechanismDescription',
          type: {
            name: 'Composite',
            polymorphic_discriminator: 'Kind',
            uber_parent: 'ScalingMechanismDescription',
            class_name: 'ScalingMechanismDescription',
            model_properties: {
            }
          }
        }
      end
    end
  end
end


text:
#ifndef NRF_GPIOTE_H__
#define NRF_GPIOTE_H__

#include "nrf_peripherals.h"
#include "nrf.h"
#include <stdint.h>
#include <stddef.h>
#include <stdbool.h>

#ifdef __cplusplus
extern "C" {
#endif

#ifdef GPIOTE_CONFIG_PORT_Msk
#define GPIOTE_CONFIG_PORT_PIN_Msk (GPIOTE_CONFIG_PORT_Msk | GPIOTE_CONFIG_PSEL_Msk)
#else
#define GPIOTE_CONFIG_PORT_PIN_Msk GPIOTE_CONFIG_PSEL_Msk
#endif
/**
* @defgroup nrf_gpiote_abs GPIOTE abstraction
* @{
* @ingroup nrf_gpiote
* @brief GPIOTE abstraction for configuration of channels.
*/

 /**
 * @enum nrf_gpiote_polarity_t
 * @brief Polarity for the GPIOTE channel.
 */
typedef enum
{
  NRF_GPIOTE_POLARITY_LOTOHI = GPIOTE_CONFIG_POLARITY_LoToHi,       ///<  Low to high.
  NRF_GPIOTE_POLARITY_HITOLO = GPIOTE_CONFIG_POLARITY_HiToLo,       ///<  High to low.
  NRF_GPIOTE_POLARITY_TOGGLE = GPIOTE_CONFIG_POLARITY_Toggle        ///<  Toggle.
} nrf_gpiote_polarity_t;

 /**
 * @enum nrf_gpiote_outinit_t
 * @brief Initial output value for the GPIOTE channel.
 */
typedef enum
{
  NRF_GPIOTE_INITIAL_VALUE_LOW  = GPIOTE_CONFIG_OUTINIT_Low,       ///<  Low to high.
  NRF_GPIOTE_INITIAL_VALUE_HIGH = GPIOTE_CONFIG_OUTINIT_High       ///<  High to low.
} nrf_gpiote_outinit_t;

/**
 * @brief Tasks.
 */
typedef enum /*lint -save -e30 -esym(628,__INTADDR__) */
{
    NRF_GPIOTE_TASKS_OUT_0     = offsetof(NRF_GPIOTE_Type, TASKS_OUT[0]), /**< Out task 0.*/
    NRF_GPIOTE_TASKS_OUT_1     = offsetof(NRF_GPIOTE_Type, TASKS_OUT[1]), /**< Out task 1.*/
    NRF_GPIOTE_TASKS_OUT_2     = offsetof(NRF_GPIOTE_Type, TASKS_OUT[2]), /**< Out task 2.*/
    NRF_GPIOTE_TASKS_OUT_3     = offsetof(NRF_GPIOTE_Type, TASKS_OUT[3]), /**< Out task 3.*/
#if (GPIOTE_CH_NUM > 4) || defined(__SDK_DOXYGEN__)
    NRF_GPIOTE_TASKS_OUT_4     = offsetof(NRF_GPIOTE_Type, TASKS_OUT[4]), /**< Out task 4.*/
    NRF_GPIOTE_TASKS_OUT_5     = offsetof(NRF_GPIOTE_Type, TASKS_OUT[5]), /**< Out task 5.*/
    NRF_GPIOTE_TASKS_OUT_6     = offsetof(NRF_GPIOTE_Type, TASKS_OUT[6]), /**< Out task 6.*/
    NRF_GPIOTE_TASKS_OUT_7     = offsetof(NRF_GPIOTE_Type, TASKS_OUT[7]), /**< Out task 7.*/
#endif
#if defined(GPIOTE_FEATURE_SET_PRESENT) || defined(__SDK_DOXYGEN__)
    NRF_GPIOTE_TASKS_SET_0     = offsetof(NRF_GPIOTE_Type, TASKS_SET[0]), /**< Set task 0.*/
    NRF_GPIOTE_TASKS_SET_1     = offsetof(NRF_GPIOTE_Type, TASKS_SET[1]), /**< Set task 1.*/
    NRF_GPIOTE_TASKS_SET_2     = offsetof(NRF_GPIOTE_Type, TASKS_SET[2]), /**< Set task 2.*/
    NRF_GPIOTE_TASKS_SET_3     = offsetof(NRF_GPIOTE_Type, TASKS_SET[3]), /**< Set task 3.*/
    NRF_GPIOTE_TASKS_SET_4     = offsetof(NRF_GPIOTE_Type, TASKS_SET[4]), /**< Set task 4.*/
    NRF_GPIOTE_TASKS_SET_5     = offsetof(NRF_GPIOTE_Type, TASKS_SET[5]), /**< Set task 5.*/
    NRF_GPIOTE_TASKS_SET_6     = offsetof(NRF_GPIOTE_Type, TASKS_SET[6]), /**< Set task 6.*/
    NRF_GPIOTE_TASKS_SET_7     = offsetof(NRF_GPIOTE_Type, TASKS_SET[7]), /**< Set task 7.*/
#endif
#if defined(GPIOTE_FEATURE_CLR_PRESENT) || defined(__SDK_DOXYGEN__)
    NRF_GPIOTE_TASKS_CLR_0     = offsetof(NRF_GPIOTE_Type, TASKS_CLR[0]), /**< Clear task 0.*/
    NRF_GPIOTE_TASKS_CLR_1     = offsetof(NRF_GPIOTE_Type, TASKS_CLR[1]), /**< Clear task 1.*/
    NRF_GPIOTE_TASKS_CLR_2     = offsetof(NRF_GPIOTE_Type, TASKS_CLR[2]), /**< Clear task 2.*/
    NRF_GPIOTE_TASKS_CLR_3     = offsetof(NRF_GPIOTE_Type, TASKS_CLR[3]), /**< Clear task 3.*/
    NRF_GPIOTE_TASKS_CLR_4     = offsetof(NRF_GPIOTE_Type, TASKS_CLR[4]), /**< Clear task 4.*/
    NRF_GPIOTE_TASKS_CLR_5     = offsetof(NRF_GPIOTE_Type, TASKS_CLR[5]), /**< Clear task 5.*/
    NRF_GPIOTE_TASKS_CLR_6     = offsetof(NRF_GPIOTE_Type, TASKS_CLR[6]), /**< Clear task 6.*/
    NRF_GPIOTE_TASKS_CLR_7     = offsetof(NRF_GPIOTE_Type, TASKS_CLR[7]), /**< Clear task 7.*/
#endif
    /*lint -restore*/
} nrf_gpiote_tasks_t;

/**
 * @brief Events.
 */
typedef enum /*lint -save -e30 -esym(628,__INTADDR__) */
{
    NRF_GPIOTE_EVENTS_IN_0     = offsetof(NRF_GPIOTE_Type, EVENTS_IN[0]), /**< In event 0.*/
    NRF_GPIOTE_EVENTS_IN_1     = offsetof(NRF_GPIOTE_Type, EVENTS_IN[1]), /**< In event 1.*/
    NRF_GPIOTE_EVENTS_IN_2     = offsetof(NRF_GPIOTE_Type, EVENTS_IN[2]), /**< In event 2.*/
    NRF_GPIOTE_EVENTS_IN_3     = offsetof(NRF_GPIOTE_Type, EVENTS_IN[3]), /**< In event 3.*/
#if (GPIOTE_CH_NUM > 4) || defined(__SDK_DOXYGEN__)
    NRF_GPIOTE_EVENTS_IN_4     = offsetof(NRF_GPIOTE_Type, EVENTS_IN[4]), /**< In event 4.*/
    NRF_GPIOTE_EVENTS_IN_5     = offsetof(NRF_GPIOTE_Type, EVENTS_IN[5]), /**< In event 5.*/
    NRF_GPIOTE_EVENTS_IN_6     = offsetof(NRF_GPIOTE_Type, EVENTS_IN[6]), /**< In event 6.*/
    NRF_GPIOTE_EVENTS_IN_7     = offsetof(NRF_GPIOTE_Type, EVENTS_IN[7]), /**< In event 7.*/
#endif
    NRF_GPIOTE_EVENTS_PORT     = offsetof(NRF_GPIOTE_Type, EVENTS_PORT), /**<  Port event.*/
    /*lint -restore*/
} nrf_gpiote_events_t;

/**
 * @enum nrf_gpiote_int_t
 * @brief GPIOTE interrupts.
 */
typedef enum
{
    NRF_GPIOTE_INT_IN0_MASK  = GPIOTE_INTENSET_IN0_Msk,  /**< GPIOTE interrupt from IN0. */
    NRF_GPIOTE_INT_IN1_MASK  = GPIOTE_INTENSET_IN1_Msk,  /**< GPIOTE interrupt from IN1. */
    NRF_GPIOTE_INT_IN2_MASK  = GPIOTE_INTENSET_IN2_Msk,  /**< GPIOTE interrupt from IN2. */
    NRF_GPIOTE_INT_IN3_MASK  = GPIOTE_INTENSET_IN3_Msk,  /**< GPIOTE interrupt from IN3. */
#if (GPIOTE_CH_NUM > 4) || defined(__SDK_DOXYGEN__)
    NRF_GPIOTE_INT_IN4_MASK  = GPIOTE_INTENSET_IN4_Msk,  /**< GPIOTE interrupt from IN4. */
    NRF_GPIOTE_INT_IN5_MASK  = GPIOTE_INTENSET_IN5_Msk,  /**< GPIOTE interrupt from IN5. */
    NRF_GPIOTE_INT_IN6_MASK  = GPIOTE_INTENSET_IN6_Msk,  /**< GPIOTE interrupt from IN6. */
    NRF_GPIOTE_INT_IN7_MASK  = GPIOTE_INTENSET_IN7_Msk,  /**< GPIOTE interrupt from IN7. */
#endif
    NRF_GPIOTE_INT_PORT_MASK = (int)GPIOTE_INTENSET_PORT_Msk, /**< GPIOTE interrupt from PORT event. */
} nrf_gpiote_int_t;

#define NRF_GPIOTE_INT_IN_MASK (NRF_GPIOTE_INT_IN0_MASK | NRF_GPIOTE_INT_IN1_MASK |\
                                NRF_GPIOTE_INT_IN2_MASK | NRF_GPIOTE_INT_IN3_MASK)
#if (GPIOTE_CH_NUM > 4)
#undef NRF_GPIOTE_INT_IN_MASK
#define NRF_GPIOTE_INT_IN_MASK (NRF_GPIOTE_INT_IN0_MASK | NRF_GPIOTE_INT_IN1_MASK |\
                                NRF_GPIOTE_INT_IN2_MASK | NRF_GPIOTE_INT_IN3_MASK |\
                                NRF_GPIOTE_INT_IN4_MASK | NRF_GPIOTE_INT_IN5_MASK |\
                                NRF_GPIOTE_INT_IN6_MASK | NRF_GPIOTE_INT_IN7_MASK)
#endif

/**
 * @brief Function for activating a specific GPIOTE task.
 *
 * @param[in]  task Task.
 */
__STATIC_INLINE void nrf_gpiote_task_set(nrf_gpiote_tasks_t task);

/**
 * @brief Function for getting the address of a specific GPIOTE task.
 *
 * @param[in] task Task.
 *
 * @returns Address.
 */
__STATIC_INLINE uint32_t nrf_gpiote_task_addr_get(nrf_gpiote_tasks_t task);

/**
 * @brief Function for getting the state of a specific GPIOTE event.
 *
 * @param[in] event Event.
 */
__STATIC_INLINE bool nrf_gpiote_event_is_set(nrf_gpiote_events_t event);

/**
 * @brief Function for clearing a specific GPIOTE event.
 *
 * @param[in] event Event.
 */
__STATIC_INLINE void nrf_gpiote_event_clear(nrf_gpiote_events_t event);

/**
 * @brief Function for getting the address of a specific GPIOTE event.
 *
 * @param[in] event Event.
 *
 * @return Address
 */
__STATIC_INLINE uint32_t nrf_gpiote_event_addr_get(nrf_gpiote_events_t event);

/**@brief Function for enabling interrupts.
 *
 * @param[in]  mask          Interrupt mask to be enabled.
 */
__STATIC_INLINE void nrf_gpiote_int_enable(uint32_t mask);

/**@brief Function for disabling interrupts.
 *
 * @param[in]  mask          Interrupt mask to be disabled.
 */
__STATIC_INLINE void nrf_gpiote_int_disable(uint32_t mask);

/**@brief Function for checking if interrupts are enabled.
 *
 * @param[in]  mask          Mask of interrupt flags to check.
 *
 * @return                   Mask with enabled interrupts.
 */
__STATIC_INLINE uint32_t nrf_gpiote_int_is_enabled(uint32_t mask);

/**@brief Function for enabling a GPIOTE event.
 *
 * @param[in]  idx        Task-Event index.
 */
__STATIC_INLINE void nrf_gpiote_event_enable(uint32_t idx);

/**@brief Function for disabling a GPIOTE event.
 *
 * @param[in]  idx        Task-Event index.
 */
__STATIC_INLINE void nrf_gpiote_event_disable(uint32_t idx);

/**@brief Function for configuring a GPIOTE event.
 *
 * @param[in]  idx        Task-Event index.
 * @param[in]  pin        Pin associated with event.
 * @param[in]  polarity   Transition that should generate an event.
 */
__STATIC_INLINE void nrf_gpiote_event_configure(uint32_t idx, uint32_t pin,
                                                nrf_gpiote_polarity_t polarity);

/**@brief Function for getting the pin associated with a GPIOTE event.
 *
 * @param[in]  idx        Task-Event index.
 *
 * @return Pin number.
 */
__STATIC_INLINE uint32_t nrf_gpiote_event_pin_get(uint32_t idx);

/**@brief Function for getting the polarity associated with a GPIOTE event.
 *
 * @param[in]  idx        Task-Event index.
 *
 * @return Polarity.
 */
__STATIC_INLINE nrf_gpiote_polarity_t nrf_gpiote_event_polarity_get(uint32_t idx);

/**@brief Function for enabling a GPIOTE task.
 *
 * @param[in]  idx        Task-Event index.
 */
__STATIC_INLINE void nrf_gpiote_task_enable(uint32_t idx);

/**@brief Function for disabling a GPIOTE task.
 *
 * @param[in]  idx        Task-Event index.
 */
__STATIC_INLINE void nrf_gpiote_task_disable(uint32_t idx);

/**@brief Function for configuring a GPIOTE task.
 * @note  Function is not configuring mode field so task is disabled after this function is called.
 *
 * @param[in]  idx        Task-Event index.
 * @param[in]  pin        Pin associated with event.
 * @param[in]  polarity   Transition that should generate an event.
 * @param[in]  init_val   Initial value of the pin.
 */
__STATIC_INLINE void nrf_gpiote_task_configure(uint32_t idx, uint32_t pin,
                                               nrf_gpiote_polarity_t polarity,
                                               nrf_gpiote_outinit_t  init_val);

/**@brief Function for forcing a specific state on the pin connected to GPIOTE.
 *
 * @param[in]  idx        Task-Event index.
 * @param[in]  init_val   Pin state.
 */
__STATIC_INLINE void nrf_gpiote_task_force(uint32_t idx, nrf_gpiote_outinit_t init_val);

/**@brief Function for resetting a GPIOTE task event configuration to the default state.
 *
 * @param[in]  idx        Task-Event index.
 */
__STATIC_INLINE void nrf_gpiote_te_default(uint32_t idx);

#ifndef SUPPRESS_INLINE_IMPLEMENTATION
__STATIC_INLINE void nrf_gpiote_task_set(nrf_gpiote_tasks_t task)
{
    *(__IO uint32_t *)((uint32_t)NRF_GPIOTE + task) = 0x1UL;
}

__STATIC_INLINE uint32_t nrf_gpiote_task_addr_get(nrf_gpiote_tasks_t task)
{
    return ((uint32_t)NRF_GPIOTE + task);
}

__STATIC_INLINE bool nrf_gpiote_event_is_set(nrf_gpiote_events_t event)
{
    return (*(uint32_t *)nrf_gpiote_event_addr_get(event) == 0x1UL) ? true : false;
}

__STATIC_INLINE void nrf_gpiote_event_clear(nrf_gpiote_events_t event)
{
    *(uint32_t *)nrf_gpiote_event_addr_get(event) = 0;
#if __CORTEX_M == 0x04
    volatile uint32_t dummy = *((volatile uint32_t *)nrf_gpiote_event_addr_get(event));
    (void)dummy;
#endif
}

__STATIC_INLINE uint32_t nrf_gpiote_event_addr_get(nrf_gpiote_events_t event)
{
    return ((uint32_t)NRF_GPIOTE + event);
}

__STATIC_INLINE void nrf_gpiote_int_enable(uint32_t mask)
{
    NRF_GPIOTE->INTENSET = mask;
}

__STATIC_INLINE void nrf_gpiote_int_disable(uint32_t mask)
{
    NRF_GPIOTE->INTENCLR = mask;
}

__STATIC_INLINE uint32_t nrf_gpiote_int_is_enabled(uint32_t mask)
{
    return (NRF_GPIOTE->INTENSET & mask);
}

__STATIC_INLINE void nrf_gpiote_event_enable(uint32_t idx)
{
   NRF_GPIOTE->CONFIG[idx] |= GPIOTE_CONFIG_MODE_Event;
}

__STATIC_INLINE void nrf_gpiote_event_disable(uint32_t idx)
{
   NRF_GPIOTE->CONFIG[idx] &= ~GPIOTE_CONFIG_MODE_Event;
}

__STATIC_INLINE void nrf_gpiote_event_configure(uint32_t idx, uint32_t pin, nrf_gpiote_polarity_t polarity)
{
  NRF_GPIOTE->CONFIG[idx] &= ~(GPIOTE_CONFIG_PORT_PIN_Msk | GPIOTE_CONFIG_POLARITY_Msk);
  NRF_GPIOTE->CONFIG[idx] |= ((pin << GPIOTE_CONFIG_PSEL_Pos) & GPIOTE_CONFIG_PORT_PIN_Msk) |
                              ((polarity << GPIOTE_CONFIG_POLARITY_Pos) & GPIOTE_CONFIG_POLARITY_Msk);
}

__STATIC_INLINE uint32_t nrf_gpiote_event_pin_get(uint32_t idx)
{
    return ((NRF_GPIOTE->CONFIG[idx] & GPIOTE_CONFIG_PORT_PIN_Msk) >> GPIOTE_CONFIG_PSEL_Pos);
}

__STATIC_INLINE nrf_gpiote_polarity_t nrf_gpiote_event_polarity_get(uint32_t idx)
{
    return (nrf_gpiote_polarity_t)((NRF_GPIOTE->CONFIG[idx] & GPIOTE_CONFIG_POLARITY_Msk) >> GPIOTE_CONFIG_POLARITY_Pos);
}

__STATIC_INLINE void nrf_gpiote_task_enable(uint32_t idx)
{
    uint32_t final_config = NRF_GPIOTE->CONFIG[idx] | GPIOTE_CONFIG_MODE_Task;
#ifdef NRF51
    /* Workaround for the OUTINIT PAN. When nrf_gpiote_task_config() is called a glitch happens
    on the GPIO if the GPIO in question is already assigned to GPIOTE and the pin is in the
    correct state in GPIOTE but not in the OUT register. */
    /* Configure channel to not existing, not connected to the pin, and configure as a tasks that will set it to proper level */
    NRF_GPIOTE->CONFIG[idx] = final_config | (((31) << GPIOTE_CONFIG_PSEL_Pos) & GPIOTE_CONFIG_PORT_PIN_Msk);
    __NOP();
    __NOP();
    __NOP();
#endif
    NRF_GPIOTE->CONFIG[idx] = final_config;
}

__STATIC_INLINE void nrf_gpiote_task_disable(uint32_t idx)
{
    NRF_GPIOTE->CONFIG[idx] &= ~GPIOTE_CONFIG_MODE_Task;
}

__STATIC_INLINE void nrf_gpiote_task_configure(uint32_t idx, uint32_t pin,
                                                nrf_gpiote_polarity_t polarity,
                                                nrf_gpiote_outinit_t  init_val)
{
  NRF_GPIOTE->CONFIG[idx] &= ~(GPIOTE_CONFIG_PORT_PIN_Msk |
                               GPIOTE_CONFIG_POLARITY_Msk |
                               GPIOTE_CONFIG_OUTINIT_Msk);

  NRF_GPIOTE->CONFIG[idx] |= ((pin << GPIOTE_CONFIG_PSEL_Pos) & GPIOTE_CONFIG_PORT_PIN_Msk) |
                             ((polarity << GPIOTE_CONFIG_POLARITY_Pos) & GPIOTE_CONFIG_POLARITY_Msk) |
                             ((init_val << GPIOTE_CONFIG_OUTINIT_Pos) & GPIOTE_CONFIG_OUTINIT_Msk);
}

__STATIC_INLINE void nrf_gpiote_task_force(uint32_t idx, nrf_gpiote_outinit_t init_val)
{
    NRF_GPIOTE->CONFIG[idx] = (NRF_GPIOTE->CONFIG[idx] & ~GPIOTE_CONFIG_OUTINIT_Msk)
                              | ((init_val << GPIOTE_CONFIG_OUTINIT_Pos) & GPIOTE_CONFIG_OUTINIT_Msk);
}

__STATIC_INLINE void nrf_gpiote_te_default(uint32_t idx)
{
    NRF_GPIOTE->CONFIG[idx] = 0;
}
#endif //SUPPRESS_INLINE_IMPLEMENTATION
/** @} */

#ifdef __cplusplus
}
#endif

#endif