text:
package com.fangcloud.sdk.http;

import com.fangcloud.sdk.util.IOUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.TimeUnit;

/**
 * An interface that the Fangcloud client library uses to make HTTP requests.
 * If you're fine with the standard Java {@link java.net.HttpURLConnection}
 * implementation, then just use {@link StandardHttpRequestor#INSTANCE}.
 */
public abstract class HttpRequestor {
    /**
     * Default timeout, in milliseconds, for opening a connection to a network resource.
     *
     * A value of 0 indicates the timeout should be disabled.
     */
    public static final long DEFAULT_CONNECT_TIMEOUT_MILLIS = TimeUnit.SECONDS.toMillis(20);
    /**
     * Default timeout, in milliseconds, for receiving a response from a network resource.
     *
     * A value of 0 indicates the timeout should be disabled.
     */
    // Careful about lowering this value. Large file uploads can result in slow responses from the
    // server.
    public static final long DEFAULT_READ_TIMEOUT_MILLIS = TimeUnit.MINUTES.toMillis(2);

    public abstract Response doGet(String url, Iterable<Header> headers) throws IOException;
    public abstract Uploader startPost(String url, Iterable<Header> headers) throws IOException;
    public abstract Uploader startPostWithStreaming(String url, Iterable<Header> headers) throws IOException;

    /**
     * A simple structure holding an HTTP header, which is key/value pair.
     * Used with {@link HttpRequestor}.
     */
    public static final class Header {
        private final String key;
        private final String value;

        public Header(String key, String value) {
            this.key = key;
            this.value = value;
        }

        /**
         * Returns header name.
         *
         * @return header name
         */
        public String getKey() {
            return key;
        }

        /**
         * Returns header value.
         *
         * @return header value
         */
        public String getValue() {
            return value;
        }
    }

    public static abstract class Uploader {
        public abstract OutputStream getBody();
        public abstract void close();
        public abstract void abort();
        public abstract Response finish() throws IOException;

        public void upload(File file) throws IOException {
            upload(new FileInputStream(file));
        }

        public void upload(InputStream in, long limit) throws IOException {
            upload(IOUtil.limit(in, limit));
        }

        public void upload(InputStream in) throws IOException {
            OutputStream out = getBody();
            try {
                IOUtil.copyStreamToStream(in, out);
            } catch (IOUtil.ReadException ex) {
                throw ex.getCause();
            } finally {
                out.close();
            }
        }

        public void upload(byte [] body) throws IOException {
            OutputStream out = getBody();
            try {
                out.write(body);
            } finally {
                out.close();
            }
        }
    }

    public static final class Response {
        private final int statusCode;
        private final InputStream body;
        private final Map<String, List<String>> headers;
        private final int contentLength;

        public Response(int statusCode, InputStream body, Map<String, ? extends List<String>> headers, int contentLength) {
            this.statusCode = statusCode;
            this.body = body;
            this.headers = asUnmodifiableCaseInsensitiveMap(headers);
            this.contentLength = contentLength;
        }

        /**
         * Returns HTTP status response code.
         *
         * @return HTTP status code
         */
        public int getStatusCode() {
            return statusCode;
        }

        /**
         * Returns an {@link InputStream} for reading the HTTP response body.
         *
         * <p> The returned stream <b>must</b> be fully read before closing.
         *
         * @return HTTP response body
         */
        public InputStream getBody() {
            return body;
        }

        /**
         * Returns a case-insensitive, unmodifiable mapping of header fields to their values.
         *
         * @return case-insensitive, unmodifiable headers
         */
        public Map<String, List<String>> getHeaders() {
            return headers;
        }

        public int getContentLength() {
            return contentLength;
        }

        private static final Map<String, List<String>> asUnmodifiableCaseInsensitiveMap(Map<String, ? extends List<String>> original) {
            Map<String, List<String>> insensitive = new TreeMap<String, List<String>>(String.CASE_INSENSITIVE_ORDER);
            for (Map.Entry<String, ? extends List<String>> entry : original.entrySet()) {
                // Java HttpURLConnection puts status line as the 'null' key.
                if (entry.getKey() == null || entry.getKey().trim().length() == 0) {
                    continue;
                }
                insensitive.put(entry.getKey(), Collections.unmodifiableList(entry.getValue()));
            }
            return Collections.unmodifiableMap(insensitive);
        }
    }
}


text:
use error::{CliError, Usage, UsageKind};
use super::Command;

use constant::MAIN_DIR;
use lib::fs::*;
use lib::setting::{Config, ConfigKey, Ignore, Storage};
use std::path::{Path, PathBuf};

#[derive(Debug)]
pub struct Sweep {
    option1: Option<String>,
    option2: Option<String>,
}

impl Command for Sweep {
    fn usage(&self) -> Usage {
        return Usage::new(UsageKind::Sweep);
    }

    fn main(&self) -> Result<(), CliError> {
        let indeed = [&self.option1, &self.option2]
            .iter()
            .any(|option| match option {
                &&Some(ref o) => o == "indeed",
                &&None        => false,
            });
        let all = match &self.option1 {
            &Some(ref o) => match o.as_ref() {
                "all"    => true,
                "indeed" => false,
                _        => return Err(From::from(self.usage())),
            },
            &None => false,
        };

        let storage = Storage::new("sweep", indeed);
        try!(storage.create_box());

        let config     = try!(Config::read());
        let moratorium = try!(config.get(ConfigKey::SweepMoratorium));
        let moratorium = Config::to_duration(moratorium);

        let ignore = try!(Ignore::read());
        let (ignored_dirs, ignored_files) = ignore.dirs_and_files();

        let target_files = walk_dir(MAIN_DIR)
            .difference(&ignored_files)
            .filter(|f| if all { true } else { !is_recently_accessed(f, &moratorium) })
            .filter(|f| !ignored_dirs.iter().any(|d| f.starts_with(d)))
            .cloned()
            .collect::<Vec<String>>();
        try!(storage.squeeze_dusts(&target_files));

        let phantom_files = if indeed {
            Vec::new()
        } else {
            target_files
                .iter()
                .map(|f| Path::new(f).to_path_buf())
                .collect::<Vec<PathBuf>>()
        };
        let potentially_empty_dirs = potentially_empty_dirs(MAIN_DIR, phantom_files);
        storage.squeeze_empty_dirs(potentially_empty_dirs).map_err(|e| From::from(e))
    }
}

impl Sweep {
    pub fn new(option1: Option<String>, option2: Option<String>) -> Self {
        Sweep { option1: option1, option2: option2 }
    }
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using ShawLib;

namespace ShawLib.TCP
{
    public class TcpClient : IDisposable
    {
        public IPAddress IP { get { return ((IPEndPoint)client.RemoteEndPoint).Address; } }
        public int Port { get { return ((IPEndPoint)client.RemoteEndPoint).Port; } }
        public bool Connected { get { return client != null ? client.Connected : false; } }

        public event EventHandler<EventArgs> OnConnect;
        public event EventHandler<ExceptionEventArgs> OnConnectFailed;
        public event EventHandler<ExceptionEventArgs> OnDisconnect;
        public event EventHandler<ReceiveEventArgs> OnReceive;

        Socket client;
        Thread threadReceive;
        bool disposed;

        /// <summary>
        /// Creates a new client instance
        /// </summary>
        public TcpClient()
            : this(new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
        { }

        // used by the client class and server class
        internal TcpClient(Socket client)
        {
            this.client = client;
        }

        void onConnectEvent()
        {
            var handler = OnConnect;
            if (handler != null)
                handler(this, EventArgs.Empty);
        }

        void onConnectFailedEvent(Exception ex)
        {
            var handler = OnConnectFailed;
            if (handler != null)
                handler(this, new ExceptionEventArgs(ex));
        }

        void onDisconnectEvent(Exception ex)
        {
            var handler = OnDisconnect;
            if (handler != null)
                handler(this, new ExceptionEventArgs(ex));
            Disconnect();
        }

        void onReceiveEvent(byte[] bytes)
        {
            var handler = OnReceive;
            if (handler != null)
                handler(this, new ReceiveEventArgs(this, bytes));
        }

        void receive()
        {
            var lengthBytes = new byte[4];
            byte[] buffer;

            try
            {
                while (client != null)
                {
                    // Receive packet length
                    if (client.Receive(lengthBytes) != lengthBytes.Length)
                        throw new Exception("Disconnected");

                    var length = BitConverter.ToInt32(lengthBytes, 0);
                    if (length <= 0)
                        throw new Exception("packet length below zero");
                    else if (length > client.ReceiveBufferSize - lengthBytes.Length)
                        throw new Exception("packet length above limit");

                    // Receive packet bytes
                    buffer = new byte[length];
                    if (client.Receive(buffer) != length)
                        throw new Exception("Disconnected, packet length did not match");

                    // Enqueue bytes into receive queue
                    onReceiveEvent(buffer);
                }
            }
            catch (Exception ex)
            {
                onDisconnectEvent(ex);
            }
        }

        /// <summary>
        /// Connects to a server
        /// </summary>
        /// <param name="ip">The server ip address</param>
        /// <param name="port">The server port</param>
        public void Connect(IPAddress ip, int port, int timeout = 3000)
        {
            if (client == null)
                client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            // only be able to bind one client to the port
            if (!client.Connected && !client.IsBound)
                client.ExclusiveAddressUse = true;

            // rise the maximun buffer, this allow bigger packets up to
            client.ReceiveBufferSize = int.MaxValue;
            client.SendBufferSize = int.MaxValue;

            bool success = false;

            try
            {
                // start connecting with a timeout of three seconds
                var result = client.BeginConnect(new IPEndPoint(ip, port), null, null);
                success = result.AsyncWaitHandle.WaitOne(timeout);

                if (success)
                    client.EndConnect(result);
            }
            catch (Exception ex)
            {
                onConnectFailedEvent(ex);
                return;
            }

            // Timeout
            if (!success)
            {
                onConnectFailedEvent(new TimeoutException());
                return;
            }

            Start();
            onConnectEvent();
        }

        public void Disconnect()
        {
            if (client != null)
            {
                client.Dispose();
                client = null;
            }
        }

        internal void Start()
        {
            threadReceive = new Thread(receive);
            threadReceive.IsBackground = true;
            threadReceive.Start();
        }

        /// <summary>
        /// Sends bytes over the network stream
        /// </summary>
        /// <param name="bytes">The bytes to be sent</param>
        /// <returns></returns>
        public bool Send(byte[] bytes)
        {
            if (!client.Connected && client != null)
                return false;

            if (bytes.Length + 4 > client.SendBufferSize)
                throw new Exception("packet length above limit");

            // Send the bytes of the packet over the network stream
            bytes = BitConverter.GetBytes(bytes.Length).Add(bytes);
            try
            {
                client.Send(bytes);
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// Diposes the client
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposed)
                return;

            if (disposing)
                Disconnect();

            disposed = true;
        }
    }
}


text:
#pragma once

#include "clanlib/core/system.h"

#include "logic/race/GameLogic.h"

namespace Race
{

class GameLogicArcadeImpl;
class GameLogicArcade : public GameLogic
{
	public:

