text:
package org.apache.cordova.media;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaRecorder;
import android.os.Environment;
import android.os.Build;

import org.apache.cordova.LOG;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.util.LinkedList;

/**
 * This class implements the audio playback and recording capabilities used by Cordova.
 * It is called by the AudioHandler Cordova class.
 * Only one file can be played or recorded per class instance.
 *
 * Local audio files must reside in one of two places:
 *      android_asset:      file name must start with /android_asset/sound.mp3
 *      sdcard:             file name is just sound.mp3
 */
public class AudioPlayer implements OnCompletionListener, OnPreparedListener, OnErrorListener {

    // AudioPlayer modes
    public enum MODE { NONE, PLAY, RECORD };

    // AudioPlayer states
    public enum STATE { MEDIA_NONE,
                        MEDIA_STARTING,
                        MEDIA_RUNNING,
                        MEDIA_PAUSED,
                        MEDIA_STOPPED,
                        MEDIA_LOADING
                      };

    private static final String LOG_TAG = "AudioPlayer";

    // AudioPlayer message ids
    private static int MEDIA_STATE = 1;
    private static int MEDIA_DURATION = 2;
    private static int MEDIA_POSITION = 3;
    private static int MEDIA_ERROR = 9;

    // Media error codes
    private static int MEDIA_ERR_NONE_ACTIVE    = 0;
    private static int MEDIA_ERR_ABORTED        = 1;
//    private static int MEDIA_ERR_NETWORK        = 2;
//    private static int MEDIA_ERR_DECODE         = 3;
//    private static int MEDIA_ERR_NONE_SUPPORTED = 4;

    private AudioHandler handler;           // The AudioHandler object
    private Context context;                // The Application Context object
    private String id;                      // The id of this player (used to identify Media object in JavaScript)
    private MODE mode = MODE.NONE;          // Playback or Recording mode
    private STATE state = STATE.MEDIA_NONE; // State of recording or playback

    private String audioFile = null;        // File name to play or record to
    private float duration = -1;            // Duration of audio

    private MediaRecorder recorder = null;  // Audio recording object
    private LinkedList<String> tempFiles = null; // Temporary recording file name
    private String tempFile = null;

    private MediaPlayer player = null;      // Audio player object
    private boolean prepareOnly = true;     // playback after file prepare flag
    private int seekOnPrepared = 0;     // seek to this location once media is prepared
    private float setRateOnPrepared = -1;

    /**
     * Constructor.
     *
     * @param handler           The audio handler object
     * @param id                The id of this audio player
     */
    public AudioPlayer(AudioHandler handler, String id, String file) {
        this.handler = handler;
        context = handler.getApplicationContext();
        this.id = id;
        this.audioFile = file;
        this.tempFiles = new LinkedList<String>();

    }

    /**
     * Creates an audio file path from the provided fileName or creates a new temporary file path.
     *
     * @param fileName the audio file name, if null a temporary 3gp file name is provided
     * @return String
     */
    private String createAudioFilePath(String fileName) {
        File dir = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)
            ? context.getExternalFilesDir(null)
            : context.getCacheDir();

        fileName = (fileName == null || fileName.isEmpty())
            ? String.format("tmprecording-%d.3gp", System.currentTimeMillis())
            : fileName;