		GameLogicArcade();
		virtual ~GameLogicArcade();

		virtual void initialize();
		virtual void destroy();

		virtual void update(unsigned p_timeElapsedMs);

		virtual void restartRace();
		unsigned getRaceStartTime() const;

	private:

		CL_SharedPtr<GameLogicArcadeImpl> m_impl;

		friend class GameLogicArcadeImpl;

};

}


text:
'use strict';

var MutatingArray = require('./lib/mutating-array');
var cache         = require('./lib/cache-v2').create();
var utils         = require('./lib/utils');

/**
 * Provides a suite of functionality around interacting with a resource on the
 * web using AJAX requests.
 *
 * @class RestModel.V2
 * @extends Ember.Object
 * @constructor
 * @param {Object} attributes the attributes to initialize the instance with
 */
module.exports = Ember.Object.extend({
  /**
   * Initialize a new instance of this class. Does so by first setting the
   * initial properties to the `originalProperties` value and by defining the
   * `dirtyProperties` property.
   *
   * @method init
   * @private
   */
  init: function() {
    this.setOriginalProperties();
    /**
     * The value of this instance's primary key. Found by iterating over the
     * class's `primaryKeys` property until this instance has a value for a
     * primary key.
     *
     * @property primaryKey
     * @private
     * @type {String,Number}
     */
    this._definePrimaryKey();

    /**
      * A list of the dirty properties on this instance.
      *
      * @property dirtyProperties
      * @type {Array}
      */
    this._defineDirtyProperties();
  },

  /**
   * A declared array of attributes of this class. These are the attributes that
   * are relied upon for the `isDirty` property, as well as other functionality.
   * Objects are not supported, but flat arrays are.
   *
   * For attributes that are arrays, indicate them as `property.[]`.
   *
   * @property attrs
   * @type {Array}
   */
  attrs: function() {
    return [];
  }.property(),

  /**
   * Whether or not the instance is "in flight", meaning that it has AJAX
   * requests in process.
   *
   * @property inFlight
   * @type {Boolean}
   */
  inFlight: Ember.computed.bool('requestPool'),

  /**
   * If the declared properties (`attrs`) of the instance are the same as their
   * original values. The opposite of `isDirty`.
   *
   * @property isClean
   * @type {Boolean}
   */
  isClean: Ember.computed.empty('dirtyProperties'),

  /**
   * If any of the declared properties (`attrs`) of the instance are different
   * from their original values. The opposite of `isClean`.
   *
   * @property isDirty
   * @type {Boolean}
   */
  isDirty: Ember.computed.notEmpty('dirtyProperties'),

  /**
   * Whether or not the record is new (has not been persisted). This property
   * should almost certainly be overriden.
   *
   * @property isNew
   * @type {Boolean}
   */
  isNew: Ember.computed.none('primaryKey'),

  /**
   * Whether or not the record has been persisted. The opposite of `isNew`.
   *
   * @property isPersisted
   * @type {Boolean}
   */
  isPersisted: Ember.computed.not('isNew'),

  /**
   * The names of the declared `attributes` without their observable modifiers
   * (e.g. will return `['tags']`, not `['tags.[]']`).
   *
   * @property attrNames
   * @private
   * @type {Array}
   */
  attrNames: function() {
    return this.get('attrs').map(function(attr) {
      if (/\.\[\]$/.test(attr)) {
        return attr.split('.')[0];
      } else {
        return attr;
      }
    });
  }.property('attrs'),

  /**
   * The parents of this instance.
   *
   * TODO: This must either be volatile or created in `init` as a computed
   *       property based on the values in `parentKeyNames`.
   *
   * @property parents
   * @private
   * @type {Object}
   */
  parents: function() {
    var parentKeyNames = this.constructor.getParentKeyNames();

    return parentKeyNames.reduce(function(parents, key) {
      parents[key] = this.get(key);
      return parents;
    }.bind(this), {});
  }.property().volatile(),

  /**
   * A path pointing to this instance, typically the class's base path joined
   * with the `primaryKey` of this instance. Will throw an error if a parent
   * necessary for building the path is lacking a primary key.
   *
   * @property path
   * @type {String}
   */
  path: function() {
    var primaryKey = this.get('isPersisted') ? this.get('primaryKey') : null;
    var parents    = this.get('parents');

    return this.constructor.buildPath(parents, primaryKey);
  }.property('primaryKey', 'parents'),

  /**
   * Delete this instance.
   *
   * @method delete
   * @async
   * @param {Object} [options] options to pass through to the AJAX request
   * @return {Ember.RSVP.Promise} a promise resolved when this instance has been
   *   deleted
   * @example
   * ```javascript
   * post.delete();
   * ```
   */
  delete: function(options) {
    return this.request('deleting', function() {
      options = utils.extend({
        url : this.get('path'),
        type: 'DELETE'
      }, options);

      return this.constructor.ajax(options).then(function() {
        return cache.removeRecord(this);
      }.bind(this));
    }.bind(this));
  },

  /**
   * Fetch this instance.
   *
   * @method fetch
   * @async
   * @param {Object} [options] options to pass through to the AJAX request
   * @return {Ember.RSVP.Promise} a promise resolved with this instance once it
   *   has been fetched
   * @example
   * ```javascript
   * post.fetch();
   * ```
   */
  fetch: function(options) {
    return this.request('fetching', function() {
      options = utils.extend({
        url : this.get('path'),
        type: 'GET'
      }, options);

      return this.constructor.request(options, {}, this).then(function(data) {
        var properties = this.constructor.getUpdatableProperties(data);
        this.setProperties(properties);
        //we assume that these must in fact be the original properties
        this.setOriginalProperties();
        return this;
      }.bind(this));
    }.bind(this));
  },

  /**
   * Persist the given data for this item to the cache.
   *
   * @method persistToCache
   * @async
   * @private
   * @param {Object} data the data to be written to the cache
   * @return {Ember.RSVP.Promise} a promise resolved with the written data
   */
  persistToCache: function(data) {
    return cache.updateRecord(this, data);
  },

  /**
   * Set the given parameter as `is#{parameter.capitalize()}` as well as
   * `inFlight` to `true` while the given function is in flight. When it is
   * resolved or rejected, set those properties to `false`.
   *
   * TODO: Need to handle the case where the same model performs the same
   *       operation at the same time, multiple times (e.g. #save and #save
   *       simultaneously).
   *
   * @method request
   * @private
   * @param {String} type the type of request the instance is entering
   * @param {Function} doRequest a function returning a promise whose finished
   *   state removes an item from the request pool
   */
  request: function(type, doRequest) {
    type = 'is%@'.fmt(type.capitalize());

    this.set(type, true);
    this.incrementProperty('requestPool');

    return doRequest().finally(function() {
      this.set(type, false);
      this.decrementProperty('requestPool');
    }.bind(this));
  },

  /**
   * Revert this instance's properties back to their original values.
   *
   * @method revert
   */
  revert: function() {
    var attrs = this.get('attrs');

    this.get('attrNames').forEach(function(key, i) {
      var value = Ember.copy(this.get('originalProperties.%@'.fmt(key)));

      if (/\.\[\]$/.test(attrs[i])) {
        this.get(key).setObjects(value);
      } else {
        this.set(key, value);
      }
    }.bind(this));
  },

  /**
   * Save this instance. If the instance is new, do a 'POST' request to the
   * class's base path, otherwise, use 'PATCH' to this instance's path.
   *
   * @method save
   * @async
   * @param {Object} [options] options to pass through to the AJAX request
   * @return {Ember.RSVP.Promise} a promise resolved with this instnace once it
   *   has been saved
   * @example
   * ```javascript
   * post.save();
   * ```
   */
  save: function(options) {
    var type = this.get('isNew') ? 'POST' : 'PATCH';

    return this.request('saving', function() {
      options = utils.extend({
        url : this.get('path'),
        type: type,
        data: this.serialize()
      }, options);

      return this.constructor.ajax(options).then(function(data) {
        return this.persistToCache(data);
      }.bind(this)).then(function(data) {
        this.setProperties(data);
        this.setOriginalProperties();
        return this;
      }.bind(this));
    }.bind(this));
  },

  /**
   * Set an object containing the original values of the instance's properties.
   *
   * @method setOriginalProperties
   * @private
   */
  setOriginalProperties: function() {
    var attrNames = this.get('attrNames');

    this.set('originalProperties', attrNames.reduce(function(properties, key) {
      var value = this.get(key);
      properties.set(key, Ember.copy(value, true));
      return properties;
    }.bind(this), Ember.Object.create()));
  },

  /**
   * Calculates dirty properties. Implements the logic behind the
   * 'dirtyProperties' property.
   *
   * @method getDirtyProperties
   * @private
   */
  getDirtyProperties: function() {
    var attrNames          = this.get('attrNames');
    var originalProperties = this.get('originalProperties');

    return attrNames.reduce(function(changedProperties, key) {
      var value         = this.get(key);
      var originalValue = originalProperties.get(key);

      if (Ember.isArray(value)) {
        if (!utils.arraysEqual(value, originalValue)) {
          changedProperties.push(key);
        }
      } else if (Ember.$.isPlainObject(value)) {
        if(!utils.objectsEqual(value, originalValue)) {
          changedProperties.push(key);
        }
      } else if (!Ember.isEqual(value, originalValue)) {
        changedProperties.push(key);
      }

      return changedProperties;
    }.bind(this), []);
  },

  /**
   * Serialize this object into JSON for sending in AJAX requests and for
   * persistent caching.
   *
   * @method serialize
   * @private
   */
  serialize: function() {
    return JSON.stringify(this.toObject());
  },

  /**
   * Get an object representation of this instance using keys from the `attrs`
   * property.
   *
   * @method toObject
   * @return {Object} the plain object representation of this instance
   */
  toObject: function() {
    return this.get('attrNames').reduce(function(properties, key) {
      var value = this.get(key);
      properties[key] = value;
      return properties;
    }.bind(this), {});
  },

  /**
   * Defines the 'primaryKey' property during initialization, as it depends
   * on the 'primaryKeys' constructor property.
   *
   * @method _definePrimaryKey
   * @static
   * @private
   */
  _definePrimaryKey: function() {
    var args = this.constructor.primaryKeys.concat(function(_, setValue) {
      var keyNames = this.constructor.primaryKeys;
      if (setValue === undefined) {
        var key, value;
        for (var i = 0; i < keyNames.length; i++) {
          key   = keyNames[i];
          value = this.get(key);

          if (!Ember.isNone(value)) {
            return value;
          }
        }
      } else {
        if (this.get('primaryKey') !== setValue) {
          this.set(keyNames[0], setValue);
        }
        return setValue;
      }
    });
    var primaryKey = Ember.computed.apply(Ember, args);
    Ember.defineProperty(this, 'primaryKey', primaryKey);
  },

  /*
   * Defines the property 'dirtyProperties'. Used during initialization.
   *
   * @method _defineDirtyProperties
   * @private
   */
  _defineDirtyProperties: function() {
    var args = this.get('attrs')
                   .concat('originalProperties', this.getDirtyProperties);
    var dirtyProperties = Ember.computed.apply(Ember, args);
    Ember.defineProperty(this, 'dirtyProperties', dirtyProperties);
  }
}).reopenClass({
  /**
   * The lowercase string version of the name of this class, used for caching
   * purposes. This must be overridden.
   *
   * @property typeKey
   * @static
   * @type String
   */
  typeKey: '',

  /**
   * An array of properties used to fetch and persist records. An array is used
   * because multiple properties may be used as primary keys in an API, e.g.
   * "id" and "name".
   *
   * @property primaryKeys
   * @static
   * @type Array
   * @default ['id']
   */
  primaryKeys: ['id'],

  /**
   * A namespace under which to nest all AJAX requests for this class. This is
   * commonly something like 'api'.
   *
   * @property namespace
   * @static
   * @type String
   * @default null
   */
  namespace: null,

  /**
   * The base path used to fetch, persist, and destroy records. Must not begin
   * with or end with a forward slash ('/').
   *
   * @property base
   * @static
   * @type String
   * @default ''
   */
  base: '',

  /**
   * Whether or not to cache GET calls when using the `::request` method.
   *
   * @property cache
   * @static
   * @type Boolean
   * @default false
   */
  cache: false,

  /**
   * An array of filters that will be called on each array returned by this
   * class.
   *
   * @property filters
   * @static
   * @type Array<Function>
   * @default []
   */
  filters: [],

  /**
   * Perform an AJAX request.
   *
   * @method ajax
   * @async
   * @static
   * @param {Object} options options to define the AJAX request
   * @param {String} options.url the path or URL to make the request to
   * @param {String} [options.type='GET'] the HTTP method used to make the
   *   request
   * @param {String} [options.data] a JSON string of data to send as the
   *   request body
   * @return {Ember.RSVP.Promise} a promise resolved with an instance or array
   *   of instances of this class, as well as the original response data, once
   *   the request has completed
   * ```
   */
  ajax: function(options) {
    var ajaxOptions = {
      type       : 'GET',
      dataType   : 'json',
      contentType: 'application/json'
    };

    utils.extend(ajaxOptions, options);

    return new Ember.RSVP.Promise(function(resolve, reject) {
      Ember.$.ajax(ajaxOptions).then(function(data) {
        if (Ember.isArray(data)) {
          data = this.deserializeArray(data);
        } else {
          data = this.deserialize(data);
        }

        resolve(data);
      }.bind(this), function(jqXHR) {
        delete jqXHR.then;
        reject(jqXHR);
      });
    }.bind(this));
  },

  /**
   * Fetch all records for this class.
   *
   * @method all
   * @static
   * @async
   * @param {Object} [parents] the parents of this resource, with either
   *   instances or primary keys as values
   * @param {Object} [options] options to pass on to the AJAX request
   * @return {Ember.RSVP.Promise} a promise resolved with an array of instances
   *   of this class
   * @example
   * ```javascript
   * Post.all();
   *
   * // With parents
   * Comment.all({ post: 1 });
   * ```
   */
  all: function(parents, options) {
    options = utils.extend({
      url : this.buildPath(parents),
      type: 'GET'
    }, options);

    var processingOptions = { parents: parents };

    return this.request(options, processingOptions).then(function(results) {
      return results;
    });
  },

  /**
   * Add an object of parents to the given path.
   *
   * @method addParentsToPath
   * @static
   * @private
   * @param {Object} parents the parents to add to the given path
   * @param {String} path the path to add the parents to
   * @return {String} the path with parent primary keys interpolated
   */
  addParentsToPath: function(parents, path) {
    Ember.$.each(parents, function(key, parent) {
      var parentKey = parent;

      if (typeof parent !== 'string' && typeof parent !== 'number') {
        parentKey = parent.get('primaryKey');
      }

      path = path.replace('/:%@'.fmt(key), '/%@'.fmt(parentKey));
    });

    return path;
  },

  /**
   * Assert that the given object of parent keys is enough for the base path of
   * this class. Throws an error if there are parent keys missing.
   *
   * @method assertHasParentKeys
   * @static
   * @private
   * @param {Object} parents the parents to validate are sufficient for this
   *   class
   */
  assertHasParentKeys: function(parents) {
    this.getParentKeyNames().forEach(function(key) {
      var parent     = parents[key];
      var primaryKey = parent ? this.getPrimaryKey(parent) : null;

      if (Ember.isNone(primaryKey)) {
        throw new Error('No primary key found for parent "%@".'.fmt(key));
      }
    }.bind(this));
  },

  /**
   * Build a path to this resource, adding parent keys and a primary key (if
   * supplied).
   *
   * @method buildPath
   * @static
   * @private
   * @param {Array} [parents] the parent keys or objects to use in the path
   * @param {Number,String} [primaryKey] a primary to be appended to the path
   * @return {String} the path including any given primary key
   */
  buildPath: function(parents, primaryKey) {
    var path = '/' + this.base;

    if (!Ember.$.isPlainObject(parents)) {
      primaryKey = parents;
      parents    = {};
    }

    this.assertHasParentKeys(parents);
    path = this.addParentsToPath(parents, path);

    if (!Ember.isNone(primaryKey)) {
      path += '/' + primaryKey;
    }

    if (!Ember.isNone(this.namespace)) {
      path = '/' + this.namespace + path;
    }

    return path;
  },

  /**
   * Deserialize data into a desirable format for updating and creating
   * instances of this class. By default, this is a no-op.
   *
   * @method deserialize
   * @static
   * @private
   * @param {Object} data the data to be deserialized
   * @return {Object} (optionally) transformed data object
   */
  deserialize: function(data) {
    return data;
  },

  /**
   * Deserialize an array of objects into an array of objects formatted for
   * updating and creating instances of this class.
   *
   * @method deserializeArray
   * @static
   * @private
   * @param {Array} data an array of objects to be deserialized
   * @return {Array} an array of (optionally) transformed objects
   */
  deserializeArray: function(data) {
    return data.map(this.deserialize.bind(this));
  },

  /**
   * Find a record by primary key.
   *
   * @method find
   * @async
   * @static
   * @param {Number,String} primaryKey the primary key used to find a record
   * @param {Object} [options] options to pass on to the AJAX request
   * @return {Ember.RSVP.Promise} a promise resolved with an instance of this
   *   class
   * ```javascript
   * Post.find(1);
   * ```
   */
  find: function(parents, primaryKey, options) {
    if (!Ember.$.isPlainObject(parents)) {
      options    = primaryKey;
      primaryKey = parents;
      parents    = {};
    }

    options = utils.extend({
      url : this.buildPath(parents, primaryKey),
      type: 'GET'
    }, options);

    return this.request(options)
      .then(this.create.bind(this)).then(function(model) {
        model.setProperties(parents);
        return model;
      });
  },

  /**
   * Get the names of the parent keys for this class.
   *
   * @method getParentKeyNames
   * @static
   * @private
   * @return {Array} the names of the parent keys based on the class's base
   */
  getParentKeyNames: function() {
    var matches = this.base.match(/\/:[^\/]+/g) || [];

    return matches.map(function(segment) {
      return segment.replace('/:', '');
    });
  },

  /**
   * Return either the value (if it is a simple value) or the primary key
   * of the given object.
   *
   * @method getPrimaryKey
   * @static
   * @private
   * @param {RestModel,String,Number} object the object to get the primary key
   *   from
   * @return {String,Number} a primary key
   */
  getPrimaryKey: function(object) {
    if (typeof object === 'number' || typeof object === 'string') {
      return object;
    } else {
      return object.get('primaryKey');
    }
  },

  /**
   * Transform results from an API request into an instance or array of
   * instances of this class.
   *
   * Accepts an object of parent properties to ensure that cached and new
   * records always have a reference to their parent records.
   *
   * @method toResult
   * @static
   * @private
   * @param {Array,Object} response an object or array of objects
   * @param {Object} [parents={}] an object of parent properties to set on the
   *   object or array of objects
   * @return {Array,RestModel} an instance or array of instances of this class
   */
  toResult: function(response, parents) {
    parents = parents || {};

    if (Ember.isArray(response)) {
      var content = response.map(function(item) {
        return this.create(item).setProperties(parents);
      }.bind(this));

      return MutatingArray.apply(content)
        .set('filters', Ember.copy(this.filters))
        .runFilters();
    } else {
      return this.create(response).setProperties(parents);
    }
  },

  /**
   * Request a given resource. Will use caching if the request is a "GET"
   * request.
   *
   * @method request
   * @async
   * @static
   * @param {Object} options options to pass on to the AJAX request
   * @param {Object} [processingOptions] options that control how the
   *   deserialized response is processed
   * @param {RestModel.V2} updateModel a model to be updated after a later API
   *   request instead of the original model returned
   * @param {Function} [processingOptions.toResult=RestModel.toResult] a
   *   function used to convert the response body into an instance or array of
   *   instances of RestModel
   * @return {Ember.RSVP.Promise} a promise resolved with an instance or array
   *   of instances from the cache or AJAX request
   * @example
   * ```javascript
   * Post.request({
   *   type: 'POST',
   *   url : '/custom-url',
   *   data: { foo: 'bar' }
   * });
   * ```
   */
  request: function(options, processingOptions, updateModel) {
    var readFromCache = this.cache && options.type.toLowerCase() === 'get';

    processingOptions = utils.extend({
      toResult   : this.toResult.bind(this)
    }, processingOptions);

    if (readFromCache) {
      return this.requestWithCache(options, processingOptions, updateModel);
    } else {
      return this.ajax(options).then(function(response) {
        var parents = processingOptions.parents;
        return processingOptions.toResult(response, parents);
      });
    }
  },

  /**
   * Request a given resource. If the resource is in the cache, resolve with the
   * cached version. The cached object returned will be updated when a
   * subsequent AJAX call completes, either by setting properties or by pushing
   * and deleting objects in the case of an array.
   *
   * @method requestWithCache
   * @async
   * @static
   * @private
   * @param {Object} options options to pass on to the AJAX request
   * @param {Object} [processingOptions] options that control how the
   *   deserialized response is processed
   * @param {RestModel.V2} updateModel a model to be updated after a later API
   *   request instead of the original model returned
   * @return {Ember.RSVP.Promise} a promise resolved with an object or array of
   *   objects from the cache or AJAX request
   */
  requestWithCache: function(options, processingOptions, updateModel) {
    var cachedValue;

    return cache.getResponse(this, options.url).then(function(_cachedValue) {
      var result;

      cachedValue = _cachedValue;

      if (cachedValue) {
        result = processingOptions.toResult(cachedValue, processingOptions.parents);
        this.ajaxAndUpdateCache(options, processingOptions, updateModel || result);
        return result;
      } else {
        return this.ajaxAndUpdateCache(options, processingOptions)
          .then(function(response) {
            return processingOptions.toResult(response);
          });
      }
    }.bind(this)).then(function(response) {
      return response;
    });
  },

  /**
   * Perform an AJAX request, update its value in the cache, and if given a
   * `cachedValue`, update it in a KVO-friendly way.
   *
   * @method ajaxAndUpdateCache
   * @async
   * @static
   * @private
   * @param {Object} options options to pass on to the AJAX request
   * @param {Array,Object} result a cached result that will be updated with new
   *   objects or properties from the AJAX request
   * @return {Ember.RSVP.Promise} a promise resolved with the newly updated
   *   cached value
   */
  ajaxAndUpdateCache: function(options, processingOptions, result) {
    var parents = processingOptions.parents;

    return this.ajax(options).then(function(response) {
      return cache.setResponse(this, options.url, response);
    }.bind(this)).then(function(response) {
      response = processingOptions.toResult(response, parents);

      if (result) {
        if (Ember.isArray(response)) {
          return this.updateCachedArray(result, response);
        } else {
          return this.updateCachedObject(result, response);
        }
      } else {
        return response;
      }
    }.bind(this));
  },

  /**
   * Update a cached array of objects. Add new objects, remove deleted objects,
   * and update existing objects.
   *
   * @method updateCachedArray
   * @async
   * @static
   * @private
   * @param {Array} result the array of RestModel instances to be updated
   * @param {Array} newArray the new values to update the cached array with
   * @return {Ember.RSVP.Promise} a promise resolved with the newly updated
   *   cached array
   */
  updateCachedArray: function(result, newArray) {
    var newRecords     = utils.findNotIn(newArray, result, this);
    var removedRecords = utils.findNotIn(result, newArray, this);
    var updatedRecords = utils.findIn(result, newArray, this);

    result.pushObjects(newRecords);
    result.removeObjects(removedRecords);

    updatedRecords.forEach(function(record) {
      if (record.get('isDirty')) { return; }
      var newProperties = utils.findMatching(record, this, newArray);
      newProperties = this.getUpdatableProperties(newProperties);
      record.setProperties(newProperties);
      record.setOriginalProperties();
    }.bind(this));

    return result;
  },

  /**
   * Update a cached object by setting its new properties.
   *
   * @method updateCachedObject
   * @async
   * @static
   * @private
   * @param {Array} cachedObject the object to be updated
   * @param {Array} newProperties the new properties to update the cached object
   *   with
   * @return {Ember.RSVP.Promise} a promise resolved with the newly updated
   *   cached object
   */
  updateCachedObject: function(result, newProperties) {
    if (result.get('isDirty')) { return; }
    newProperties = this.getUpdatableProperties(newProperties);
    result.setProperties(newProperties);
    result.setOriginalProperties();
    return result;
  },

  /**
   * A list of attributes that can be used to update a cached object after an
   * AJAX call has been made. Meant to exclude special properties added by
   * RestModel.
   *
   * @method getUpdatableProperties
   * @static
   * @private
   * @param {RestModel} model the model to pull properties from
   * @return {Array} an array of property names
   */
  getUpdatableProperties: function(model) {
    var keys = Ember.keys(model).filter(function(key) {
      return ['originalProperties', 'dirtyProperties'].indexOf(key) === -1;
    });

    return model.getProperties(keys);
  }
});


text:
package com.amazonaws.services.identitymanagement.model;

import java.io.Serializable;

import com.amazonaws.AmazonWebServiceRequest;

/**
 * Container for the parameters to the {@link com.amazonaws.services.identitymanagement.AmazonIdentityManagement#getGroup(GetGroupRequest) GetGroup operation}.
 *

 * Returns a list of users that are in the specified group. You can
 * paginate the results using the MaxItems and
 * Marker parameters.
 *

 *
 * @see com.amazonaws.services.identitymanagement.AmazonIdentityManagement#getGroup(GetGroupRequest)
 */
public class GetGroupRequest extends AmazonWebServiceRequest implements Serializable, Cloneable {

    /**
     * The name of the group.
     *

     * Constraints:

     * Length: 1 - 128

     * Pattern: [\w+=,.@-]+

     */
    private String groupName;

    /**
     * Use this parameter only when paginating results and only after you
     * receive a response indicating that the results are truncated. Set it
     * to the value of the Marker element in the response you
     * received to inform the next call about where to start.
     *

     * Constraints:

     * Length: 1 - 320

     * Pattern: [\u0020-\u00FF]+

     */
    private String marker;

    /**
     * Use this only when paginating results to indicate the maximum number
     * of items you want in the response. If there are additional items
     * beyond the maximum you specify, the IsTruncated response
     * element is true.
This parameter is optional. If you do
     * not include it, it defaults to 100. Note that IAM might return fewer
     * results, even when there are more results available. If this is the
     * case, the IsTruncated response element returns
     * true and Marker contains a value to include
     * in the subsequent call that tells the service where to continue from.
     *

     * Constraints:

     * Range: 1 - 1000

     */
    private Integer maxItems;

    /**
     * Default constructor for a new GetGroupRequest object.  Callers should use the
     * setter or fluent setter (with...) methods to initialize this object after creating it.
     */
    public GetGroupRequest() {}

    /**
     * Constructs a new GetGroupRequest object.
     * Callers should use the setter or fluent setter (with...) methods to
     * initialize any additional object members.
     *
     * @param groupName The name of the group.
     */
    public GetGroupRequest(String groupName) {
        setGroupName(groupName);
    }