        return dir.getAbsolutePath() + File.separator + fileName;
    }

    /**
     * Destroy player and stop audio playing or recording.
     */
    public void destroy() {
        // Stop any play or record
        if (this.player != null) {
            if ((this.state == STATE.MEDIA_RUNNING) || (this.state == STATE.MEDIA_PAUSED)) {
                this.player.stop();
                this.setState(STATE.MEDIA_STOPPED);
            }
            this.player.release();
            this.player = null;
        }
        if (this.recorder != null) {
            if (this.state != STATE.MEDIA_STOPPED) {
                this.stopRecording(true);
            }
            this.recorder.release();
            this.recorder = null;
        }
    }

    /**
     * Start recording the specified file.
     *
     * @param file              The name of the file
     */
    public void startRecording(String file) {
        String errorMessage;
        switch (this.mode) {
        case PLAY:
            errorMessage = "AudioPlayer Error: Can't record in play mode.";
            sendErrorStatus(MEDIA_ERR_ABORTED, errorMessage);
            break;
        case NONE:
            this.audioFile = file;
            this.recorder = new MediaRecorder();
            this.recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            this.recorder.setOutputFormat(MediaRecorder.OutputFormat.AAC_ADTS); // RAW_AMR);
            this.recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC); //AMR_NB);
            this.tempFile = createAudioFilePath(null);
            this.recorder.setOutputFile(this.tempFile);
            try {
                this.recorder.prepare();
                this.recorder.start();
                this.setState(STATE.MEDIA_RUNNING);
                return;
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            sendErrorStatus(MEDIA_ERR_ABORTED, null);
            break;
        case RECORD:
            errorMessage = "AudioPlayer Error: Already recording.";
            sendErrorStatus(MEDIA_ERR_ABORTED, errorMessage);
        }
    }

    /**
     * Save temporary recorded file to specified name
     *
     * @param file
     */
    public void moveFile(String file) {
        /* this is a hack to save the file as the specified name */

        if (!file.startsWith("/")) {
            file = createAudioFilePath(file);
        }

        int size = this.tempFiles.size();
        LOG.d(LOG_TAG, "size = " + size);

        // only one file so just copy it
        if (size == 1) {
            String logMsg = "renaming " + this.tempFile + " to " + file;
            LOG.d(LOG_TAG, logMsg);

            File f = new File(this.tempFile);
            if (!f.renameTo(new File(file))) {

                FileOutputStream outputStream = null;
                File outputFile = null;
                try {
                    outputFile = new File(file);
                    outputStream = new FileOutputStream(outputFile);
                    FileInputStream inputStream = null;
                    File inputFile = null;
                    try {
                        inputFile = new File(this.tempFile);
                        LOG.d(LOG_TAG,  "INPUT FILE LENGTH: " + String.valueOf(inputFile.length()) );
                        inputStream = new FileInputStream(inputFile);
                        copy(inputStream, outputStream, false);
                    } catch (Exception e) {
                        LOG.e(LOG_TAG, e.getLocalizedMessage(), e);
                   } finally {
                        if (inputStream != null) try {
                            inputStream.close();
                            inputFile.delete();
                            inputFile = null;
                        } catch (Exception e) {
                            LOG.e(LOG_TAG, e.getLocalizedMessage(), e);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (outputStream != null) try {
                        outputStream.close();
                        LOG.d(LOG_TAG, "OUTPUT FILE LENGTH: " + String.valueOf(outputFile.length()) );
                    } catch (Exception e) {
                        LOG.e(LOG_TAG, e.getLocalizedMessage(), e);
                    }
                }
            }
        }
        // more than one file so the user must have pause recording. We'll need to concat files.
        else {
          FileOutputStream outputStream = null;
          try {
              outputStream = new FileOutputStream(new File(file));
              FileInputStream inputStream = null;
              File inputFile = null;
              for (int i = 0; i < size; i++) {
                  try {
                      inputFile = new File(this.tempFiles.get(i));
                      inputStream = new FileInputStream(inputFile);
                      copy(inputStream, outputStream, (i>0));
                  } catch(Exception e) {
                      LOG.e(LOG_TAG, e.getLocalizedMessage(), e);
                  } finally {
                      if (inputStream != null) try {
                          inputStream.close();
                          inputFile.delete();
                          inputFile = null;
                      } catch (Exception e) {
                          LOG.e(LOG_TAG, e.getLocalizedMessage(), e);
                      }
                  }
              }
          } catch(Exception e) {
              e.printStackTrace();
          } finally {
              if (outputStream != null) try {
                  outputStream.close();
              } catch (Exception e) {
                  LOG.e(LOG_TAG, e.getLocalizedMessage(), e);
              }
          }
        }
    }

    private static long copy(InputStream from, OutputStream to, boolean skipHeader)
                throws IOException {
        byte[] buf = new byte[8096];
        long total = 0;
        if (skipHeader) {
            from.skip(6);
        }
        while (true) {
            int r = from.read(buf);
            if (r == -1) {
                break;
            }
            to.write(buf, 0, r);
            total += r;
        }
        return total;
    }

    /**
     * Stop/Pause recording and save to the file specified when recording started.
     */
    public void stopRecording(boolean stop) {
        if (this.recorder != null) {
            try{
                if (this.state == STATE.MEDIA_RUNNING) {
                    this.recorder.stop();
                }
                this.recorder.reset();
                if (!this.tempFiles.contains(this.tempFile)) {
                    this.tempFiles.add(this.tempFile);
                }
                if (stop) {
                    LOG.d(LOG_TAG, "stopping recording");
                    this.setState(STATE.MEDIA_STOPPED);
                    this.moveFile(this.audioFile);
                } else {
                    LOG.d(LOG_TAG, "pause recording");
                    this.setState(STATE.MEDIA_PAUSED);
                }
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * Resume recording and save to the file specified when recording started.
     */
    public void resumeRecording() {
        startRecording(this.audioFile);
    }

    //==========================================================================
    // Playback
    //==========================================================================

    /**
     * Start or resume playing audio file.
     *
     * @param file              The name of the audio file.
     */
    public void startPlaying(String file) {
        if (this.readyPlayer(file) && this.player != null) {
            this.player.start();
            this.setState(STATE.MEDIA_RUNNING);
            this.seekOnPrepared = 0; //insures this is always reset
        } else {
            this.prepareOnly = false;
        }
    }

    /**
     * Seek or jump to a new time in the track.
     */
    public void seekToPlaying(int milliseconds) {
        if (this.readyPlayer(this.audioFile)) {
            if (milliseconds > 0) {
                this.player.seekTo(milliseconds);
            }
            LOG.d(LOG_TAG, "Send a onStatus update for the new seek");
            sendStatusChange(MEDIA_POSITION, null, (milliseconds / 1000.0f), null);
        }
        else {
            this.seekOnPrepared = milliseconds;
        }
    }

    /**
     * Pause playing.
     */
    public void pausePlaying() {

        // If playing, then pause
        if (this.state == STATE.MEDIA_RUNNING && this.player != null) {
            this.player.pause();
            this.setState(STATE.MEDIA_PAUSED);
        }
        else {
            String errorMessage = "AudioPlayer Error: pausePlaying() called during invalid state: " + this.state.ordinal();
            sendErrorStatus(MEDIA_ERR_NONE_ACTIVE, errorMessage);
        }
    }

    /**
     * Stop playing the audio file.
     */
    public void stopPlaying() {
        if ((this.state == STATE.MEDIA_RUNNING) || (this.state == STATE.MEDIA_PAUSED)) {
            this.player.pause();
            this.player.seekTo(0);
            LOG.d(LOG_TAG, "stopPlaying is calling stopped");
            this.setState(STATE.MEDIA_STOPPED);
        }
        else {
            String errorMessage = "AudioPlayer Error: stopPlaying() called during invalid state: " + this.state.ordinal();
            sendErrorStatus(MEDIA_ERR_NONE_ACTIVE, errorMessage);
        }
    }

    /**
     * Resume playing.
     */
    public void resumePlaying() {
    	this.startPlaying(this.audioFile);
    }

    /**
     * Callback to be invoked when playback of a media source has completed.
     *
     * @param player           The MediaPlayer that reached the end of the file
     */
    public void onCompletion(MediaPlayer player) {
        LOG.d(LOG_TAG, "on completion is calling stopped");
        this.setState(STATE.MEDIA_STOPPED);
    }

    /**
     * Get current position of playback.
     *
     * @return                  position in msec or -1 if not playing
     */
    public long getCurrentPosition() {
        if ((this.state == STATE.MEDIA_RUNNING) || (this.state == STATE.MEDIA_PAUSED)) {
            int curPos = this.player.getCurrentPosition();
            sendStatusChange(MEDIA_POSITION, null, (curPos / 1000.0f), null);
            return curPos;
        }
        else {
            return -1;
        }
    }

    /**
     * Determine if playback file is streaming or local.
     * It is streaming if file name starts with "http://"
     *
     * @param file              The file name
     * @return                  T=streaming, F=local
     */
    public boolean isStreaming(String file) {
        if (file.contains("http://") || file.contains("https://") || file.contains("rtsp://")) {
            return true;
        }
        else {
            return false;
        }
    }

    /**
      * Get the duration of the audio file.
      *
      * @param file             The name of the audio file.
      * @return                 The duration in msec.
      *                             -1=can't be determined
      *                             -2=not allowed
      */
    public float getDuration(String file) {

        // Can't get duration of recording
        if (this.recorder != null) {
            return (-2); // not allowed
        }

        // If audio file already loaded and started, then return duration
        if (this.player != null) {
            return this.duration;
        }

        // If no player yet, then create one
        else {
            this.prepareOnly = true;
            this.startPlaying(file);

            // This will only return value for local, since streaming
            // file hasn't been read yet.
            return this.duration;
        }
    }

    /**
     * Callback to be invoked when the media source is ready for playback.
     *
     * @param player           The MediaPlayer that is ready for playback
     */
    public void onPrepared(MediaPlayer player) {
        // Listen for playback completion
        this.player.setOnCompletionListener(this);
        // seek to any location received while not prepared
        this.seekToPlaying(this.seekOnPrepared);
        // apply any playback rate received while not prepared
        if (setRateOnPrepared >= 0)
            this.player.setPlaybackParams (this.player.getPlaybackParams().setSpeed(setRateOnPrepared));
        // If start playing after prepared
        if (!this.prepareOnly) {
            this.player.start();
            this.setState(STATE.MEDIA_RUNNING);
            this.seekOnPrepared = 0; //reset only when played
        } else {
            this.setState(STATE.MEDIA_STARTING);
        }
        // Save off duration
        this.duration = getDurationInSeconds();
        // reset prepare only flag
        this.prepareOnly = true;

        // Send status notification to JavaScript
        sendStatusChange(MEDIA_DURATION, null, this.duration, null);
    }

    /**
     * By default Android returns the length of audio in mills but we want seconds
     *
     * @return length of clip in seconds
     */
    private float getDurationInSeconds() {
        return (this.player.getDuration() / 1000.0f);
    }

    /**
     * Callback to be invoked when there has been an error during an asynchronous operation
     *  (other errors will throw exceptions at method call time).
     *
     * @param player           the MediaPlayer the error pertains to
     * @param arg1              the type of error that has occurred: (MEDIA_ERROR_UNKNOWN, MEDIA_ERROR_SERVER_DIED)
     * @param arg2              an extra code, specific to the error.
     */
    public boolean onError(MediaPlayer player, int arg1, int arg2) {
        String errorMessage = "AudioPlayer.onError(" + arg1 + ", " + arg2 + ")";

        // we don't want to send success callback
        // so we don't call setState() here
        this.state = STATE.MEDIA_STOPPED;
        this.destroy();
        // Send error notification to JavaScript
        sendErrorStatus(arg1, errorMessage);

        return false;
    }

    /**
     * Set the state and send it to JavaScript.
     *
     * @param state
     */
    private void setState(STATE state) {
        if (this.state != state) {
            sendStatusChange(MEDIA_STATE, null, (float)state.ordinal(), null);
        }
        this.state = state;
    }

    /**
     * Set the mode and send it to JavaScript.
     *
     * @param mode
     */
    private void setMode(MODE mode) {
        if (this.mode != mode) {
            //mode is not part of the expected behavior, so no notification
            //this.handler.webView.sendJavascript("cordova.require('cordova-plugin-media.Media').onStatus('" + this.id + "', " + MEDIA_STATE + ", " + mode + ");");
        }
        this.mode = mode;
    }

    /**
     * Get the audio state.
     *
     * @return int
     */
    public int getState() {
        return this.state.ordinal();
    }

    /**
     * Set the volume for audio player
     *
     * @param volume
     */
    public void setVolume(float volume) {
        if (this.player != null) {
            this.player.setVolume(volume, volume);
        } else {
            String errorMessage = "AudioPlayer Error: Cannot set volume until the audio file is initialized.";
            sendErrorStatus(MEDIA_ERR_NONE_ACTIVE, errorMessage);
        }
    }

    /**
     * attempts to put the player in play mode
     * @return true if in playmode, false otherwise
     */
    private boolean playMode() {
        switch(this.mode) {
        case NONE:
            this.setMode(MODE.PLAY);
            break;
        case PLAY:
            break;
        case RECORD:
            String errorMessage = "AudioPlayer Error: Can't play in record mode.";
            sendErrorStatus(MEDIA_ERR_ABORTED, errorMessage);
            return false; //player is not ready
        }
        return true;
    }

    /**
     * attempts to initialize the media player for playback
     * @param file the file to play
     * @return false if player not ready, reports if in wrong mode or state
     */
    private boolean readyPlayer(String file) {
        if (playMode()) {
            switch (this.state) {
                case MEDIA_NONE:
                    if (this.player == null) {
                        this.player = new MediaPlayer();
                        this.player.setOnErrorListener(this);
                    }
                    try {
                        this.loadAudioFile(file);
                    } catch (Exception e) {
                        sendErrorStatus(MEDIA_ERR_ABORTED, e.getMessage());
                    }
                    return false;
                case MEDIA_LOADING:
                    //cordova js is not aware of MEDIA_LOADING, so we send MEDIA_STARTING instead
                    LOG.d(LOG_TAG, "AudioPlayer Loading: startPlaying() called during media preparation: " + STATE.MEDIA_STARTING.ordinal());
                    this.prepareOnly = false;
                    return false;
                case MEDIA_STARTING:
                case MEDIA_RUNNING:
                case MEDIA_PAUSED:
                    return true;
                case MEDIA_STOPPED:
                    //if we are readying the same file
                    if (file!=null && this.audioFile.compareTo(file) == 0) {
                        //maybe it was recording?
                        if (player == null) {
                            this.player = new MediaPlayer();
                            this.player.setOnErrorListener(this);
                            this.prepareOnly = false;

                            try {
                                this.loadAudioFile(file);
                            } catch (Exception e) {
                                sendErrorStatus(MEDIA_ERR_ABORTED, e.getMessage());
                            }
                            return false;//we´re not ready yet
                        }
                        else {
                           //reset the audio file
                            player.seekTo(0);
                            player.pause();
                            return true;
                        }
                    } else {
                        //reset the player
                        this.player.reset();
                        try {
                            this.loadAudioFile(file);
                        } catch (Exception e) {
                            sendErrorStatus(MEDIA_ERR_ABORTED, e.getMessage());
                        }
                        //if we had to prepare the file, we won't be in the correct state for playback
                        return false;
                    }
                default:
                    String errorMessage = "AudioPlayer Error: startPlaying() called during invalid state: " + this.state;
                    sendErrorStatus(MEDIA_ERR_ABORTED, errorMessage);
            }
        }
        return false;
    }

    /**
     * load audio file
     * @throws IOException
     * @throws IllegalStateException
     * @throws SecurityException
     * @throws IllegalArgumentException
     */
    private void loadAudioFile(String file) throws IllegalArgumentException, SecurityException, IllegalStateException, IOException {
        if (this.isStreaming(file)) {
            this.player.setDataSource(file);
            this.player.setAudioStreamType(AudioManager.STREAM_MUSIC);
            //if it's a streaming file, play mode is implied
            this.setMode(MODE.PLAY);
            this.setState(STATE.MEDIA_STARTING);
            this.player.setOnPreparedListener(this);
            this.player.prepareAsync();
        }
        else {
            if (file.startsWith("/android_asset/")) {
                String f = file.substring(15);
                android.content.res.AssetFileDescriptor fd = this.handler.cordova.getActivity().getAssets().openFd(f);
                this.player.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
            }
            else {
                File fp = new File(file);
                if (fp.exists()) {
                    FileInputStream fileInputStream = new FileInputStream(file);
                    this.player.setDataSource(fileInputStream.getFD());
                    fileInputStream.close();
                }
                else {
                    this.player.setDataSource(createAudioFilePath(file));
                }
            }
                this.setState(STATE.MEDIA_STARTING);
                this.player.setOnPreparedListener(this);
                this.player.prepare();

                // Get duration
                this.duration = getDurationInSeconds();
            }
    }

    private void sendErrorStatus(int errorCode, String errorMessage) {
        sendStatusChange(MEDIA_ERROR, errorCode, null, errorMessage);
    }

    private void sendStatusChange(int messageType, Integer additionalCode, Float value, String errorMessage) {
        if (additionalCode != null && value != null) {
            throw new IllegalArgumentException("Only one of additionalCode or value can be specified, not both");
        }

        if (errorMessage != null) {
            LOG.d(LOG_TAG, errorMessage);
        }

        JSONObject statusDetails = new JSONObject();
        try {
            statusDetails.put("id", this.id);
            statusDetails.put("msgType", messageType);
            if (additionalCode != null) {
                JSONObject code = new JSONObject();
                code.put("code", additionalCode.intValue());

                if (errorMessage != null) {
                    code.put("message", errorMessage);
                }

                statusDetails.put("value", code);
            }
            else if (value != null) {
                statusDetails.put("value", value.floatValue());
            }
        } catch (JSONException e) {
            LOG.e(LOG_TAG, "Failed to create status details", e);
        }

        this.handler.sendEventMessage("status", statusDetails);
    }

    /**
     * Get current amplitude of recording.
     *
     * @return amplitude or 0 if not recording
     */
    public float getCurrentAmplitude() {
        if (this.recorder != null) {
            try{
                if (this.state == STATE.MEDIA_RUNNING) {
                    return (float) this.recorder.getMaxAmplitude() / 32762;
                }
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }
        return 0;
    }

    /**
     * Set the playback rate for the player (ignored on API < 23)
     *
     * @param volume
     */
    public void setRate(float rate) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            LOG.d(LOG_TAG, "AudioPlayer Warning: Request to set playback rate not supported on current OS version");
            return;
        }

        if (this.player != null) {
            try {
                boolean wasPlaying = this.player.isPlaying();

                this.player.setPlaybackParams(this.player.getPlaybackParams().setSpeed(rate));

                if (!wasPlaying && this.player.isPlaying()) {
                    this.player.pause();
                }
            } catch(Exception e) {
                e.printStackTrace();
            }
        } else {
            setRateOnPrepared = rate;
        }
    }
}


text:
/**
@module ember-metal
*/

import { assert } from 'ember-metal/debug';
import isEnabled from 'ember-metal/features';
import { meta as metaFor, peekMeta } from 'ember-metal/meta';
import { overrideChains } from 'ember-metal/property_events';
// ..........................................................
// DESCRIPTOR
//

/**
  Objects of this type can implement an interface to respond to requests to
  get and set. The default implementation handles simple properties.

  @class Descriptor
  @private
*/
export function Descriptor() {
  this.isDescriptor = true;
}

const REDEFINE_SUPPORTED = (function () {
  // https://github.com/spalger/kibana/commit/b7e35e6737df585585332857a4c397dc206e7ff9
  var a = Object.create(Object.prototype, {
    prop: {
      configurable: true,
      value: 1
    }
  });

  Object.defineProperty(a, 'prop', {
    configurable: true,
    value: 2
  });

  return a.prop === 2;
}());
// ..........................................................
// DEFINING PROPERTIES API
//

export function MANDATORY_SETTER_FUNCTION(name) {
  function SETTER_FUNCTION(value) {
    let m = peekMeta(this);
    if (!m.isInitialized(this)) {
      m.writeValues(name, value);
    } else {
      assert(`You must use Ember.set() to set the \`${name}\` property (of ${this}) to \`${value}\`.`, false);
    }
  }

  SETTER_FUNCTION.isMandatorySetter = true;
  return SETTER_FUNCTION;
}

export function DEFAULT_GETTER_FUNCTION(name) {
  return function GETTER_FUNCTION() {
    let meta = peekMeta(this);
    return meta && meta.peekValues(name);
  };
}

import { UNDEFINED } from './meta';

export function INHERITING_GETTER_FUNCTION(name) {
  function IGETTER_FUNCTION() {
    let meta = peekMeta(this);
    let val = meta && meta.readInheritedValue('values', name);

    if (val === UNDEFINED) {
      var proto = Object.getPrototypeOf(this);
      return proto && proto[name];
    } else {
      return val;
    }
  }

  IGETTER_FUNCTION.isInheritingGetter = true;
  return IGETTER_FUNCTION;
}

/**
  NOTE: This is a low-level method used by other parts of the API. You almost
  never want to call this method directly. Instead you should use
  `Ember.mixin()` to define new properties.

  Defines a property on an object. This method works much like the ES5
  `Object.defineProperty()` method except that it can also accept computed
  properties and other special descriptors.

  Normally this method takes only three parameters. However if you pass an
  instance of `Descriptor` as the third param then you can pass an
  optional value as the fourth parameter. This is often more efficient than
  creating new descriptor hashes for each property.

  ## Examples

  ```javascript
  // ES5 compatible mode
  Ember.defineProperty(contact, 'firstName', {
    writable: true,
    configurable: false,
    enumerable: true,
    value: 'Charles'
  });

  // define a simple property
  Ember.defineProperty(contact, 'lastName', undefined, 'Jolley');

  // define a computed property
  Ember.defineProperty(contact, 'fullName', Ember.computed('firstName', 'lastName', function() {
    return this.firstName+' '+this.lastName;
  }));
  ```

  @private
  @method defineProperty
  @for Ember
  @param {Object} obj the object to define this property on. This may be a prototype.
  @param {String} keyName the name of the property
  @param {Descriptor} [desc] an instance of `Descriptor` (typically a
    computed property) or an ES5 descriptor.
    You must provide this or `data` but not both.
  @param {*} [data] something other than a descriptor, that will
    become the explicit value of this property.
*/
export function defineProperty(obj, keyName, desc, data, meta) {
  var possibleDesc, existingDesc, watching, value;

  if (!meta) {
    meta = metaFor(obj);
  }
  var watchEntry = meta.peekWatching(keyName);
  possibleDesc = obj[keyName];
  existingDesc = (possibleDesc !== null && typeof possibleDesc === 'object' && possibleDesc.isDescriptor) ? possibleDesc : undefined;

  watching = watchEntry !== undefined && watchEntry > 0;

  if (existingDesc) {
    existingDesc.teardown(obj, keyName);
  }

  if (desc instanceof Descriptor) {
    value = desc;
    if (isEnabled('mandatory-setter')) {
      if (watching) {
        Object.defineProperty(obj, keyName, {
          configurable: true,
          enumerable: true,
          writable: true,
          value: value
        });
      } else {
        obj[keyName] = value;
      }
    } else {
      obj[keyName] = value;
    }
    if (desc.setup) { desc.setup(obj, keyName); }
  } else {
    if (desc == null) {
      value = data;

      if (isEnabled('mandatory-setter')) {
        if (watching) {
          meta.writeValues(keyName, data);

          let defaultDescriptor = {
            configurable: true,
            enumerable: true,
            set: MANDATORY_SETTER_FUNCTION(keyName),
            get: DEFAULT_GETTER_FUNCTION(keyName)
          };

          if (REDEFINE_SUPPORTED) {
            Object.defineProperty(obj, keyName, defaultDescriptor);
          } else {
            handleBrokenPhantomDefineProperty(obj, keyName, defaultDescriptor);
          }
        } else {
          obj[keyName] = data;
        }
      } else {
        obj[keyName] = data;
      }
    } else {
      value = desc;

      // fallback to ES5
      Object.defineProperty(obj, keyName, desc);
    }
  }

  // if key is being watched, override chains that
  // were initialized with the prototype
  if (watching) { overrideChains(obj, keyName, meta); }

  // The `value` passed to the `didDefineProperty` hook is
  // either the descriptor or data, whichever was passed.
  if (obj.didDefineProperty) { obj.didDefineProperty(obj, keyName, value); }

  return this;
}

function handleBrokenPhantomDefineProperty(obj, keyName, desc) {
  // https://github.com/ariya/phantomjs/issues/11856
  Object.defineProperty(obj, keyName, { configurable: true, writable: true, value: 'iCry' });
  Object.defineProperty(obj, keyName, desc);
}

redpajama_set_name: RedPajamaGithub


text:
namespace base {
class DictionaryValue;
}

namespace net {
class ProxyServer;
}

// Factory and wrapper for proxy config dictionaries that are stored
// in the user preferences. The dictionary has the following structure:
// {
//   mode: string,
//   server: string,
//   pac_url: string,
//   bypass_list: string
// }
// See proxy_config_dictionary.cc for the structure of the respective strings.
class PROXY_CONFIG_EXPORT ProxyConfigDictionary {
 public:
  // Creates a deep copy of |dict| and leaves ownership to caller.
  explicit ProxyConfigDictionary(const base::DictionaryValue* dict);
  ~ProxyConfigDictionary();

  bool GetMode(ProxyPrefs::ProxyMode* out) const;
  bool GetPacUrl(std::string* out) const;
  bool GetPacMandatory(bool* out) const;
  bool GetProxyServer(std::string* out) const;
  bool GetBypassList(std::string* out) const;
  bool HasBypassList() const;

  const base::DictionaryValue& GetDictionary() const;

  static base::DictionaryValue* CreateDirect();
  static base::DictionaryValue* CreateAutoDetect();
  static base::DictionaryValue* CreatePacScript(const std::string& pac_url,
                                                bool pac_mandatory);
  static base::DictionaryValue* CreateFixedServers(
      const std::string& proxy_server,
      const std::string& bypass_list);
  static base::DictionaryValue* CreateSystem();

  // Encodes the proxy server as "<url-scheme>=<proxy-scheme>://<proxy>".
  // Used to generate the |proxy_server| arg for CreateFixedServers().
  static void EncodeAndAppendProxyServer(const std::string& url_scheme,
                                         const net::ProxyServer& server,
                                         std::string* spec);

 private:
  static base::DictionaryValue* CreateDictionary(
      ProxyPrefs::ProxyMode mode,
      const std::string& pac_url,
      bool pac_mandatory,
      const std::string& proxy_server,
      const std::string& bypass_list);

  scoped_ptr<base::DictionaryValue> dict_;

  DISALLOW_COPY_AND_ASSIGN(ProxyConfigDictionary);
};

#endif  // COMPONENTS_PROXY_CONFIG_PROXY_CONFIG_DICTIONARY_H_


text:
var toString = require('./toString');

module.exports = function (str, options) {
  var i;
  if (Object.prototype.toString.call(options) === '[object Array]') {
    var array = [];
    for (i in options) {
      array[i] = toString(options[i]);
    }
    return array.indexOf(str) >= 0;
  } else if (typeof options === 'object') {
    return options.hasOwnProperty(str);
  } else if (options && typeof options.indexOf === 'function') {
    return options.indexOf(str) >= 0;
  }
  return false;
};


text:
package org.assertj.core.api;

/**
 * Base class for file size assertions.
 *
 * @since 3.22.0
 */
public abstract class AbstractFileSizeAssert<SELF extends AbstractFileAssert<SELF>>
    extends AbstractLongAssert<AbstractFileSizeAssert<SELF>> {

  protected AbstractFileSizeAssert(Long actualFileSize, Class<?> selfType) {
    super(actualFileSize, selfType);
  }

  /**
   * Returns to the file on which we ran size assertions on.
   *

   * Example:
   *
 File file = File.createTempFile("tmp", "bin");
   * Files.write(file.toPath(), new byte[] {1, 1});
   *
   * assertThat(file).size().isGreaterThan(1L).isLessThan(5L)
   *                 .returnToFile().hasBinaryContent(new byte[] {1, 1});

   *
   * @return file assertions.
   */
  public abstract AbstractFileAssert<SELF> returnToFile();
}


text:
(function() {

  'use strict';

  angular.module('partnerApp')

    .directive('playerForm', function(){
      return {
        scope: {},
        bindToController: {

        },
        controller: 'PlayerFormCtrl',
        controllerAs: 'ctrl',
        templateUrl: 'components/player-form/player-form.html'
      };
    });

})();


text:
from recipe_engine import recipe_api

import urllib

class UrlApi(recipe_api.RecipeApi):
  quote = staticmethod(urllib.quote)
  urlencode = staticmethod(urllib.urlencode)

  @recipe_api.non_step
  def join(self, *parts):
    return '/'.join(str(x).strip('/') for x in parts)

  def fetch(self, url, step_name=None, attempts=None, headers=None, **kwargs):
    """Fetches data at given URL and returns it as str.

    Args:
      url: URL to fetch.
      step_name: optional step name, 'fetch <url>' by default.
      attempts: how many attempts to make (1 by default).
      headers: a {header_name: value} dictionary for HTTP headers.

    Returns:
      Fetched data as string.
    """
    fetch_result = self.fetch_to_file(
        url, None, step_name=step_name, attempts=attempts, headers=headers,
        **kwargs)
    return fetch_result.raw_io.output

  def fetch_to_file(self, url, path, step_name=None, attempts=None,
                    headers=None, **kwargs):
    """Fetches data at given URL and writes it to file.

    Args:
      url: URL to fetch.
      path: path to write the fetched file to. You are responsible for deleting
            it later if not needed.
      step_name: optional step name, 'fetch <url>' by default.
      attempts: how many attempts to make (1 by default).
      headers: a {header_name: value} dictionary for HTTP headers.

    Returns:
      Step.
    """
    if not step_name:
      step_name = 'fetch %s' % url
    args = [
        url,
        '--outfile', self.m.raw_io.output(leak_to=path),
    ]

    if headers:
      args.extend(['--headers-json', self.m.json.input(headers)])

    if attempts:
      args.extend(['--attempts', attempts])
    return self.m.python(
        name=step_name,
        script=self.package_repo_resource('scripts', 'tools', 'pycurl.py'),
        args=args,
        **kwargs)


text:
package com.helger.html.request;

import javax.annotation.Nonnull;

import com.helger.commons.collection.impl.ICommonsList;

/**
 * Defines an abstract request field for input controls. It encapsulates a name
 * and 0-n request values.
 *
 * @author Philip Helger´
 * @since 8.0.2
 */
public interface IHCRequestFieldMultiValue extends IHCBaseRequestField
{
  /**
   * Get the default values that should be used if no request value is present.
   *
   * @return The default value to be used as fallback. May not be
   *         null but maybe empty.
   */
  @Nonnull
  ICommonsList <String> getDefaultValues ();

  /**
   * In case multiple request parameters with the same value are present (e.g.
   * multi-selects) this method retrieves all request values. If no such request
   * value is present, the default values are returned.
   *
   * @return A list of request values with the same field name or the default
   *         values if no such request values are present.
   */
  @Nonnull
  ICommonsList <String> getRequestValues ();
}


text:
#ifndef GrDrawVerticesOp_DEFINED
#define GrDrawVerticesOp_DEFINED

#include "GrTypesPriv.h"
#include "SkRefCnt.h"
#include "SkVertices.h"

class GrColorSpaceXform;
class GrDrawOp;
class GrPaint;
class GrRecordingContext;

namespace GrDrawVerticesOp {

    /**
     * Draw a SkVertices. The GrPaint param's color is used if the vertices lack per-vertex color.
     * If the vertices lack local coords then the vertex positions are used as local coords. The
     * primitive type drawn is derived from the SkVertices object, unless overridePrimType is
     * specified.
     */
    std::unique_ptr<GrDrawOp> Make(GrRecordingContext*,
                                   GrPaint&&,
                                   sk_sp<SkVertices>,
                                   const SkVertices::Bone bones[],
                                   int boneCount,
                                   const SkMatrix& viewMatrix,
                                   GrAAType,
                                   sk_sp<GrColorSpaceXform>,
                                   GrPrimitiveType* overridePrimType = nullptr);
};

#endif


text:
package pl.java.borowiec.common.dao.hibernate;

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

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.google.common.base.Preconditions;

/**
 * @author Sławomir Borowiec
 *         Module name : personalBlogDao
 *         Creating time : 06-04-2013 16:52:02
 */
public abstract class AbstractCriteriaHibernateDao<T extends Serializable> {
	private final Class<T> clazz;
	@Autowired
	SessionFactory sessionFactory;

	public AbstractCriteriaHibernateDao(final Class<T> clazzToSet) {
		this.clazz = clazzToSet;
	}

	public T findById(final Long id) {
		Preconditions.checkArgument(id != null);
		return (T) this.getCurrentSession().get(this.clazz, id);
	}

	public List<T> getAll() {
		return this.getCurrentSession().createQuery("FROM " + this.clazz.getName()).list();
	}

	public void save(final T entity) {
		Preconditions.checkNotNull(entity);
		this.getCurrentSession().persist(entity);
	}

	public T update(final T entity) {
		Preconditions.checkNotNull(entity);
		return (T) this.getCurrentSession().merge(entity);
	}

	public void remove(final T entity) {
		Preconditions.checkNotNull(entity);
		this.getCurrentSession().delete(entity);
	}

	public void removeById(final Long entityId) {
		final T entity = this.findById(entityId);
		Preconditions.checkState(entity != null);
		this.remove(entity);
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	protected final Session getCurrentSession() {
		return this.sessionFactory.getCurrentSession();
	}

	public long countAll() {
		return (Long) sessionFactory.getCurrentSession().createQuery("Select count(*) FROM " + this.clazz.getName()).uniqueResult();
	}
}


text:
<?php

namespace Detail\Mail\Factory\Options;

use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

use Detail\Mail\Exception\ConfigException;
use Detail\Mail\Options\ModuleOptions;

class ModuleOptionsFactory implements FactoryInterface
{
    /**
     * {@inheritDoc}
     * @return ModuleOptions
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $config = $serviceLocator->get('Config');

        if (!isset($config['detail_mail'])) {
            throw new ConfigException('Config for Detail\Mail is not set');
        }

        return new ModuleOptions($config['detail_mail']);
    }
}


text:
require 'vk/api/responses'

module Vk
  module API
    class Ads < Vk::Schema::Namespace
      module Responses
        # @see https://github.com/VKCOM/vk-api-schema/blob/master/objects.json
        class GetAdsTargetingResponse < Vk::Schema::Response
          # @return [Array] @see https://github.com/VKCOM/vk-api-schema/blob/master/objects.json
          attribute :response, API::Types::Coercible::Array.member(API::Ads::TargSettings).optional.default(nil)
        end
      end
    end
  end
end


text:
/**
 * @module  EventTarget
 * @author  lifesinger@gmail.com
 */
KISSY.add('event-target', function(S, undefined) {

    var Event = S.Event;

    /**
     * EventTarget provides the implementation for any object to publish,
     * subscribe and fire to custom events.
     */
    S.EventTarget = {

        isCustomEventTarget: true,

        fire: function(type, eventData) {
            var id = S.DOM.data(this, Event.EVENT_GUID) || -1,
                cache = Event._getCache(id) || { },
                events = cache.events || { },
                t = events[type];

            if(t && S.isFunction(t.handle)) {
                return t.handle(undefined, eventData);
            }
        },

        on: function(type, fn, scope) {
            Event.add(this, type, fn, scope);
            return this; // chain
        },

        detach: function(type, fn, scope) {
            Event.remove(this, type, fn, scope);
            return this; // chain
        }
    };
});

/**
 * NOTES:
 *
 *  2010.04
 *   - 初始设想 api: publish, fire, on, detach. 实际实现时发现,publish 不是必须
 *     的,on 时能自动 publish. api 简化为:触发/订阅/反订阅
 *
 *   - detach 命名是因为 removeEventListener 太长,remove 则太容易冲突
 */


text:
<?php

namespace Buzz\Message;

abstract class AbstractMessage implements MessageInterface
{
    private $headers = array();
    private $content;

    /**
     * Returns the value of a header.
     *
     * @param string         $name
     * @param string|boolean $glue Glue for implode, or false to return an array
     *
     * @return string|array|null
     */
    public function getHeader($name, $glue = "\r\n")
    {
        $needle = $name.':';

        $values = array();
        foreach ($this->getHeaders() as $header) {
            if (0 === stripos($header, $needle)) {
                $values[] = trim(substr($header, strlen($needle)));
            }
        }

        if (false === $glue) {
            return $values;
        } else {
            return count($values) ? implode($glue, $values) : null;
        }
    }

    /**
     * Returns a header's attributes.
     *
     * @param string $name A header name
     *
     * @return array An associative array of attributes
     */
    public function getHeaderAttributes($name)
    {
        $attributes = array();
        foreach ($this->getHeader($name, false) as $header) {
            if (false !== strpos($header, ';')) {
                // remove header value
                list(, $header) = explode(';', $header, 2);

                // loop through attribute key=value pairs
                foreach (array_map('trim', explode(';', trim($header))) as $pair) {
                    list($key, $value) = explode('=', $pair);
                    $attributes[$key] = $value;
                }
            }
        }

        return $attributes;
    }

    /**
     * Returns the value of a particular header attribute.
     *
     * @param string $header    A header name
     * @param string $attribute An attribute name
     *
     * @return string|null The value of the attribute or null if it isn't set
     */
    public function getHeaderAttribute($header, $attribute)
    {
        $attributes = $this->getHeaderAttributes($header);

        if (isset($attributes[$attribute])) {
            return $attributes[$attribute];
        }
    }

    /**
     * Returns the current message as a DOMDocument.
     *
     * @return DOMDocument
     */
    public function toDomDocument()
    {
        $revert = libxml_use_internal_errors(true);

        $document = new \DOMDocument('1.0', $this->getHeaderAttribute('Content-Type', 'charset') ?: 'UTF-8');
        $document->loadHTML($this->getContent());

        libxml_use_internal_errors($revert);

        return $document;
    }

    public function setHeaders(array $headers)
    {
        $this->headers = $this->flattenHeaders($headers);
    }

    public function addHeader($header)
    {
        $this->headers[] = $header;
    }

    public function addHeaders(array $headers)
    {
        $this->headers = array_merge($this->headers, $this->flattenHeaders($headers));
    }

    public function getHeaders()
    {
        return $this->headers;
    }

    public function setContent($content)
    {
        $this->content = $content;
    }

    public function getContent()
    {
        return $this->content;
    }

    public function __toString()
    {
        $string = implode("\r\n", $this->getHeaders())."\r\n";

        if ($content = $this->getContent()) {
            $string .= "\r\n$content\r\n";
        }

        return $string;
    }

    protected function flattenHeaders(array $headers)
    {
        $flattened = array();
        foreach ($headers as $key => $header) {
            if (is_int($key)) {
                $flattened[] = $header;
            } else {
                $flattened[] = $key.': '.$header;
            }
        }

        return $flattened;
    }
}


text:
### `/workspace`

Each docker image contains a `/workspace` where all relevant files are located.

### `ARG lombokjar=lombok.jar`

When building the image, a lombok.jar will be downloaded to `/workspace/classpath` and `/workspace/modules`.
By default, this is the latest released version. You can download a specific version by adding `--build-arg lombokjar=lombok-<major.minor.build>.jar`

### `ARG jdk=13`

The jdk version to be used. Supported values:

- `13` (default)
- `12`
- `11`
- `10`
- `9`
- `8`

The version is also accessible in `JDK_VERSION`.

### Use fresh lombok.jar
If you want to use a lombok.jar from your system, assuming `<lombokhome>` contains the path to the lombok directory (where the .git subdirectory is located)
you can mount your recently built lombok.jar by providing `-v /<lombokhome>/dist/lombok.jar:/workspace/lombok.jar` to the `docker run` command.

## Examples

- [ant](ant/readme.md)
- [bazel](bazel/readme.md)
- [gradle](gradle/readme.md)
- [maven](maven/readme.md)


text:
package won.bot.framework.eventbot.filter.impl;

import won.bot.framework.eventbot.event.Event;
import won.bot.framework.eventbot.filter.AbstractDelegatingFilter;
import won.bot.framework.eventbot.filter.EventFilter;

/**
 * Delegating filter that inverts its delegate's result.
 */
public class NotFilter extends AbstractDelegatingFilter {
    public NotFilter(final EventFilter delegate) {
        super(delegate);
    }

    @Override
    public boolean accept(final Event event) {
        return !getDelegate().accept(event);
    }
}


text:
package org.apache.hadoop.hbase.client;

import org.apache.hadoop.hbase.classification.InterfaceAudience;
import org.apache.hadoop.hbase.client.metrics.ScanMetrics;

/**
 * Receives {@link Result} for an asynchronous scan.
 */
@InterfaceAudience.Public
public interface ScanResultConsumer {

  /**
   * @param result the data fetched from HBase service.
   * @return {@code false} if you want to terminate the scan process. Otherwise {@code true}
   */
  boolean onNext(Result result);

  /**
   * Indicate that we hit an unrecoverable error and the scan operation is terminated.
   * <p>
   * We will not call {@link #onComplete()} after calling {@link #onError(Throwable)}.
   */
  void onError(Throwable error);

  /**
   * Indicate that the scan operation is completed normally.
   */
  void onComplete();

  /**
   * If {@code scan.isScanMetricsEnabled()} returns true, then this method will be called prior to
   * all other methods in this interface to give you the {@link ScanMetrics} instance for this scan
   * operation. The {@link ScanMetrics} instance will be updated on-the-fly during the scan, you can
   * store it somewhere to get the metrics at any time if you want.
   */
  default void onScanMetricsCreated(ScanMetrics scanMetrics) {
  }
}


text:
package com.opengamma.strata.market.sensitivity;

import java.io.Serializable;
import java.time.LocalDate;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.function.DoubleUnaryOperator;

import org.joda.beans.Bean;
import org.joda.beans.BeanBuilder;
import org.joda.beans.BeanDefinition;
import org.joda.beans.ImmutableBean;
import org.joda.beans.JodaBeanUtils;
import org.joda.beans.MetaProperty;
import org.joda.beans.Property;
import org.joda.beans.PropertyDefinition;
import org.joda.beans.impl.direct.DirectFieldsBeanBuilder;
import org.joda.beans.impl.direct.DirectMetaBean;
import org.joda.beans.impl.direct.DirectMetaProperty;
import org.joda.beans.impl.direct.DirectMetaPropertyMap;

import com.google.common.collect.ComparisonChain;
import com.opengamma.strata.basics.currency.Currency;
import com.opengamma.strata.basics.currency.FxRateProvider;

/**
 * Point sensitivity to the zero rate curve.
 *

 * Holds the sensitivity to the zero rate curve at a specific date.
 */
@BeanDefinition(builderScope = "private")
public final class ZeroRateSensitivity
    implements PointSensitivity, PointSensitivityBuilder, ImmutableBean, Serializable {

  /**
   * The currency of the curve for which the sensitivity is computed.
   */
  @PropertyDefinition(validate = "notNull")
  private final Currency curveCurrency;
  /**
   * The date that was looked up on the curve.
   */
  @PropertyDefinition(validate = "notNull")
  private final LocalDate date;
  /**
   * The currency of the sensitivity.
   */
  @PropertyDefinition(validate = "notNull", overrideGet = true)
  private final Currency currency;
  /**
   * The value of the sensitivity.
   */
  @PropertyDefinition(overrideGet = true)
  private final double sensitivity;

  //-------------------------------------------------------------------------
  /**
   * Obtains a {@code ZeroRateSensitivity} from the curve currency, date and value.
   *

   * The currency representing the curve is used also for the sensitivity currency.
   *
   * @param currency  the currency of the curve and sensitivity
   * @param date  the date that was looked up on the curve
   * @param sensitivity  the value of the sensitivity
   * @return the point sensitivity object
   */
  public static ZeroRateSensitivity of(Currency currency, LocalDate date, double sensitivity) {
    return new ZeroRateSensitivity(currency, date, currency, sensitivity);
  }

  /**
   * Obtains a {@code ZeroRateSensitivity} from the curve currency, date, sensitivity currency and value.
   *

   * The currency representing the curve is used also for the sensitivity currency.
   *
   * @param curveCurrency  the currency of the curve
   * @param date  the date that was looked up on the curve
   * @param sensitivityCurrency  the currency of the sensitivity
   * @param sensitivity  the value of the sensitivity
   * @return the point sensitivity object
   */
  public static ZeroRateSensitivity of(
      Currency curveCurrency,
      LocalDate date,
      Currency sensitivityCurrency,
      double sensitivity) {
    return new ZeroRateSensitivity(curveCurrency, date, sensitivityCurrency, sensitivity);
  }

  //-------------------------------------------------------------------------
  @Override
  public ZeroRateSensitivity withCurrency(Currency currency) {
    if (this.currency.equals(currency)) {
      return this;
    }
    return new ZeroRateSensitivity(curveCurrency, date, currency, sensitivity);
  }

  @Override
  public ZeroRateSensitivity withSensitivity(double sensitivity) {
    return new ZeroRateSensitivity(curveCurrency, date, currency, sensitivity);
  }

  @Override
  public int compareKey(PointSensitivity other) {
    if (other instanceof ZeroRateSensitivity) {
      ZeroRateSensitivity otherZero = (ZeroRateSensitivity) other;
      return ComparisonChain.start()
          .compare(curveCurrency, otherZero.curveCurrency)
          .compare(currency, otherZero.currency)
          .compare(date, otherZero.date)
          .result();
    }
    return getClass().getSimpleName().compareTo(other.getClass().getSimpleName());
  }

  @Override
  public ZeroRateSensitivity convertedTo(Currency resultCurrency, FxRateProvider rateProvider) {
    return (ZeroRateSensitivity) PointSensitivity.super.convertedTo(resultCurrency, rateProvider);
  }

  //-------------------------------------------------------------------------
  @Override
  public ZeroRateSensitivity multipliedBy(double factor) {
    return new ZeroRateSensitivity(curveCurrency, date, currency, sensitivity * factor);
  }

  @Override
  public ZeroRateSensitivity mapSensitivity(DoubleUnaryOperator operator) {
    return new ZeroRateSensitivity(curveCurrency, date, currency, operator.applyAsDouble(sensitivity));
  }

  @Override
  public ZeroRateSensitivity normalize() {
    return this;
  }

  @Override
  public MutablePointSensitivities buildInto(MutablePointSensitivities combination) {
    return combination.add(this);
  }

  @Override
  public ZeroRateSensitivity cloned() {
    return this;
  }

  //------------------------- AUTOGENERATED START -------------------------
  ///CLOVER:OFF
  /**
   * The meta-bean for {@code ZeroRateSensitivity}.
   * @return the meta-bean, not null
   */
  public static ZeroRateSensitivity.Meta meta() {
    return ZeroRateSensitivity.Meta.INSTANCE;
  }

  static {
    JodaBeanUtils.registerMetaBean(ZeroRateSensitivity.Meta.INSTANCE);
  }

  /**
   * The serialization version id.
   */
  private static final long serialVersionUID = 1L;

  private ZeroRateSensitivity(
      Currency curveCurrency,
      LocalDate date,
      Currency currency,
      double sensitivity) {
    JodaBeanUtils.notNull(curveCurrency, "curveCurrency");
    JodaBeanUtils.notNull(date, "date");
    JodaBeanUtils.notNull(currency, "currency");
    this.curveCurrency = curveCurrency;
    this.date = date;
    this.currency = currency;
    this.sensitivity = sensitivity;
  }

  @Override
  public ZeroRateSensitivity.Meta metaBean() {
    return ZeroRateSensitivity.Meta.INSTANCE;
  }

  @Override
  public <R> Property<R> property(String propertyName) {
    return metaBean().<R>metaProperty(propertyName).createProperty(this);
  }

  @Override
  public Set<String> propertyNames() {
    return metaBean().metaPropertyMap().keySet();
  }

  //-----------------------------------------------------------------------
  /**
   * Gets the currency of the curve for which the sensitivity is computed.
   * @return the value of the property, not null
   */
  public Currency getCurveCurrency() {
    return curveCurrency;
  }

  //-----------------------------------------------------------------------
  /**
   * Gets the date that was looked up on the curve.
   * @return the value of the property, not null
   */
  public LocalDate getDate() {
    return date;
  }

  //-----------------------------------------------------------------------
  /**
   * Gets the currency of the sensitivity.
   * @return the value of the property, not null
   */
  @Override
  public Currency getCurrency() {
    return currency;
  }

  //-----------------------------------------------------------------------
  /**
   * Gets the value of the sensitivity.
   * @return the value of the property
   */
  @Override
  public double getSensitivity() {
    return sensitivity;
  }

  //-----------------------------------------------------------------------
  @Override
  public boolean equals(Object obj) {
    if (obj == this) {
      return true;
    }
    if (obj != null && obj.getClass() == this.getClass()) {
      ZeroRateSensitivity other = (ZeroRateSensitivity) obj;
      return JodaBeanUtils.equal(getCurveCurrency(), other.getCurveCurrency()) &&
          JodaBeanUtils.equal(getDate(), other.getDate()) &&
          JodaBeanUtils.equal(getCurrency(), other.getCurrency()) &&
          JodaBeanUtils.equal(getSensitivity(), other.getSensitivity());
    }
    return false;
  }

  @Override
  public int hashCode() {
    int hash = getClass().hashCode();
    hash = hash * 31 + JodaBeanUtils.hashCode(getCurveCurrency());
    hash = hash * 31 + JodaBeanUtils.hashCode(getDate());
    hash = hash * 31 + JodaBeanUtils.hashCode(getCurrency());
    hash = hash * 31 + JodaBeanUtils.hashCode(getSensitivity());
    return hash;
  }

  @Override
  public String toString() {
    StringBuilder buf = new StringBuilder(160);
    buf.append("ZeroRateSensitivity{");
    buf.append("curveCurrency").append('=').append(getCurveCurrency()).append(',').append(' ');
    buf.append("date").append('=').append(getDate()).append(',').append(' ');
    buf.append("currency").append('=').append(getCurrency()).append(',').append(' ');
    buf.append("sensitivity").append('=').append(JodaBeanUtils.toString(getSensitivity()));
    buf.append('}');
    return buf.toString();
  }

  //-----------------------------------------------------------------------
  /**
   * The meta-bean for {@code ZeroRateSensitivity}.
   */
  public static final class Meta extends DirectMetaBean {
    /**
     * The singleton instance of the meta-bean.
     */
    static final Meta INSTANCE = new Meta();

    /**
     * The meta-property for the {@code curveCurrency} property.
     */
    private final MetaProperty<Currency> curveCurrency = DirectMetaProperty.ofImmutable(
        this, "curveCurrency", ZeroRateSensitivity.class, Currency.class);
    /**
     * The meta-property for the {@code date} property.
     */
    private final MetaProperty<LocalDate> date = DirectMetaProperty.ofImmutable(
        this, "date", ZeroRateSensitivity.class, LocalDate.class);
    /**
     * The meta-property for the {@code currency} property.
     */
    private final MetaProperty<Currency> currency = DirectMetaProperty.ofImmutable(
        this, "currency", ZeroRateSensitivity.class, Currency.class);
    /**
     * The meta-property for the {@code sensitivity} property.
     */
    private final MetaProperty<Double> sensitivity = DirectMetaProperty.ofImmutable(
        this, "sensitivity", ZeroRateSensitivity.class, Double.TYPE);
    /**
     * The meta-properties.
     */
    private final Map<String, MetaProperty<?>> metaPropertyMap$ = new DirectMetaPropertyMap(
        this, null,
        "curveCurrency",
        "date",
        "currency",
        "sensitivity");

    /**
     * Restricted constructor.
     */
    private Meta() {
    }

    @Override
    protected MetaProperty<?> metaPropertyGet(String propertyName) {
      switch (propertyName.hashCode()) {
        case 1303639584:  // curveCurrency
          return curveCurrency;
        case 3076014:  // date
          return date;
        case 575402001:  // currency
          return currency;
        case 564403871:  // sensitivity
          return sensitivity;
      }
      return super.metaPropertyGet(propertyName);
    }

    @Override
    public BeanBuilder<? extends ZeroRateSensitivity> builder() {
      return new ZeroRateSensitivity.Builder();
    }

    @Override
    public Class<? extends ZeroRateSensitivity> beanType() {
      return ZeroRateSensitivity.class;
    }

    @Override
    public Map<String, MetaProperty<?>> metaPropertyMap() {
      return metaPropertyMap$;
    }

    //-----------------------------------------------------------------------
    /**
     * The meta-property for the {@code curveCurrency} property.
     * @return the meta-property, not null
     */
    public MetaProperty<Currency> curveCurrency() {
      return curveCurrency;
    }

    /**
     * The meta-property for the {@code date} property.
     * @return the meta-property, not null
     */
    public MetaProperty<LocalDate> date() {
      return date;
    }

    /**
     * The meta-property for the {@code currency} property.
     * @return the meta-property, not null
     */
    public MetaProperty<Currency> currency() {
      return currency;
    }

    /**
     * The meta-property for the {@code sensitivity} property.
     * @return the meta-property, not null
     */
    public MetaProperty<Double> sensitivity() {
      return sensitivity;
    }

    //-----------------------------------------------------------------------
    @Override
    protected Object propertyGet(Bean bean, String propertyName, boolean quiet) {
      switch (propertyName.hashCode()) {
        case 1303639584:  // curveCurrency
          return ((ZeroRateSensitivity) bean).getCurveCurrency();
        case 3076014:  // date
          return ((ZeroRateSensitivity) bean).getDate();
        case 575402001:  // currency
          return ((ZeroRateSensitivity) bean).getCurrency();
        case 564403871:  // sensitivity
          return ((ZeroRateSensitivity) bean).getSensitivity();
      }
      return super.propertyGet(bean, propertyName, quiet);
    }

    @Override
    protected void propertySet(Bean bean, String propertyName, Object newValue, boolean quiet) {
      metaProperty(propertyName);
      if (quiet) {
        return;
      }
      throw new UnsupportedOperationException("Property cannot be written: " + propertyName);
    }

  }

  //-----------------------------------------------------------------------
  /**
   * The bean-builder for {@code ZeroRateSensitivity}.
   */
  private static final class Builder extends DirectFieldsBeanBuilder<ZeroRateSensitivity> {

    private Currency curveCurrency;
    private LocalDate date;
    private Currency currency;
    private double sensitivity;

    /**
     * Restricted constructor.
     */
    private Builder() {
    }

    //-----------------------------------------------------------------------
    @Override
    public Object get(String propertyName) {
      switch (propertyName.hashCode()) {
        case 1303639584:  // curveCurrency
          return curveCurrency;
        case 3076014:  // date
          return date;
        case 575402001:  // currency
          return currency;
        case 564403871:  // sensitivity
          return sensitivity;
        default:
          throw new NoSuchElementException("Unknown property: " + propertyName);
      }
    }

    @Override
    public Builder set(String propertyName, Object newValue) {
      switch (propertyName.hashCode()) {
        case 1303639584:  // curveCurrency
          this.curveCurrency = (Currency) newValue;
          break;
        case 3076014:  // date
          this.date = (LocalDate) newValue;
          break;
        case 575402001:  // currency
          this.currency = (Currency) newValue;
          break;
        case 564403871:  // sensitivity
          this.sensitivity = (Double) newValue;
          break;
        default:
          throw new NoSuchElementException("Unknown property: " + propertyName);
      }
      return this;
    }

    @Override
    public Builder set(MetaProperty<?> property, Object value) {
      super.set(property, value);
      return this;
    }

    @Override
    public Builder setString(String propertyName, String value) {
      setString(meta().metaProperty(propertyName), value);
      return this;
    }

    @Override
    public Builder setString(MetaProperty<?> property, String value) {
      super.setString(property, value);
      return this;
    }

    @Override
    public Builder setAll(Map<String, ? extends Object> propertyValueMap) {
      super.setAll(propertyValueMap);
      return this;
    }

    @Override
    public ZeroRateSensitivity build() {
      return new ZeroRateSensitivity(
          curveCurrency,
          date,
          currency,
          sensitivity);
    }

    //-----------------------------------------------------------------------
    @Override
    public String toString() {
      StringBuilder buf = new StringBuilder(160);
      buf.append("ZeroRateSensitivity.Builder{");
      buf.append("curveCurrency").append('=').append(JodaBeanUtils.toString(curveCurrency)).append(',').append(' ');
      buf.append("date").append('=').append(JodaBeanUtils.toString(date)).append(',').append(' ');
      buf.append("currency").append('=').append(JodaBeanUtils.toString(currency)).append(',').append(' ');
      buf.append("sensitivity").append('=').append(JodaBeanUtils.toString(sensitivity));
      buf.append('}');
      return buf.toString();
    }

  }

  ///CLOVER:ON
  //-------------------------- AUTOGENERATED END --------------------------
}


text:
import datetime
from django import template

register = template.Library()

# @register.simple_tag
# def current_time(format_string):
#     return datetime.datetime.now().strftime(format_string)

@register.simple_tag(takes_context=True)
def active_sidebar_by_path(context, path):
    """高亮当前sidebar-item"""
    curr_path = context['request'].path
    return 'active' if path in curr_path else ''


text:
let transform = require("../lib/api/node").transform;
let Plugin    = require("../lib/transformation/plugin");
let chai      = require("chai");

describe("traversal path", function () {
  it("replaceWithSourceString", function () {
    let expectCode = "function foo() {}";

    let actualCode = transform(expectCode, {
      plugins: [new Plugin({
        visitor: {
          FunctionDeclaration: function (path) {
            path.replaceWithSourceString("console.whatever()");
          }
        }
      })]
    }).code;

    chai.expect(actualCode).to.be.equal("console.whatever();");
  });

  it("replaceWith (arrow expression body to block statement body)", function () {
    let expectCode = "var fn = () => true;";

    let actualCode = transform(expectCode, {
      plugins: [new Plugin({
        visitor: {
          ArrowFunctionExpression: function (path) {
            path.get("body").replaceWith({
              type: "BlockStatement",
              body: [{
                type: "ReturnStatement",
                argument: {
                  type: "BooleanLiteral",
                  value: true
                }
              }]
            });
          }
        }
      })]
    }).code;

    chai.expect(actualCode).to.be.equal("var fn = () => {\n  return true;\n};");
  });

  it("replaceWith (arrow block statement body to expression body)", function () {
    let expectCode = "var fn = () => { return true; }";

    let actualCode = transform(expectCode, {
      plugins: [new Plugin({
        visitor: {
          ArrowFunctionExpression: function (path) {
            path.get("body").replaceWith({
              type: "BooleanLiteral",
              value: true
            });
          }
        }
      })]
    }).code;

    chai.expect(actualCode).to.be.equal("var fn = () => true;");
  });

  it("replaceWith (for-in left expression to variable declaration)", function () {
    let expectCode = "for (KEY in right);";

    let actualCode = transform(expectCode, {
      plugins: [new Plugin({
        visitor: {
          ForInStatement: function (path) {
            path.get("left").replaceWith({
              type: "VariableDeclaration",
              kind: "var",
              declarations: [{
                type: "VariableDeclarator",
                id: {
                  type: "Identifier",
                  name: "KEY"
                }
              }]
            });
          }
        }
      })]
    }).code;

    chai.expect(actualCode).to.be.equal("for (var KEY in right);");
  });

  it("replaceWith (for-in left variable declaration to expression)", function () {
    let expectCode = "for (var KEY in right);";

    let actualCode = transform(expectCode, {
      plugins: [new Plugin({
        visitor: {
          ForInStatement: function (path) {
            path.get("left").replaceWith({
              type: "Identifier",
              name: "KEY"
            });
          }
        }
      })]
    }).code;

    chai.expect(actualCode).to.be.equal("for (KEY in right);");
  });

  it("replaceWith (for-loop left expression to variable declaration)", function () {
    let expectCode = "for (KEY;;);";

    let actualCode = transform(expectCode, {
      plugins: [new Plugin({
        visitor: {
          ForStatement: function (path) {
            path.get("init").replaceWith({
              type: "VariableDeclaration",
              kind: "var",
              declarations: [{
                type: "VariableDeclarator",
                id: {
                  type: "Identifier",
                  name: "KEY"
                }
              }]
            });
          }
        }
      })]
    }).code;

    chai.expect(actualCode).to.be.equal("for (var KEY;;);");
  });

  it("replaceWith (for-loop left variable declaration to expression)", function () {
    let expectCode = "for (var KEY;;);";

    let actualCode = transform(expectCode, {
      plugins: [new Plugin({
        visitor: {
          ForStatement: function (path) {
            path.get("init").replaceWith({
              type: "Identifier",
              name: "KEY"
            });
          }
        }
      })]
    }).code;

    chai.expect(actualCode).to.be.equal("for (KEY;;);");
  });
});


text:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>

    <script>
        var saleOffice = {};
        saleOffice.clientList = {};

        saleOffice.listen = function(key, fn) {
            if (!this.clientList[key]) {
                this.clientList[key] = [];
            }
            this.clientList[key].push(fn);
        };

        saleOffice.trigger = function() {
            var key = Array.prototype.shift.call(arguments);
            var fns = this.clientList[key];

            if (!fns || fns.length === 0) {
                return;
            }

            var fn = '';
            for (var i = 0; i < fns.length; i++) {
                fn = fns[i];
                fn.apply(this, arguments);
            }
        };

        saleOffice.listen('click', function(value) {
            console.log('click:' + value);
        });

        saleOffice.listen('mouseover', function(value) {
            console.log('mouseover: ' + value);
        });
    </script>
</body>
</html>


text:
package org.apache.ignite.lang;

import org.apache.ignite.internal.util.*;
import org.apache.ignite.testframework.junits.common.*;

import java.util.*;

/**
 * Set wrapper test.
 */
@GridCommonTest(group = "Lang")
public class GridSetWrapperSelfTest extends GridCommonAbstractTest {

    /** @throws Exception If failed. */
    public void testEmptySet() throws Exception {
        checkCollectionEmptiness(new GridSetWrapper<>(new HashMap<String, Object>()));
    }

    /** @throws Exception If failed. */
    public void testMultipleValuesSet() throws Exception {
        Set<String> set = new GridSetWrapper<>(new HashMap<String, Object>());

        set.add("v1");
        set.add("v2");
        set.add("v3");
        set.add("v4");
        set.add("v5");
        set.add("v6");

        assert !set.isEmpty();

        assertEquals(6, set.size());

        set.add("v5");
        set.add("v6");

        assertEquals(6, set.size());

        assert set.contains("v1");
        assert set.contains("v2");
        assert set.contains("v3");
        assert set.contains("v4");
        assert set.contains("v5");
        assert set.contains("v6");
        assert !set.contains("v7");

        Iterator<String> iter = set.iterator();

        for (int i = 0; i < 6; i++)
            assert iter.next().contains("v");

        assert !iter.hasNext();
    }

    /** @throws Exception If failed. */
    public void testSetRemove() throws Exception {
        Collection<String> set = new GridSetWrapper<>(new HashMap<String, Object>());

        // Put 1 element.
        set.add("v1");

        assert set.remove("v1");
        assert !set.remove("v2");

        checkCollectionEmptiness(set);

        // Put 2 elements.
        set.add("v1");
        set.add("v2");

        assert set.remove("v1");
        assert set.remove("v2");
        assert !set.remove("v3");

        checkCollectionEmptiness(set);

        // Put more than 5 elements.
        set.add("v1");
        set.add("v2");
        set.add("v3");
        set.add("v4");
        set.add("v5");
        set.add("v6");

        assert set.remove("v1");
        assert set.remove("v2");
        assert set.remove("v3");
        assert set.remove("v4");
        assert set.remove("v5");
        assert set.remove("v6");
        assert !set.remove("v7");

        checkCollectionEmptiness(set);
    }

    /** @throws Exception If failed. */
    public void testSetRemoveAll() throws Exception {
        Collection<String> set = new GridSetWrapper<>(new HashMap<String, Object>());

        set.add("v1");
        set.add("v2");
        set.add("v3");
        set.add("v4");
        set.add("v5");

        set.removeAll(IgniteUtils.addAll(new HashSet<String>(), "v2", "v4", "v5"));

        assertEquals(2, set.size());

        assert set.contains("v1");
        assert !set.contains("v2");
        assert set.contains("v3");
        assert !set.contains("v4");
        assert !set.contains("v5");
    }

    /** @throws Exception If failed. */
    public void testSetClear() throws Exception {
        Collection<String> set = new GridSetWrapper<>(new HashMap<String, Object>());

        set.add("v1");
        set.add("v2");
        set.add("v3");
        set.add("v4");
        set.add("v5");
        set.add("v6");

        assertEquals(6, set.size());

        set.clear();

        checkCollectionEmptiness(set);
    }

    /** @throws Exception If failed. */
    public void testIterator() throws Exception {
        Set<String> set = new GridSetWrapper<>(new HashMap<String, Object>());

        set.add("v1");
        set.add("v2");
        set.add("v3");
        set.add("v4");
        set.add("v5");
        set.add("v6");

        Iterator<String> iter = set.iterator();

        assert iter.hasNext();

        String e = iter.next();

        assert e.contains("v");

        iter.next();

        iter.remove();

        assertEquals(5, set.size());

        assert iter.next() != null;
        assert iter.next() != null;

        iter.remove();

        assertEquals(4, set.size());

        assert iter.next() != null;

        assert iter.next() != null;

        assert !iter.hasNext();
    }

    /**
     * Checks set emptiness.
     *
     * @param c Set to check.
     * @throws Exception If failed.
     */
    private void checkCollectionEmptiness(Collection<?> c) throws Exception {
        assert c.isEmpty();

        assert !c.contains("Some value");

        assertEquals(0, c.size());

        assert !c.iterator().hasNext();

        try {
            c.iterator().next();

            fail("NoSuchElementException must have been thrown.");
        }
        catch (NoSuchElementException e) {
            info("Caught expected exception: " + e);
        }

        try {
            c.iterator().remove();

            fail("IllegalStateException must have been thrown.");
        }
        catch (IllegalStateException e) {
            info("Caught expected exception: " + e);
        }
    }
}


text:
from google.cloud import batch_v1alpha

def sample_list_tasks():
    # Create a client
    client = batch_v1alpha.BatchServiceClient()

    # Initialize request argument(s)
    request = batch_v1alpha.ListTasksRequest(
        parent="parent_value",
    )

    # Make the request
    page_result = client.list_tasks(request=request)

    # Handle the response
    for response in page_result:
        print(response)

# [END batch_v1alpha_generated_BatchService_ListTasks_sync]


text:
package es.tid.bgp.bgp4.update.fields.pathAttributes;

import es.tid.bgp.bgp4.update.MalformedBGP4ElementException;
import es.tid.bgp.bgp4.update.fields.PathAttribute;

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

/**
 * AS_PATH (Type Code 2):
 *

 * AS_PATH is a well-known mandatory attribute that is composed
 * of a sequence of AS path segments.  Each AS path segment is
 * represented by a triple{@code <path segment type, path segment
 * length, path segment value>}.
 *

 * The path segment type is a 1-octet length field with the
 * following values defined:
 *

 * Value      Segment Type
 *

 * 1         AS_SET: unordered set of ASes a route in the
 * UPDATE message has traversed
 *

 * 2         AS_SEQUENCE: ordered set of ASes a route in
 * the UPDATE message has traversed
 *

 * The path segment length is a 1-octet length field,
 * containing the number of ASes (not the number of octets) in
 * the path segment value field.
 *

 * The path segment value field contains one or more AS
 * numbers, each encoded as a 2-octet length field.
 *

 * Usage of this attribute is defined in 5.1.2.
 *
 * @author mcs
 */
public class AS_Path_Attribute extends PathAttribute
{
	private LinkedList<AS_Path_Segment> asPathSegments;

	public AS_Path_Attribute()
	{
		super();
		//Poner los flags.
		this.typeCode = PathAttributesTypeCode.PATH_ATTRIBUTE_TYPECODE_ASPATH;
		asPathSegments = new LinkedList<AS_Path_Segment>();
	}

	public AS_Path_Attribute(byte[] bytes, int offset) throws MalformedBGP4ElementException
	{
		super(bytes, offset);
		asPathSegments = new LinkedList<AS_Path_Segment>();
		decode();
	}

	@Override
	public void encode()
	{
		int path_attribute_length=0;

		for(AS_Path_Segment asPathSegment : asPathSegments)
		{
			asPathSegment.encode();
			path_attribute_length+=asPathSegment.getLength();
		}
		this.setPathAttributeLength(path_attribute_length);
		bytes = new byte[length];
		encodeHeader();
		int offset = this.mandatoryLength; //After the header encoding
		int num_segs=asPathSegments.size();
		for(int i=0;i<num_segs;++i)
		{
			System.arraycopy(asPathSegments.get(i).getBytes(), 0, bytes, offset, asPathSegments.get(i).getLength());
			offset += asPathSegments.get(i).getLength();
		}

	}

	public void decode() throws MalformedBGP4ElementException
	{
		if(typeCode != PathAttributesTypeCode.PATH_ATTRIBUTE_TYPECODE_ASPATH)
			throw new MalformedBGP4ElementException();

		int offset = this.mandatoryLength;
		while(offset < length)
		{
			AS_Path_Segment asPathSegment = new AS_Path_Segment(bytes, offset);
			asPathSegments.add(asPathSegment);
			offset += asPathSegment.getLength();
		}
	}

	public int getType()
	{
		return typeCode;
	}

	public List<AS_Path_Segment> getAsPathSegments(){ return asPathSegments; }

	public void setAsPathSegments(LinkedList<AS_Path_Segment> asPathSegments)
	{
		this.asPathSegments = asPathSegments;
	}

	@Override
	public String toString()
	{
		String ret="";
		ret+="AS_PATH [Type=" + typeCode + " Length=" + length + " NumberOfAsPathSegments=" + asPathSegments.size() + "]";
		for (int i=0; i<asPathSegments.size();++i){
			ret+=asPathSegments.toString();
		}
		return ret;
	}

	@Override
	public boolean equals(Object obj)
	{
		if(this == obj)
			return true;
		if(obj == null)
			return false;
		if(getClass() != obj.getClass())
			return false;
		AS_Path_Attribute other = (AS_Path_Attribute) obj;
		if(! Arrays.equals(bytes, other.getBytes()))
			return false;
		if(length != other.getLength())
			return false;
		return true;

	}

}


text:
using System;
using System.Web;
using Errordite.Client.Configuration;
using Errordite.Client.Interfaces;

namespace Errordite.Client.DataCollectors
{
    public class HttpContextDataCollector : DataCollectorBase, IDataCollector
    {
        public ErrorData Collect(Exception e, IErrorditeConfiguration configuration)
        {
            var context = HttpContext.Current;

            if (context == null)
                return null;

            var data = new ErrorData();

            AddIfNotEmpty("HttpMethod", context.Request.HttpMethod, data);

            if(context.Request.UrlReferrer != null)
                AddIfNotEmpty("Referrer", context.Request.UrlReferrer.AbsoluteUri, data);

            if (context.Request.Form.Count > 0)
            {
                foreach(var key in context.Request.Form.Keys)
                {
                    AddIfNotEmpty(string.Format("Form.{0}", key),
                        Sanitise(configuration, key.ToString(), context.Request.Form[key.ToString()]),
                        data);
                }
            }

            if (context.Request.Headers.Count > 0)
            {
                foreach (string key in context.Request.Headers.Keys)
                {
                    switch (key)
                    {
                        case "User-Agent":
                            continue;
                    }

                    AddIfNotEmpty(string.Format("Header.{0}", key),
                        Sanitise(configuration, key, context.Request.Headers[key]),
                        data);
                }
            }

            return data;
        }

        public ErrorData Collect(Exception e)
        {
            return null;
        }
    }
}


text:
package fr.sii.ogham.testing.assertion.internal;

import static fr.sii.ogham.testing.assertion.internal.CloudhopperAssertions.getCloudhopperSender;
import static fr.sii.ogham.testing.assertion.internal.FreemarkerAssersions.getFreemarkerParsers;
import static fr.sii.ogham.testing.assertion.internal.JavaMailAssertions.getJavaMailSender;
import static fr.sii.ogham.testing.assertion.internal.SendGridAssertions.getSendGridSender;
import static fr.sii.ogham.testing.assertion.internal.ThymeleafAssertions.getThymeleafParsers;

import fr.sii.ogham.core.builder.MessagingBuilder;
import fr.sii.ogham.core.service.MessagingService;

/**
 * Helper to make assertions on {@link MessagingService} instance created by a
 * {@link MessagingBuilder}.
 *
 * @author Aurélien Baudet
 *
 */
public class MessagingServiceAssertions {
	private final MessagingService messagingService;

	public MessagingServiceAssertions(MessagingService messagingService) {
		this.messagingService = messagingService;
	}

	/**
	 * Use it to ensure that SendGrid is configured as expected.
	 *
	 *

	 * The version of SendGrid is automatically determined. If the automatic
	 * detection doesn't work, use {@link #sendGrid(SendGridVersion)}
	 *
	 * For example:
	 *
	 *

	 * {@code
	 * sendGrid()
	 *   .apiKey(equalTo("foo"))
	 * }
	 *

	 *
	 * @return builder for fluent chaining
	 */
	public SendGridAssertions sendGrid() {
		return new SendGridAssertions(this, getSendGridSender(messagingService));
	}

	/**
	 * Use it to ensure that SendGrid (for a particular version) is configured
	 * as expected.
	 *
	 * For example:
	 *
	 *

	 * {code
	 * sendGrid(SendGridVersion.V2)
	 *   .apiKey(equalTo("foo"))
	 * }
	 *

	 *
	 * @param sendGridVersion
	 *            the SendGrid version to use
	 * @return builder for fluent chaining
	 */
	public SendGridAssertions sendGrid(SendGridVersion sendGridVersion) {
		return new SendGridAssertions(this, getSendGridSender(messagingService, sendGridVersion.getSenderClass()));
	}

	/**
	 * Use it to ensure that Thymeleaf is configured as expected.
	 *
	 *

	 * All the ThymeleafParser instances are automatically retrieved
	 * from {@link MessagingService}. You can then select which
	 * ThymeleafParser to check by using fluent API.
	 *
	 * For example:
	 *
	 *

	 * {@code
	 * thymeleaf()
	 *   .email()
	 *     .engine(isA(SpringTemplateEngine.class))
	 * }
	 *

	 *
	 * @return the builder for fluent chaining
	 */
	public ThymeleafAssertions thymeleaf() {
		return new ThymeleafAssertions(this, getThymeleafParsers(messagingService));
	}

	/**
	 * Use it to ensure that FreeMarker is configured as expected.
	 *
	 *

	 * All the FreeMarkerParser instances are automatically retrieved
	 * from {@link MessagingService}. You can then select which
	 * FreeMarkerParser to check by using fluent API.
	 *
	 * For example, to ensure that UTF-8 is used as default encoding for email
	 * parser:
	 *
	 *

	 * {@code
	 * freemarker()
	 *   .email()
	 *     .configuration()
	 *       .defaultEncoding(equalTo("UTF-8"))
	 * }
	 *

	 *
	 * @return the builder for fluent chaining
	 */
	public FreemarkerAssersions freemarker() {
		return new FreemarkerAssersions(this, getFreemarkerParsers(messagingService));
	}

	/**
	 * Use it to ensure that JavaMailSender is configured as expected.
	 *
	 * For example:
	 *
	 *

	 * {@code
	 * javaMail()
	 *   .host(equalTo("foo"))
	 * }
	 *

	 *
	 * @return the builder for fluent chaining
	 */
	public JavaMailAssertions javaMail() {
		return new JavaMailAssertions(this, getJavaMailSender(messagingService));
	}

	/**
	 * Use it to ensure that CloudhopperSMPPSender is configured as expected.
	 *
	 * For example:
	 *
	 *

	 * {@code
	 * cloudhopper()
	 *   .host(equalTo("foo"))
	 * }
	 *

	 *
	 * @return the builder for fluent chaining
	 */
	public CloudhopperAssertions cloudhopper() {
		return new CloudhopperAssertions(this, getCloudhopperSender(messagingService));
	}

}


text:
var path = require('path');

var esprima = require('esprima');
var _ = require('lodash');

module.exports = function(sails){
    return {

        defaults: function(config){
            return {
                paths: {
                    policyFactories: path.resolve(config.appPath, 'api/policyFactories')
                }
            };
        },

        configure: function(){

            _.extend(sails.config.paths, {
                policyFactories: path.resolve(sails.config.appPath, sails.config.paths.policyFactories),
            });

            sails.config.policies = this.parsePolicies(sails.config.policies);
        },

        parsePolicies: parsePolicies,
        parseEsprima: parseEsprima,
    };
}

/*
    input [Any]
*/
function parsePolicies(input){
    var type = typeof input;

    if(type === 'object'){
        for(var i in input){
            input[i] = this.parsePolicies(input[i]);
        }

        return input;
    }

    if(type === 'string'){
        var parsedString = esprima.parse(input).body[0].expression;
        return this.parseEsprima(parsedString);
    }

    return input;
}

/*
    input [Esprima Object]
    fromFactory [Boolean] set to true the result will be interpreted by a factory
*/
function parseEsprima(input, fromFactory){

    var type = input.type;

    if(type === esprimaType.value){
        return input.value;
    }

    if(type === esprimaType.policy){

        var policyName = input.name;

        if(fromFactory){
            return require(sails.config.paths.policies + '/' + policyName);
        }

        return policyName;
    }

    if(type === esprimaType.factory){

        var factoryName = input.callee.name;

        try {
            var factory = require(sails.config.paths.policyFactories + '/' + factoryName);
        } catch (e) {
            return require(sails.config.paths.policies + '/' + factoryName);
        }

        var args = input.arguments.map(function(arg){
            return this.parseEsprima(arg, true);
        }, this);

        return factory.apply(this, args);
    }

    throw new Error('esprima type unhandled: ' + type);
}

var esprimaType = {
    value: 'Literal',
    policy: 'Identifier',
    factory: 'CallExpression',
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

  <title>inputEx - SerializeField Usage</title>

<link rel="stylesheet" type="text/css" href="../lib/yui/reset-fonts/reset-fonts.css">
<link rel="stylesheet" type="text/css" href="../lib/yui/container/assets/container.css">
<link rel="stylesheet" type="text/css" href="../lib/yui/assets/skins/sam/skin.css">

<link type='text/css' rel='stylesheet' href='../css/inputEx.css' />

<link rel="stylesheet" type="text/css" href="css/demo.css"/>
<link rel="stylesheet" type="text/css" href="css/dpSyntaxHighlighter.css">

inputEx - SerializeField Usage

Basic SerializeField creation (JSON serialization)

		<textarea name="code" class="JScript">
			var field = new inputEx.SerializeField({
				parentEl: 'container1',
				label: 'Your name',
				description: 'Please enter your name',

				subfield: {
							type: 'group',
							fields: [
								{ name: 'firstname', typeInvite: 'firstname' },
								{ name: 'lastname', typeInvite: 'lastname' }
							],
							required:true
				}

			});

		   var el = YAHOO.util.Dom.get('container1');

			var button1 = inputEx.cn('button', null, null, "SetValue with '{\"firstname\":\"Jimi\",\"lastname\":\"Hendrix\"}'");
			el.appendChild(button1);
			YAHOO.util.Event.addListener(button1, "click" ,function() {
			   field.setValue('{"firstname":"Jimi","lastname":"Hendrix"}');
			});

			var logDiv = inputEx.cn('div', null, null, "Log :");
			el.appendChild(logDiv);
			field.updatedEvt.subscribe(function(e,params) {
				var value = params[0];
				logDiv.innerHTML += "Updated at "+(new Date())+" with value "+value;
				logDiv.appendChild(inputEx.cn('br'));
			});
		</textarea>

XML serialization

There is an issue because ObjTree needs only 1 root element :

		<textarea name="code" class="JScript">
			var field = new inputEx.SerializeField({
				parentEl: 'container2',
				label: 'Your name',
				description: 'Please enter your name',

				serializer: 'xml',

				subfield: {
							type: 'group',
							fields: [
								{
									type: 'group',
									name: 'person',
									fields: [
										{ name: 'firstname', typeInvite: 'firstname' },
										{ name: 'lastname', typeInvite: 'lastname' }
									]
								}
							]
				}

			});

		   var el = YAHOO.util.Dom.get('container2');

			var button2 = inputEx.cn('button', null, null, "SetValue");
			el.appendChild(button2);
			YAHOO.util.Event.addListener(button2, "click" ,function() {
				var xml = String.fromCharCode(60)+'?xml version="1.0" encoding="UTF-8" ?'+String.fromCharCode(62)+String.fromCharCode(60)+'person'+String.fromCharCode(62)+String.fromCharCode(60)+'firstname'+String.fromCharCode(62)+'Jimi'+String.fromCharCode(60)+'/firstname'+String.fromCharCode(62)+String.fromCharCode(60)+'lastname'+String.fromCharCode(62)+'Hendrix'+String.fromCharCode(60)+'/lastname'+String.fromCharCode(62)+String.fromCharCode(60)+'/person'+String.fromCharCode(62);
				field.setValue(xml);
			});

			var logDiv = inputEx.cn('div', null, null, "Log :");
			el.appendChild(logDiv);
			field.updatedEvt.subscribe(function(e,params) {
				var value = params[0].replace( new RegExp(String.fromCharCode(60),"g") , '<' ).replace( new RegExp(String.fromCharCode(62),"g") , '>' );
				logDiv.innerHTML += "Updated at "+(new Date())+" with value "+inputEx.htmlEntities(value);
				logDiv.appendChild(inputEx.cn('br'));
			});
		</textarea>


text:
<?php

namespace Renegare\Soauth\Test;

use Silex\Application;
use Symfony\Component\HttpFoundation\Response;

class FlowTestCase extends WebtestCase {

    protected $mockRenderer;

    protected function configureApplication(Application $app) {
        parent::configureApplication($app);

        $app['soauth.user.provider.config'] = [
            'test@example.com' => ['password' => $app['security.encoder.digest']->encodePassword('Password123', ''), 'roles' => ['ROLE_USER'], 'enabled' => true]
        ];

        $app['soauth.client.provider.config'] = [
            '1' => [
                'name' => 'Example Client',
                'domain' => 'client.com',
                'active' => true,
                'secret' => 'cl13nt53crt'
            ],
            '2' => [
                'name' => 'Example Client',
                'domain' => 'client.com',
                'active' => false,
                'secret' => 'cl13nt53crt'
            ]
        ];

        $this->configureMocks($app);
    }

    protected function configureMocks(Application $app) {
        $this->mockRenderer = $this->getMock('Renegare\Soauth\RendererInterface');
        $app['soauth.renderer'] = $this->mockRenderer;
        $this->mockRenderer->expects($this->any())
            ->method('renderSignInForm')->will($this->returnCallback(function($data) {
                return '<form method="post">
    <input type="text" name="username" value="'. (isset($data['username'])? $data['username'] : '') .'"/>
    <input type="password" name="password" />
    <input type="hidden" name="redirect_uri" value="'. $data['redirect_uri'] .'" />
    <input type="hidden" name="client_id" value="'. $data['client_id'] .'" />
    <button type="submit">Sign-in</button>
</form>';
            }));
    }
}


text:
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;

using Pingu.Chunks;

namespace Pingu
{

    public class PngFile : IEnumerable<Chunk>
    {
        readonly List<Chunk> chunksToWrite = new List<Chunk>();
        static readonly byte[] Magic = { 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a };

        public void Add(Chunk chunk) => chunksToWrite.Add(chunk);

        IEnumerator<Chunk> IEnumerable<Chunk>.GetEnumerator() => chunksToWrite.GetEnumerator();
        IEnumerator IEnumerable.GetEnumerator() => chunksToWrite.GetEnumerator();

        public int ChunkCount => chunksToWrite.Count;

        public async Task WriteFileAsync(Stream target)
        {
            await target.WriteAsync(Magic, 0, Magic.Length).ConfigureAwait(false);
            foreach (var chunk in this)
                await chunk.WriteSelfToStreamAsync(target).ConfigureAwait(false);
        }
    }
}