    /**
     * The name of the group.
     *

     * Constraints:

     * Length: 1 - 128

     * Pattern: [\w+=,.@-]+

     *
     * @return The name of the group.
     */
    public String getGroupName() {
        return groupName;
    }

    /**
     * The name of the group.
     *

     * Constraints:

     * Length: 1 - 128

     * Pattern: [\w+=,.@-]+

     *
     * @param groupName The name of the group.
     */
    public void setGroupName(String groupName) {
        this.groupName = groupName;
    }

    /**
     * The name of the group.
     *

     * Returns a reference to this object so that method calls can be chained together.
     *

     * Constraints:

     * Length: 1 - 128

     * Pattern: [\w+=,.@-]+

     *
     * @param groupName The name of the group.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public GetGroupRequest withGroupName(String groupName) {
        this.groupName = groupName;
        return this;
    }

    /**
     * Use this parameter only when paginating results and only after you
     * receive a response indicating that the results are truncated. Set it
     * to the value of the Marker element in the response you
     * received to inform the next call about where to start.
     *

     * Constraints:

     * Length: 1 - 320

     * Pattern: [\u0020-\u00FF]+

     *
     * @return Use this parameter only when paginating results and only after you
     *         receive a response indicating that the results are truncated. Set it
     *         to the value of the Marker element in the response you
     *         received to inform the next call about where to start.
     */
    public String getMarker() {
        return marker;
    }

    /**
     * Use this parameter only when paginating results and only after you
     * receive a response indicating that the results are truncated. Set it
     * to the value of the Marker element in the response you
     * received to inform the next call about where to start.
     *

     * Constraints:

     * Length: 1 - 320

     * Pattern: [\u0020-\u00FF]+

     *
     * @param marker Use this parameter only when paginating results and only after you
     *         receive a response indicating that the results are truncated. Set it
     *         to the value of the Marker element in the response you
     *         received to inform the next call about where to start.
     */
    public void setMarker(String marker) {
        this.marker = marker;
    }

    /**
     * Use this parameter only when paginating results and only after you
     * receive a response indicating that the results are truncated. Set it
     * to the value of the Marker element in the response you
     * received to inform the next call about where to start.
     *

     * Returns a reference to this object so that method calls can be chained together.
     *

     * Constraints:

     * Length: 1 - 320

     * Pattern: [\u0020-\u00FF]+

     *
     * @param marker Use this parameter only when paginating results and only after you
     *         receive a response indicating that the results are truncated. Set it
     *         to the value of the Marker element in the response you
     *         received to inform the next call about where to start.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public GetGroupRequest withMarker(String marker) {
        this.marker = marker;
        return this;
    }

    /**
     * Use this only when paginating results to indicate the maximum number
     * of items you want in the response. If there are additional items
     * beyond the maximum you specify, the IsTruncated response
     * element is true.
This parameter is optional. If you do
     * not include it, it defaults to 100. Note that IAM might return fewer
     * results, even when there are more results available. If this is the
     * case, the IsTruncated response element returns
     * true and Marker contains a value to include
     * in the subsequent call that tells the service where to continue from.
     *

     * Constraints:

     * Range: 1 - 1000

     *
     * @return Use this only when paginating results to indicate the maximum number
     *         of items you want in the response. If there are additional items
     *         beyond the maximum you specify, the IsTruncated response
     *         element is true.
This parameter is optional. If you do
     *         not include it, it defaults to 100. Note that IAM might return fewer
     *         results, even when there are more results available. If this is the
     *         case, the IsTruncated response element returns
     *         true and Marker contains a value to include
     *         in the subsequent call that tells the service where to continue from.
     */
    public Integer getMaxItems() {
        return maxItems;
    }

    /**
     * Use this only when paginating results to indicate the maximum number
     * of items you want in the response. If there are additional items
     * beyond the maximum you specify, the IsTruncated response
     * element is true.
This parameter is optional. If you do
     * not include it, it defaults to 100. Note that IAM might return fewer
     * results, even when there are more results available. If this is the
     * case, the IsTruncated response element returns
     * true and Marker contains a value to include
     * in the subsequent call that tells the service where to continue from.
     *

     * Constraints:

     * Range: 1 - 1000

     *
     * @param maxItems Use this only when paginating results to indicate the maximum number
     *         of items you want in the response. If there are additional items
     *         beyond the maximum you specify, the IsTruncated response
     *         element is true.
This parameter is optional. If you do
     *         not include it, it defaults to 100. Note that IAM might return fewer
     *         results, even when there are more results available. If this is the
     *         case, the IsTruncated response element returns
     *         true and Marker contains a value to include
     *         in the subsequent call that tells the service where to continue from.
     */
    public void setMaxItems(Integer maxItems) {
        this.maxItems = maxItems;
    }

    /**
     * Use this only when paginating results to indicate the maximum number
     * of items you want in the response. If there are additional items
     * beyond the maximum you specify, the IsTruncated response
     * element is true.
This parameter is optional. If you do
     * not include it, it defaults to 100. Note that IAM might return fewer
     * results, even when there are more results available. If this is the
     * case, the IsTruncated response element returns
     * true and Marker contains a value to include
     * in the subsequent call that tells the service where to continue from.
     *

     * Returns a reference to this object so that method calls can be chained together.
     *

     * Constraints:

     * Range: 1 - 1000

     *
     * @param maxItems Use this only when paginating results to indicate the maximum number
     *         of items you want in the response. If there are additional items
     *         beyond the maximum you specify, the IsTruncated response
     *         element is true.
This parameter is optional. If you do
     *         not include it, it defaults to 100. Note that IAM might return fewer
     *         results, even when there are more results available. If this is the
     *         case, the IsTruncated response element returns
     *         true and Marker contains a value to include
     *         in the subsequent call that tells the service where to continue from.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public GetGroupRequest withMaxItems(Integer maxItems) {
        this.maxItems = maxItems;
        return this;
    }

    /**
     * Returns a string representation of this object; useful for testing and
     * debugging.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getGroupName() != null) sb.append("GroupName: " + getGroupName() + ",");
        if (getMarker() != null) sb.append("Marker: " + getMarker() + ",");
        if (getMaxItems() != null) sb.append("MaxItems: " + getMaxItems() );
        sb.append("}");
        return sb.toString();
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getGroupName() == null) ? 0 : getGroupName().hashCode());
        hashCode = prime * hashCode + ((getMarker() == null) ? 0 : getMarker().hashCode());
        hashCode = prime * hashCode + ((getMaxItems() == null) ? 0 : getMaxItems().hashCode());
        return hashCode;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null) return false;

        if (obj instanceof GetGroupRequest == false) return false;
        GetGroupRequest other = (GetGroupRequest)obj;

        if (other.getGroupName() == null ^ this.getGroupName() == null) return false;
        if (other.getGroupName() != null && other.getGroupName().equals(this.getGroupName()) == false) return false;
        if (other.getMarker() == null ^ this.getMarker() == null) return false;
        if (other.getMarker() != null && other.getMarker().equals(this.getMarker()) == false) return false;
        if (other.getMaxItems() == null ^ this.getMaxItems() == null) return false;
        if (other.getMaxItems() != null && other.getMaxItems().equals(this.getMaxItems()) == false) return false;
        return true;
    }

    @Override
    public GetGroupRequest clone() {

            return (GetGroupRequest) super.clone();
    }

}


text:
import {parseAndGetStatementInVariableDeclarator} from '../../../utils';
import {expect} from 'chai';

describe('VariableDeclarator', () => {
    it('should return correct type', () => {
        expect(parseAndGetStatementInVariableDeclarator('x').type).to.equal('VariableDeclarator');
    });

    it('should accept declaration without init', () => {
        let statement = parseAndGetStatementInVariableDeclarator('x');
        expect(statement.type).to.equal('VariableDeclarator');
        expect(statement.id.name).to.equal('x');
        expect(statement.init).to.equal(null);
    });

    it('should accept declaration with init', () => {
        let statement = parseAndGetStatementInVariableDeclarator('x = 1');
        expect(statement.type).to.equal('VariableDeclarator');
        expect(statement.id.name).to.equal('x');
        expect(statement.init.type).to.equal('NumericLiteral');
        expect(statement.init.value).to.equal(1);
    });

    it('should accept declaration with parentheses', () => {
        let statement = parseAndGetStatementInVariableDeclarator('x = ( 1 )');
        expect(statement.type).to.equal('VariableDeclarator');
        expect(statement.id.name).to.equal('x');
        expect(statement.init.type).to.equal('NumericLiteral');
        expect(statement.init.value).to.equal(1);
    });

    it('should accept array pattern', () => {
        let statement = parseAndGetStatementInVariableDeclarator('[ x ] = ( 1 )');
        expect(statement.type).to.equal('VariableDeclarator');
        expect(statement.id.type).to.equal('ArrayPattern');
        expect(statement.id.elements[0].type).to.equal('Identifier');
        expect(statement.id.elements[0].name).to.equal('x');
        expect(statement.init.type).to.equal('NumericLiteral');
        expect(statement.init.value).to.equal(1);
    });

    it('should accept object pattern', () => {
        let statement = parseAndGetStatementInVariableDeclarator('{ x } = ( 1 )');
        expect(statement.type).to.equal('VariableDeclarator');
        expect(statement.id.type).to.equal('ObjectPattern');
        expect(statement.id.properties[0].key.type).to.equal('Identifier');
        expect(statement.id.properties[0].key.name).to.equal('x');
        expect(statement.init.type).to.equal('NumericLiteral');
        expect(statement.init.value).to.equal(1);
    });
});


text:
#ifndef __SYSCON_H
#define __SYSCON_H

/**
 * struct syscon_uc_info - Information stored by the syscon UCLASS_UCLASS
 *
 * @regmap:	Register map for this controller
 */
struct syscon_uc_info {
	struct regmap *regmap;
};

/* So far there are no ops so this is a placeholder */
struct syscon_ops {
};

#define syscon_get_ops(dev)        ((struct syscon_ops *)(dev)->driver->ops)

/**
 * syscon_get_regmap() - Get access to a register map
 *
 * @dev:	Device to check (UCLASS_SCON)
 * @info:	Returns regmap for the device
 * @return 0 if OK, -ve on error
 */
struct regmap *syscon_get_regmap(struct udevice *dev);

/**
 * syscon_get_regmap_by_driver_data() - Look up a controller by its ID
 *
 * Each system controller can be accessed by its driver data, which is
 * assumed to be unique through the scope of all system controllers that
 * are in use. This function looks up the controller given this driver data.
 *
 * @driver_data:	Driver data value to look up
 * @devp:		Returns the controller correponding to @driver_data
 * @return 0 on success, -ENODEV if the ID was not found, or other -ve error
 *	   code
 */
int syscon_get_by_driver_data(ulong driver_data, struct udevice **devp);

/**
 * syscon_get_regmap_by_driver_data() - Look up a controller by its ID
 *
 * Each system controller can be accessed by its driver data, which is
 * assumed to be unique through the scope of all system controllers that
 * are in use. This function looks up the regmap given this driver data.
 *
 * @driver_data:	Driver data value to look up
 * @return register map correponding to @driver_data, or -ve error code
 */
struct regmap *syscon_get_regmap_by_driver_data(ulong driver_data);

/**
 * syscon_get_first_range() - get the first memory range from a syscon regmap
 *
 * @driver_data:	Driver data value to look up
 * @return first region of register map correponding to @driver_data, or
 *			-ve error code
 */
void *syscon_get_first_range(ulong driver_data);

#endif


text:
package org.spongepowered.api.world;

import com.flowpowered.math.vector.Vector3d;
import org.slf4j.Logger;
import org.spongepowered.api.Game;
import org.spongepowered.api.scheduler.Scheduler;
import org.spongepowered.api.scheduler.Task;
import org.spongepowered.api.util.ResettableBuilder;

import javax.annotation.Nullable;

/**
 * A world border is a square boundary, extending through the entire y-axis.
 *
 *
It can gradually grow or shrink to a radius over a period of time.
 * A warning is displayed when a contracting world border will reach the player
 * in a certain amount of time, or when the player is a certain number of
 * blocks away.

 *
 *
In Minecraft, a warning is displayed in the form of a reddish tint.

 */
public interface WorldBorder {

    /**
     * Get the diameter the world border is expanding or contracting to.
     *
     *
This will return the same value as {@link #getDiameter} unless
     * {@link #getTimeRemaining} is greater than 0.

     *
     * @return The diameter being changed to
     */
    double getNewDiameter();

    /**
     * Get the diameter of the world border.
     *
     *
The returned diameter applies to the x and z axis. The world border
     * extends over the entire y-axis.

     *
     * @return The diameter
     */
    double getDiameter();

    /**
     * Set the diameter of the world border.
     *
     *
The specified diameter applies to the x and z axis. The world border
     * extends over the entire y-axis.

     *
     * @param diameter The diameter
     */
    void setDiameter(double diameter);

    /**
     * Set the diameter of the world border, over the given period of time.
     *
     *
The world border diameter increases/decrease linearly over the specified time.
     * The specified diameter applies to the x and z axis. The world border
     * extends over the entire y-axis.

     *
     * @param diameter The diameter where the border will expand/contract to
     * @param time     The time over which to change, in milliseconds
     */
    void setDiameter(double diameter, long time);

    /**
     * Set the starting diameter and the ending diameter of the world border, over the given period of time.
     *
     *
The world border diameter increases/diameter linearly over the specified time.
     * The specified diameter applies to the x and z axis. The world border
     * extends over the entire y-axis.

     *
     * @param startDiameter The diameter where the border will start
     * @param endDiameter   The diameter where the border will end
     * @param time          The time over which to change, in milliseconds
     */
    void setDiameter(double startDiameter, double endDiameter, long time);

    /**
     * Get the time remaining until the world border stops expanding or contracting.
     *
     * @return The time remaining, in milliseconds
     */
    long getTimeRemaining();

    /**
     * Set the center of the world border.
     *
     * @param x The x-axis center of the world border
     * @param z The z-axis center of the world border
     */
    void setCenter(double x, double z);

    /**
     * Get the center of the world border.
     *
     *
The returned position is three-dimensional. As the worldborder extends
     * over the entire y-axis, the returned position will always have
     * a {@code y} set to 0.

     *
     * @return The center
     */
    Vector3d getCenter();

    /**
     * Get the time when a contracting world border will warn a player for whom
     * the world border will reach in {@code time} seconds.
     *
     *
In Minecraft, the warning is displayed in the form of a
     * reddish tint.

     *
     * @return The time, in seconds
     */
    int getWarningTime();

    /**
     * Set the time when a contracting world border will warn a player for whom
     * the world border will reach in {@code time} seconds.
     *
     *
In Minecraft, the warning is displayed in the form of a
     * reddish tint.

     *
     * @param time The time, in seconds
     */
    void setWarningTime(int time);

    /**
     * Get the distance when a contracting world border will warn a player for whom
     * the world border is {@code distance} blocks away.
     *
     *
In Minecraft, the warning is displayed in the form of a
     * reddish tint.

     *
     * @return The distance, in blocks
     */
    int getWarningDistance();

    /**
     * Set the distance when a contracting world border will warn a player for whom
     * the world border is {@code distance} blocks away.
     *
     *
In Minecraft, the warning is displayed in the form of a
     * reddish tint.

     *
     * @param distance The distance, in blocks
     */
    void setWarningDistance(int distance);

    /**
     * Get the distance a player may be outside the world border before
     * taking damage.
     *
     * @return The distance
     */
    double getDamageThreshold();

    /**
     * Set the distance a player may be be outside the world border before
     * taking damage.
     *
     * @param distance The distance
     */
    void setDamageThreshold(double distance);

    /**
     * Get the damage done to a player per block per tick when outside the
     * buffer.
     *
     * @return The damage amount
     */
    double getDamageAmount();

    /**
     * Set the damage done to a player per block per tick when outside the
     * buffer.
     *
     * @param damage The damage amount
     */
    void setDamageAmount(double damage);

    /**
     * Returns a new builder for creating a task to pre-generate the chunks
     * inside the border. The current state of the border is "snapshoted" for
     * the builder. It is not backed by this instance. If the border size is
     * changing then the target size is used.
     *
     * @param world The target world
     * @return The builder for the chunk pre-generate task
     * @see ChunkPreGenerate
     */
    ChunkPreGenerate newChunkPreGenerate(World world);

    /**
     * A builder for submitting a task to pre-generate chunks inside a world
     * border.
     *
     *
The task is synchronous and repeating with a given interval and
     * either a target number of chunks per ticks and/or a percentage of the
     * tick time.

     *
     *
Chunk order is not defined but a proper implementation should use
     * and "inside-out" strategy for better results if the task is
     * cancelled.

     *
     * @see WorldBorder#newChunkPreGenerate(World)
     * @see World#newChunkPreGenerate(Vector3d, double)
     */
    interface ChunkPreGenerate extends ResettableBuilder<Task, ChunkPreGenerate> {

        /**
         * Sets the owner of the resulting task.
         *
         *
Mandatory.

         *
         * @param plugin The owner plugin
         * @return This for chained calls
         */
        ChunkPreGenerate owner(Object plugin);

        /**
         * Sets the logger for logging generator efforts.
         *
         *
Optional.

         *
         * @param logger A logger for the generator
         * @return This for chained calls
         */
        ChunkPreGenerate logger(@Nullable Logger logger);

        /**
         * Sets the interval between generation runs.
         *
         *
Must be greater than 0.

         *
         *
Optional.

         *
         *
Default is 10.

         *
         * @param tickInterval The tick interval
         * @return This for chained calls
         */
        ChunkPreGenerate tickInterval(int tickInterval);

        /**
         * Sets maximum number of chunks per tick to generate.
         *
         *
Use a value smaller or equal to 0 to disable.

         *
         *
Optional if {@link #tickPercentLimit(float)} is used.

         *
         *
Default is disabled.

         *
         * @param chunkCount The maximum number of chunks to generate
         * @return This for chained calls
         */
        ChunkPreGenerate chunksPerTick(int chunkCount);

        /**
         * Sets the limit of tick time that can be used to generate chunks
         * as a percentage of {@link Scheduler#getPreferredTickInterval()}. The
         * percentage should be a value in the range (0, 1]. No estimation is
         * used to decide when to stop so the actual value will always be
         * somewhere above the given percentage.
         *
         *
Use a value smaller or equal to 0 to disable.

         *
         *
Optional if {@link #chunksPerTick(int)} is used.

         *
         *
Default is 15%.

         *
         * @param tickPercent The
         * @return This for chained calls
         */
        ChunkPreGenerate tickPercentLimit(float tickPercent);

        /**
         * Schedules the task with the {@link Game#getScheduler()}.
         *
         * @return The resulting task
         */
        Task start();

    }

}


text:
package org.apache.aries.jpa.support.osgi.impl;

import java.util.Dictionary;
import java.util.Hashtable;

import javax.transaction.TransactionManager;

import org.apache.aries.jpa.supplier.EmSupplier;
import org.apache.aries.jpa.support.impl.XAJpaTemplate;
import org.apache.aries.jpa.template.JpaTemplate;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.coordinator.Coordinator;
import org.osgi.service.jpa.EntityManagerFactoryBuilder;
import org.osgi.util.tracker.ServiceTracker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Is created for an EntityManagerFactory with JTA transactions and creates
 * an XaJpaTemplate for it as soon as the TransactionManager service is present.
 */
@SuppressWarnings("rawtypes")
public class TMTracker extends ServiceTracker<TransactionManager, ServiceRegistration> {
    private static final Logger LOG = LoggerFactory.getLogger(TMTracker.class);
    static final String TRANSACTION_TYPE = "transaction.type";

    private final EmSupplier emSupplier;
    private final String unitName;

    private Coordinator coordinator;

    public TMTracker(BundleContext context, EmSupplier emSupplier, String unitName, Coordinator coordinator) {
        super(context, TransactionManager.class, null);
        this.emSupplier = emSupplier;
        this.unitName = unitName;
        this.coordinator = coordinator;
    }

    @Override
    public ServiceRegistration addingService(ServiceReference<TransactionManager> ref) {
        TransactionManager tm = context.getService(ref);
        XAJpaTemplate txManager = new XAJpaTemplate(emSupplier, tm, coordinator);
        return context.registerService(JpaTemplate.class, txManager, xaTxManProps(unitName));
    }

    private static Dictionary<String, String> xaTxManProps(String unitName) {
        Dictionary<String, String> txmanProperties = new Hashtable<String, String>(); // NOSONAR
        txmanProperties.put(EntityManagerFactoryBuilder.JPA_UNIT_NAME, unitName);
        txmanProperties.put(TRANSACTION_TYPE, "JTA");
        return txmanProperties;
    }

    @Override
    public void removedService(ServiceReference<TransactionManager> reference, ServiceRegistration reg) {
        try {
            reg.unregister();
            context.ungetService(reference);
        } catch (Exception e) {
            LOG.debug("Exception during unregister", e);
        }
    }

}


text:
<?php
class newsletter extends WP_Widget
{
  function newsletter()
  {
    $widget_ops = array('classname' => 'newsletter', 'description' => 'Newsletter or Subscription' );
    $this->WP_Widget('newsletter', 'ChimpS : Newsletter', $widget_ops);
  }

  function form($instance)
  {
	$instance = wp_parse_args( (array) $instance, array( 'title' => '' ) );
	$title = $instance['title'];
	$short_desc = empty($instance['short_desc']) ? ' ' : apply_filters('widget_title', $instance['short_desc']);
	?>

        <label for="<?php echo $this->get_field_id('title'); ?>">
            Title:
            <input class="upcoming" id="<?php echo $this->get_field_id('title'); ?>" size="40" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo esc_attr($title); ?>" />

      <label for="<?php echo $this->get_field_id('short_desc'); ?>">
            Short Description:

          <textarea rows="2"  cols="35" class="upcoming" id="<?php echo $this->get_field_id('short_desc'); ?>" name="<?php echo $this->get_field_name('short_desc'); ?>"><?php echo esc_attr($short_desc); ?></textarea>

    <?php
  }

  function update($new_instance, $old_instance)
  {
    $instance = $old_instance;
    $instance['title'] = $new_instance['title'];
    $instance['short_desc'] = $new_instance['short_desc'];
    return $instance;
  }

	function widget($args, $instance)
	{

	extract($args, EXTR_SKIP);
		$title = empty($instance['title']) ? ' ' : apply_filters('widget_title', $instance['title']);
		$short_desc = empty($instance['short_desc']) ? ' ' : apply_filters('widget_title', $instance['short_desc']);
		echo $before_widget;
			// WIDGET display CODE Start
			if (!empty($title))
				echo $before_title;
				echo $title;
				echo $after_title;
				global $wpdb, $post;

			?>

						<form id="frm_newsletter" action="javascript:frm_newsletter()">

								<?php if($short_desc != ''){
											echo '
';
											echo substr($short_desc, 0, 120);
											if ( strlen($short_desc) > 120 ) echo "...";
											echo '
';
										}
								?>
								<input type="text" class="bar" name="newsletter_email" value="Enter Email Address" onfocus="if(this.value=='Enter Email Address') {this.value='';}" onblur="if(this.value=='') {this.value='Enter Email Address';}" />
								<button id="btn_newsletter" class="backcolr">Submit</button>

				        </form>

			<?php
		echo $after_widget;
		}

	}
add_action( 'widgets_init', create_function('', 'return register_widget("newsletter");') );?>


text:
package org.ovirt.engine.core.bll;

import org.ovirt.engine.core.common.queries.IdQueryParameters;

public class GetVdsGroupsByStoragePoolIdQuery<P extends IdQueryParameters>
        extends QueriesCommandBase<P> {
    public GetVdsGroupsByStoragePoolIdQuery(P parameters) {
        super(parameters);
    }

    @Override
    protected void executeQueryCommand() {
        getQueryReturnValue().setReturnValue(
                getDbFacade().getVdsGroupDao().getAllForStoragePool(
                        getParameters().getId(),
                        getUserID(),
                        getParameters().isFiltered()));
    }
}


text:
module Coursewareable::Api::V1
  # [Coursewareable::Response] API controller
  class ResponsesController < ApplicationController

    # Render requested response
    def show
      resp = @current_resource_owner.responses.where(
        :assignment_id => params[:assignment_id]).first
      render :json => resp, :root => :response
    end
  end
end


text:
<!DOCTYPE html>

	<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
	{common_head}

					<input type="text" id="search_key" name="search_key"
					                                       class="input_box"/>
					<input id="btn_search" class="btn2" value="查 询" type="button" style="display:{display}"/>

			用户活动ID
			用户名称
			活动名称
			报名时间
			状态
			通过
            拒绝
            删除

		<icms id="activity_user_list" type="list">
			<item>
				<![CDATA[

							{f_ActivityUserId}

							{f_UserName}

							{f_ActivityTitle}

							{f_CreateDate}

                                {f_State}

				]]>
			</item>
		</icms>

{PagerButton}


text:
This sample shows how to create a workflow that supports custom events.

### Applies to ###
- Office 365 Multi Tenant (MT)

### Prerequisites ###
None

### Solution ###
Solution | Author(s)
---------|----------
Workflow.CustomEvents | Paolo Pialorsi (**PiaSys.com**)

### Version history ###
Version  | Date | Comments
---------| -----| --------
1.0  | November 6th 2014 | Initial release

### Disclaimer ###
**THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.**

----------

# SCENARIO: WAIT CUSTOM EVENT #
This SharePoint-hosted sample application for SharePoint demonstrates how to create a workflow that waits for a custom event, which will be raised by a custom Page via JavaScript and using the JavaScript Client Object Model (JSOM) for the Workflow Services Manager library.

## WORKFLOW ##
### WORKFLOW ARGUMENTS ###
The workflow does not expect any argument, it simply starts against the target item and waits for a custom event.

## WORKFLOW TARGET ITEMS LIST ###
The list of items against which the sample workflow runs.

The *WFEventFired* field is used to set the value of the custom event that has been fired using the custom Page.

### START THE WORKFLOW ###
Using the Workflows page or the ECB menu item named "Start Sample Workflow" you can start the workflow.

### FIRE CUSTOM EVENT ###
Using ECB menu item named "Fire Custom Event" you can fire the custom event.

# HOW TO TEST THE SAMPLE #
Using Visual Studio 2013, configure the target SharePoint Online site collection, and simply start (F5) the SharePoint App from within Visual Studio 2013


text:
<?php
namespace Google\Service\Books\VolumesMybooks;

/**
 * The "mybooks" collection of methods.
 * Typical usage is:
 *  <code>
 *   $booksService = new Google_Service_Books(...);
 *   $mybooks = $booksService->mybooks;
 *  </code>
 */
class Resource extends \Google\Service\Resource
{

  /**
   * Return a list of books in My Library. (mybooks.listVolumesMybooks)
   *
   * @param array $optParams Optional parameters.
   *
   * @opt_param string locale
   * ISO-639-1 language and ISO-3166-1 country code. Ex:'en_US'. Used for generating recommendations.
   * @opt_param string startIndex
   * Index of the first result to return (starts at 0)
   * @opt_param string maxResults
   * Maximum number of results to return.
   * @opt_param string source
   * String to identify the originator of this request.
   * @opt_param string acquireMethod
   * How the book was aquired
   * @opt_param string processingState
   * The processing state of the user uploaded volumes to be returned. Applicable only if the
    * UPLOADED is specified in the acquireMethod.
   * @return \Google\Service\Books\Volumes
   */
  public function listVolumesMybooks($optParams = array())
  {
    $params = array();
    $params = array_merge($params, $optParams);
    return $this->call('list', array($params), "\Google\Service\Books\Volumes");
  }
}


text:
package com.opengamma.analytics.financial.credit.isdastandardmodel;

import static com.opengamma.analytics.financial.credit.isdastandardmodel.CDSCoupon.makeCoupons;

import java.util.Arrays;

import org.threeten.bp.LocalDate;
import org.threeten.bp.Period;
import org.threeten.bp.temporal.JulianFields;

import com.opengamma.financial.convention.businessday.BusinessDayConvention;
import com.opengamma.financial.convention.businessday.BusinessDayConventions;
import com.opengamma.financial.convention.calendar.Calendar;
import com.opengamma.financial.convention.calendar.MondayToFridayCalendar;
import com.opengamma.financial.convention.daycount.DayCount;
import com.opengamma.financial.convention.daycount.DayCounts;
import com.opengamma.util.ArgumentChecker;

/**
 * This converts and stores all the date logic as doubles for CDS pricing on a particular date.
 *

 * For convenient ways to generate sets of CDSs
 *
 * @see CDSAnalyticFactory
 */
public class CDSAnalytic {
  private static final Calendar DEFAULT_CALENDAR = new MondayToFridayCalendar("Weekend_Only");
  private static final BusinessDayConvention FOLLOWING = BusinessDayConventions.FOLLOWING;
  /** Curve daycount generally fixed to Act/365 in ISDA */
  private static final DayCount ACT_365 = DayCounts.ACT_365;
  private static final DayCount ACT_360 = DayCounts.ACT_360;

  private final double _lgd;
  private final boolean _payAccOnDefault;
  private final CDSCoupon[] _coupons;

  // important time measures for the curve zero time ('now') using the curve DCC
  private final double _accStart; // the start of the first accrual period (usually < 0)
  private final double _effectiveProtectionStart; // when protection starts (usually zero unless forward starting CDS)
  private final double _cashSettlementTime; // Time when CDS is cash settled (valuation time defaults to this)
  private final double _protectionEnd; // when the CDS ends

  private final double _accrued;
  private final int _accruedDays;

  /**
   * Generates an analytic description of a CDS trade on a particular date. This can then be passed to a analytic CDS pricer.

   * This using a weekend only calendar with a following convention. ACT/360 is used for accrual and ACT/365 to convert payment dates to year-fractions
   * (doubles)
   *
   * @param tradeDate
   *          The trade date
   * @param stepinDate
   *          (aka Protection Effective date or assignment date). Date when party assumes ownership. This is usually T+1. This is when protection (and risk)
   *          starts in terms of the model. Note, this is sometimes just called the Effective Date, however this can cause confusion with the legal effective
   *          date which is T-60 or T-90.
   * @param valueDate
   *          The valuation date. The date that values are PVed to. Is is normally today + 3 business days. Aka cash-settle date.
   * @param accStartDate
   *          This is when the CDS nominally starts in terms of premium payments. i.e. the number of days in the first period (and thus the amount of the first
   *          premium payment) is counted from this date.
   * @param endDate
   *          (aka maturity date) This is when the contract expires and protection ends - any default after this date does not trigger a payment. (the
   *          protection ends at end of day)
   * @param payAccOnDefault
   *          Is the accrued premium paid in the event of a default
   * @param paymentInterval
   *          The nominal step between premium payments (e.g. 3 months, 6 months).
   * @param stubType
   *          stubType Options are FRONTSHORT, FRONTLONG, BACKSHORT, BACKLONG or NONE - Note in this code NONE is not allowed
   * @param protectStart
   *          If protectStart = true, then protections starts at the beginning of the day, otherwise it is at the end.
   * @param recoveryRate
   *          The recovery rate
   */
  public CDSAnalytic(final LocalDate tradeDate, final LocalDate stepinDate, final LocalDate valueDate, final LocalDate accStartDate, final LocalDate endDate,
      final boolean payAccOnDefault,
      final Period paymentInterval, final StubType stubType, final boolean protectStart, final double recoveryRate) {
    this(tradeDate, stepinDate, valueDate, accStartDate, endDate, payAccOnDefault, paymentInterval, stubType, protectStart, recoveryRate, FOLLOWING,
        DEFAULT_CALENDAR, ACT_360, ACT_365);
  }

  /**
   * Generates an analytic description of a CDS trade on a particular date. This can then be passed to a analytic CDS pricer.

   * This using a weekend only calendar with a following convention. ACT/360 is used for accrual and ACT/365 to convert payment dates to year-fractions
   * (doubles)
   *
   * Note this uses a curve daycount of ACT/365 to match the ISDA methodology.
   *
   * @param tradeDate
   *          The trade date
   * @param stepinDate
   *          (aka Protection Effective sate or assignment date). Date when party assumes ownership. This is usually T+1. This is when protection (and risk)
   *          starts in terms of the model. Note, this is sometimes just called the Effective Date, however this can cause confusion with the legal effective
   *          date which is T-60 or T-90.
   * @param valueDate
   *          The valuation date. The date that values are PVed to. Is is normally today + 3 business days. Aka cash-settle date.
   * @param accStartDate
   *          This is when the CDS nominally starts in terms of premium payments. i.e. the number of days in the first period (and thus the amount of the first
   *          premium payment) is counted from this date.
   * @param endDate
   *          (aka maturity date) This is when the contract expires and protection ends - any default after this date does not trigger a payment. (the
   *          protection ends at end of day)
   * @param payAccOnDefault
   *          Is the accrued premium paid in the event of a default
   * @param paymentInterval
   *          The nominal step between premium payments (e.g. 3 months, 6 months).
   * @param stubType
   *          stubType Options are FRONTSHORT, FRONTLONG, BACKSHORT, BACKLONG or NONE - Note in this code NONE is not allowed
   * @param protectStart
   *          If protectStart = true, then protections starts at the beginning of the day, otherwise it is at the end.
   * @param recoveryRate
   *          The recovery rate
   * @param businessdayAdjustmentConvention
   *          How are adjustments for non-business days made
   * @param calendar
   *          Calendar defining what is a non-business day
   * @param accrualDayCount
   *          Day count used for accrual
   */
  public CDSAnalytic(final LocalDate tradeDate, final LocalDate stepinDate, final LocalDate valueDate, final LocalDate accStartDate, final LocalDate endDate,
      final boolean payAccOnDefault,
      final Period paymentInterval, final StubType stubType, final boolean protectStart, final double recoveryRate,
      final BusinessDayConvention businessdayAdjustmentConvention,
      final Calendar calendar, final DayCount accrualDayCount) {
    this(tradeDate, stepinDate, valueDate, accStartDate, endDate, payAccOnDefault, paymentInterval, stubType, protectStart, recoveryRate,
        businessdayAdjustmentConvention, calendar, accrualDayCount,
        ACT_365);
  }

  /**
   * Generates an analytic description of a CDS trade on a particular date. This can then be passed to a analytic CDS pricer
   *
   * @param tradeDate
   *          The trade date or 'today', this is the date other times are measured from (i.e. t = 0)
   * @param stepinDate
   *          (aka Protection Effective date or assignment date). Date when party assumes ownership. This is usually T+1. This is when protection (and risk)
   *          starts in terms of the model. Note, this is sometimes just called the Effective Date, however this can cause confusion with the legal effective
   *          date which is T-60 or T-90.
   * @param valueDate
   *          The valuation date. The date that values are PVed to. Is is normally today + 3 business days. Aka cash-settle date.
   * @param accStartDate
   *          This is when the CDS nominally starts in terms of premium payments. i.e. the number of days in the first period (and thus the amount of the first
   *          premium payment) is counted from this date.
   * @param endDate
   *          (aka maturity date) This is when the contract expires and protection ends - any default after this date does not trigger a payment. (the
   *          protection ends at end of day)
   * @param payAccOnDefault
   *          Is the accrued premium paid in the event of a default
   * @param paymentInterval
   *          The nominal step between premium payments (e.g. 3 months, 6 months).
   * @param stubType
   *          stubType Options are FRONTSHORT, FRONTLONG, BACKSHORT, BACKLONG or NONE - Note in this code NONE is not allowed
   * @param isProtectStart
   *          If protectStart = true, then protections starts at the beginning of the day, otherwise it is at the end.
   * @param recoveryRate
   *          The recovery rate
   * @param businessdayAdjustmentConvention
   *          How are adjustments for non-business days made
   * @param calendar
   *          Calendar defining what is a non-business day
   * @param accrualDayCount
   *          Day count used for accrual
   * @param curveDayCount
   *          Day count used on curve (NOTE ISDA uses ACT/365 (fixed) and it is not recommended to change this)
   */
  public CDSAnalytic(final LocalDate tradeDate, final LocalDate stepinDate, final LocalDate valueDate, final LocalDate accStartDate, final LocalDate endDate,
      final boolean payAccOnDefault,
      final Period paymentInterval, final StubType stubType, final boolean isProtectStart, final double recoveryRate,
      final BusinessDayConvention businessdayAdjustmentConvention,
      final Calendar calendar, final DayCount accrualDayCount, final DayCount curveDayCount) {
    ArgumentChecker.notNull(tradeDate, "tradeDate");
    ArgumentChecker.notNull(stepinDate, "stepinDate");
    ArgumentChecker.notNull(valueDate, "valueDate");
    ArgumentChecker.notNull(accStartDate, "accStartDate");
    ArgumentChecker.notNull(endDate, "endDate");
    ArgumentChecker.notNull(paymentInterval, "tenor");
    ArgumentChecker.notNull(stubType, "stubType");
    ArgumentChecker.notNull(businessdayAdjustmentConvention, "businessdayAdjustmentConvention");
    ArgumentChecker.notNull(accrualDayCount, "accuralDayCount");
    ArgumentChecker.notNull(curveDayCount, "curveDayCount");
    ArgumentChecker.isInRangeInclusive(0, 1, recoveryRate);
    ArgumentChecker.isFalse(valueDate.isBefore(tradeDate), "Require valueDate >= today");
    ArgumentChecker.isFalse(stepinDate.isBefore(tradeDate), "Require stepin >= today");
    // TODO should not allow the accrual start to be after the stepin (protection start), since this is 'free' protection. Currently some tests have this
    // and need to be changed
    // ArgumentChecker.isFalse(stepinDate.isBefore(accStartDate), "Require stepin >= accStartDate");
    ArgumentChecker.isFalse(tradeDate.isAfter(endDate), "CDS has expired");

    _payAccOnDefault = payAccOnDefault;

    final LocalDate startDate = stepinDate.isAfter(accStartDate) ? stepinDate : accStartDate;
    final LocalDate effectiveStartDate = isProtectStart ? startDate.minusDays(1) : startDate;

    _accStart = accStartDate.isBefore(tradeDate) ? -curveDayCount.getDayCountFraction(accStartDate, tradeDate)
        : curveDayCount.getDayCountFraction(tradeDate, accStartDate);
    _cashSettlementTime = curveDayCount.getDayCountFraction(tradeDate, valueDate);
    _effectiveProtectionStart = effectiveStartDate.isBefore(tradeDate) ? -curveDayCount.getDayCountFraction(effectiveStartDate, tradeDate)
        : curveDayCount.getDayCountFraction(tradeDate,
            effectiveStartDate);
    _protectionEnd = curveDayCount.getDayCountFraction(tradeDate, endDate);
    _lgd = 1 - recoveryRate;

    final ISDAPremiumLegSchedule fullPaymentSchedule = new ISDAPremiumLegSchedule(accStartDate, endDate, paymentInterval, stubType,
        businessdayAdjustmentConvention, calendar, isProtectStart);
    final ISDAPremiumLegSchedule paymentSchedule = ISDAPremiumLegSchedule.truncateSchedule(stepinDate, fullPaymentSchedule);
    _coupons = makeCoupons(tradeDate, paymentSchedule, isProtectStart, accrualDayCount, curveDayCount);

    final LocalDate accStart = paymentSchedule.getAccStartDate(0);
    final long firstJulianDate = accStart.getLong(JulianFields.MODIFIED_JULIAN_DAY);
    final long secondJulianDate = stepinDate.getLong(JulianFields.MODIFIED_JULIAN_DAY);
    _accruedDays = secondJulianDate > firstJulianDate ? (int) (secondJulianDate - firstJulianDate) : 0;
    _accrued = accStart.isBefore(stepinDate) ? accrualDayCount.getDayCountFraction(accStart, stepinDate) : 0.0;
  }

  public int getNumPayments() {
    return _coupons.length;
  }

  /**
   * Gets the payAccOnDefault.
   *
   * @return the payAccOnDefault
   */
  public boolean isPayAccOnDefault() {
    return _payAccOnDefault;
  }

  /**
   * The loss-given-default. This is 1 - recovery rate
   *
   * @return the LGD
   */
  public double getLGD() {
    return _lgd;
  }

  /**
   * Gets year fraction (according to curve DCC) between the trade date and the cash-settle date.
   *
   * @return the CashSettleTime
   */
  public double getCashSettleTime() {
    return _cashSettlementTime;
  }

  /**
   * Year fraction (according to curve DCC) from trade date to accrual start date. This will be negative for spot starting CDS, but will be positive for forward
   * starting CDS.
   *
   * @return accrual start year-fraction.
   */
  public double getAccStart() {
    return _accStart;
  }

  /**
   * Year fraction (according to curve DCC) from trade date to effective protection start date. The effective protection start date is the greater of the
   * accrual start date and the step-in date; if protection is from start of day, this is adjusted back one day - so for a standard CDS it is the trade date.
   *
   * @return the effectiveProtectionStart
   */
  public double getEffectiveProtectionStart() {
    return _effectiveProtectionStart;
  }

  /**
   * Year fraction (according to curve DCC) from trade date to the maturity of the CDS.
   *
   * @return the protectionEnd
   */
  public double getProtectionEnd() {
    return _protectionEnd;
  }

  /**
   * Get all the coupons on the premium leg.
   *
   * @return the coupons.
   */
  public CDSCoupon[] getCoupons() {
    return _coupons;
  }

  /**
   * get a coupon at a particular index (zero based).
   *
   * @param index
   *          the index
   * @return a coupon
   */
  public CDSCoupon getCoupon(final int index) {
    return _coupons[index];
  }

  /**
   * Gets the accrued premium per unit of (fractional) spread - i.e. if the quoted spread (coupon) was 500bps the actual accrued premium paid would be this
   * times 0.05
   *
   * @return the accrued premium per unit of (fractional) spread (and unit of notional)
   */
  public double getAccruedYearFraction() {
    return _accrued;
  }

  /**
   * Gets the accrued premium per unit of notional.
   *
   * @param fractionalSpread
   *          The fraction spread
   * @return the accrued premium
   */
  public double getAccruedPremium(final double fractionalSpread) {
    return _accrued * fractionalSpread;
  }

  /**
   * Get the number of days of accrued premium.
   *
   * @return Accrued days
   */
  public int getAccruedDays() {
    return _accruedDays;
  }

  /**
   * Get the number of days of accrued premium.
   *
   * @return the accrued days
   * @deprecated use {@link #getAccruedDays()}
   */
  @Deprecated
  public int getAccuredDays() {
    return _accruedDays;
  }

  private CDSAnalytic(final double lgd, final CDSCoupon[] coupons, final double start, final double effectiveProtectionStart, final double protectionEnd,
      final double valuationTime,
      final boolean payAccOnDefault, final double accrued, final int accruedDays) {
    ArgumentChecker.noNulls(coupons, "coupons");

    _accStart = start;
    _effectiveProtectionStart = effectiveProtectionStart;
    _protectionEnd = protectionEnd;
    _cashSettlementTime = valuationTime;

    _lgd = lgd;
    _coupons = coupons;
    _payAccOnDefault = payAccOnDefault;
    _accrued = accrued;
    _accruedDays = accruedDays;
  }

  /**
   * produce a copy of the CDS with a new recovery rate.
   *
   * @param recoveryRate
   *          The recovery rate
   * @return a new CDS
   */
  public CDSAnalytic withRecoveryRate(final double recoveryRate) {
    ArgumentChecker.isInRangeInclusive(0, 1, recoveryRate);
    return new CDSAnalytic(1 - recoveryRate, _coupons, _accStart, _effectiveProtectionStart, _protectionEnd, _cashSettlementTime, _payAccOnDefault, _accrued,
        _accruedDays);
  }

  /**
   * Generate a CDS with a time offset. The main use is to produce a forward starting CDS from a forward CDS. A forward CDS is a CDS with a future trade date
   * viewed from that date (i.e. it is a spot CDS view from the future trade date). A forward starting CDS is a CDS (seen today) that starts on some future
   * date. The effect of this operation is to shift all time-to based numbers by offset.
   *
   * @param offset
   *          The offset (in years) - must be positive
   * @return an offset (i.e. forward starting) CDS
   */
  public CDSAnalytic withOffset(final double offset) {
    ArgumentChecker.isTrue(offset >= 0, "offset must be positive");
    if (offset == 0.0) {
      return this;
    }
    final int n = getNumPayments();
    final CDSCoupon[] coupons = new CDSCoupon[n];
    for (int i = 0; i < n; i++) {
      coupons[i] = _coupons[i].withOffset(offset);
    }
    return new CDSAnalytic(_lgd, coupons, _accStart + offset, _effectiveProtectionStart + offset, _protectionEnd + offset, _cashSettlementTime + offset,
        _payAccOnDefault, _accrued, _accruedDays);
  }

  @Override
  public int hashCode() {
    final int prime = 31;
    int result = 1;
    long temp;
    temp = Double.doubleToLongBits(_accStart);
    result = prime * result + (int) (temp ^ temp >>> 32);
    temp = Double.doubleToLongBits(_accrued);
    result = prime * result + (int) (temp ^ temp >>> 32);
    result = prime * result + _accruedDays;
    temp = Double.doubleToLongBits(_cashSettlementTime);
    result = prime * result + (int) (temp ^ temp >>> 32);
    result = prime * result + Arrays.hashCode(_coupons);
    temp = Double.doubleToLongBits(_effectiveProtectionStart);
    result = prime * result + (int) (temp ^ temp >>> 32);
    temp = Double.doubleToLongBits(_lgd);
    result = prime * result + (int) (temp ^ temp >>> 32);
    result = prime * result + (_payAccOnDefault ? 1231 : 1237);
    temp = Double.doubleToLongBits(_protectionEnd);
    result = prime * result + (int) (temp ^ temp >>> 32);
    return result;
  }

  @Override
  public boolean equals(final Object obj) {
    if (this == obj) {
      return true;
    }
    if (obj == null) {
      return false;
    }
    if (getClass() != obj.getClass()) {
      return false;
    }
    final CDSAnalytic other = (CDSAnalytic) obj;
    if (Double.doubleToLongBits(_accStart) != Double.doubleToLongBits(other._accStart)) {
      return false;
    }
    if (Double.doubleToLongBits(_accrued) != Double.doubleToLongBits(other._accrued)) {
      return false;
    }
    if (_accruedDays != other._accruedDays) {
      return false;
    }
    if (Double.doubleToLongBits(_cashSettlementTime) != Double.doubleToLongBits(other._cashSettlementTime)) {
      return false;
    }
    if (!Arrays.equals(_coupons, other._coupons)) {
      return false;
    }
    if (Double.doubleToLongBits(_effectiveProtectionStart) != Double.doubleToLongBits(other._effectiveProtectionStart)) {
      return false;
    }
    if (Double.doubleToLongBits(_lgd) != Double.doubleToLongBits(other._lgd)) {
      return false;
    }
    if (_payAccOnDefault != other._payAccOnDefault) {
      return false;
    }
    if (Double.doubleToLongBits(_protectionEnd) != Double.doubleToLongBits(other._protectionEnd)) {
      return false;
    }
    return true;
  }

}