text:
package jsondns

import (
	"net"
	"strconv"
	"strings"
	"time"

	"github.com/miekg/dns"
)

func Marshal(msg *dns.Msg) *Response {
	now := time.Now().UTC()

	resp := new(Response)
	resp.Status = uint32(msg.Rcode)
	resp.TC = msg.Truncated
	resp.RD = msg.RecursionDesired
	resp.RA = msg.RecursionAvailable
	resp.AD = msg.AuthenticatedData
	resp.CD = msg.CheckingDisabled

	resp.Question = make([]Question, 0, len(msg.Question))
	for _, question := range msg.Question {
		jsonQuestion := Question{
			Name: question.Name,
			Type: question.Qtype,
		}
		resp.Question = append(resp.Question, jsonQuestion)
	}

	resp.Answer = make([]RR, 0, len(msg.Answer))
	for _, rr := range msg.Answer {
		jsonAnswer := marshalRR(rr, now)
		if !resp.HaveTTL || jsonAnswer.TTL < resp.LeastTTL {
			resp.HaveTTL = true
			resp.LeastTTL = jsonAnswer.TTL
			resp.EarliestExpires = jsonAnswer.Expires
		}
		resp.Answer = append(resp.Answer, jsonAnswer)
	}

	resp.Authority = make([]RR, 0, len(msg.Ns))
	for _, rr := range msg.Ns {
		jsonAuthority := marshalRR(rr, now)
		if !resp.HaveTTL || jsonAuthority.TTL < resp.LeastTTL {
			resp.HaveTTL = true
			resp.LeastTTL = jsonAuthority.TTL
			resp.EarliestExpires = jsonAuthority.Expires
		}
		resp.Authority = append(resp.Authority, jsonAuthority)
	}

	resp.Additional = make([]RR, 0, len(msg.Extra))
	for _, rr := range msg.Extra {
		jsonAdditional := marshalRR(rr, now)
		header := rr.Header()
		if header.Rrtype == dns.TypeOPT {
			opt := rr.(*dns.OPT)
			resp.Status = ((opt.Hdr.Ttl & 0xff000000) >> 20) | (resp.Status & 0xff)
			for _, option := range opt.Option {
				if option.Option() == dns.EDNS0SUBNET {
					edns0 := option.(*dns.EDNS0_SUBNET)
					clientAddress := edns0.Address
					if clientAddress == nil {
						clientAddress = net.IP{0, 0, 0, 0}
					} else if ipv4 := clientAddress.To4(); ipv4 != nil {
						clientAddress = ipv4
					}
					resp.EdnsClientSubnet = clientAddress.String() + "/" + strconv.FormatUint(uint64(edns0.SourceScope), 10)
				}
			}
			continue
		}
		if !resp.HaveTTL || jsonAdditional.TTL < resp.LeastTTL {
			resp.HaveTTL = true
			resp.LeastTTL = jsonAdditional.TTL
			resp.EarliestExpires = jsonAdditional.Expires
		}
		resp.Additional = append(resp.Additional, jsonAdditional)
	}

	return resp
}

func marshalRR(rr dns.RR, now time.Time) RR {
	jsonRR := RR{}
	rrHeader := rr.Header()
	jsonRR.Name = rrHeader.Name
	jsonRR.Type = rrHeader.Rrtype
	jsonRR.TTL = rrHeader.Ttl
	jsonRR.Expires = now.Add(time.Duration(jsonRR.TTL) * time.Second)
	jsonRR.ExpiresStr = jsonRR.Expires.Format(time.RFC1123)
	data := strings.SplitN(rr.String(), "\t", 5)
	if len(data) >= 5 {
		jsonRR.Data = data[4]
	}
	return jsonRR
}


text:
{% extends "issbase.html" %}
{% load issues %}
{% block content %}

    <form action="" method="POST">{% csrf_token %}
        <fieldset class="module aligned">

        {% for name in modelform.fldorder %}
            {% with modelform|get:name as fld %}

                    {{ fld.label }}
                    {{ fld }}

            {% endwith %}
        {% endfor %}

        </fieldset>

<input id="submit-btn" type="submit" value="Save">

    </form>

{% endblock %}

redpajama_set_name: RedPajamaGithub


text:
const common = require('../../../common.js');
const mockery = require('mockery');
const assert = require('assert');

describe('Test CLI Runner Generate', function() {

  beforeEach(function() {
    mockery.enable({useCleanCache: true, warnOnReplace: false, warnOnUnregistered: false});
    mockery.registerMock('./argv-setup.js', {
      isDefault(option, value) {
        return value.includes('nightwatch.');
      },

      getDefault() {
        return './nightwatch.json';
      }
    });
  });

  afterEach(function() {
    mockery.deregisterAll();
    mockery.resetCache();
    mockery.disable();
  });

  it('test start CLI Runner with no config file', function () {
    let configData;
    const fs = require('fs');
    const path = require('path');
    const tplData = fs.readFileSync(path.resolve('lib/runner/cli/nightwatch.conf.ejs')).toString();

    mockery.registerMock('os', {
      platform: function() {
        return 'win';
      }
    });

    mockery.registerMock('fs', {
      statSync: function (fileName) {
        if (fileName.endsWith('/nightwatch.conf.js')) {
          return {
            isFile: function () {
              return false;
            }
          };
        }

        if (fileName.endsWith('/nightwatch.json')) {
          return {
            isFile: function () {
              return false;
            }
          };
        }
      },

      readFileSync: function(fileName) {
        return {
          toString: function () {
            return tplData;
          }
        };
      },

      writeFileSync: function (destFileName, content) {
        assert.strictEqual(destFileName, path.join(process.cwd(), 'nightwatch.conf.js'));

        configData = eval(content);
        mockery.registerMock(path.join(process.cwd(), 'nightwatch.conf.js'), configData);

        assert.strictEqual(typeof configData.safari, 'undefined');

        assert.deepStrictEqual(configData.test_settings.chrome, {
          desiredCapabilities: {
            browserName: 'chrome',
            'goog:chromeOptions': {
              args: [],
              w3c: false
            }
          },

          webdriver: {
            start_process: true,
            port: 9515,
            server_path: '',
            cli_args: []
          }
        });

        assert.deepStrictEqual(configData.test_settings.firefox, {
          desiredCapabilities: {
            browserName: 'firefox',
            alwaysMatch: {
              acceptInsecureCerts: true,
              'moz:firefoxOptions': {
                args: []
              }
            }
          },
          webdriver: {
            start_process: true,
            port: 4444,
            server_path: '',
            cli_args: []
          }
        });

        assert.deepStrictEqual(configData.test_settings.browserstack, {
          desiredCapabilities: {
            'bstack:options': {
              userName: '${BROWSERSTACK_USER}',
              accessKey: '${BROWSERSTACK_KEY}'
            }
          },

          selenium: {
            host: 'hub-cloud.browserstack.com',
            port: 443
          },

          disable_error_log: true,
          webdriver: {
            timeout_options: {
              timeout: 15000,
              retry_attempts: 3
            },
            keep_alive: true,
            start_process: false
          }
        });

        assert.deepStrictEqual(configData.test_settings['browserstack.local'], {
          extends: 'browserstack',
          desiredCapabilities: {
            'browserstack.local': true
          }
        });

        assert.deepStrictEqual(configData.test_settings['browserstack.local_firefox'], {
          extends: 'browserstack.local',
          desiredCapabilities: {
            browserName: 'firefox'
          }
        });

        assert.deepStrictEqual(configData.test_settings['browserstack.local_chrome'], {
          extends: 'browserstack.local',
          desiredCapabilities: {
            browserName: 'chrome'
          }
        });

        assert.deepStrictEqual(configData.test_settings['browserstack.chrome'], {
          extends: 'browserstack',
          desiredCapabilities: {
            browserName: 'chrome',
            chromeOptions: {
              w3c: false
            }
          }
        });

        assert.deepStrictEqual(configData.test_settings['browserstack.ie'], {
          extends: 'browserstack',
          desiredCapabilities: {
            browserName: 'internet explorer',
            browserVersion: '11.0'
          }
        });

        assert.deepStrictEqual(configData.test_settings.selenium_server, {
          selenium: {
            start_process: true,
            port: 4444,
            server_path: '',
            cli_args: {
              'webdriver.gecko.driver': '',
              'webdriver.chrome.driver': ''
            }
          }
        });

      }
    });

    const CliRunner = common.require('runner/cli/cli.js');
    const ieRunner = new CliRunner({
      config: './nightwatch.json',
      env: 'browserstack.ie'
    }).setup();

    assert.strictEqual(ieRunner.argv.config, path.join(process.cwd(), 'nightwatch.conf.js'));
    assert.deepStrictEqual(ieRunner.test_settings.desiredCapabilities, {
      browserName: 'internet explorer',
      browserVersion: '11.0',
      'bstack:options': {
        userName: '${BROWSERSTACK_USER}',
        accessKey: '${BROWSERSTACK_KEY}'
      }
    });

    const chromeLocalRunner = new CliRunner({
      config: './nightwatch.json',
      env: 'browserstack.local_chrome'
    }).setup();

    assert.deepStrictEqual(chromeLocalRunner.test_settings.desiredCapabilities, {
      browserName: 'chrome',
      'browserstack.local': true,
      'bstack:options': {
        userName: '${BROWSERSTACK_USER}',
        accessKey: '${BROWSERSTACK_KEY}'
      }
    });
  });

});


text: start a webapp with python3


text:
namespace vtrc { namespace client {

    namespace {
        typedef common::transport_win_pipe::socket_type          socket_type;
        typedef client_stream_impl<client_win_pipe, socket_type> super_type;
    }

    struct client_win_pipe::impl: public super_type  {

        impl( VTRC_ASIO::io_service &ios,
              client::base *client, protocol_signals *callbacks )
            :super_type(ios, client, callbacks, 4096)
        { }

        void connect( const std::string &address )
        {
            HANDLE pipe = CreateFileA( address.c_str( ),
                                 GENERIC_WRITE | GENERIC_READ,
                                 0,
                                 NULL, OPEN_EXISTING,
                                 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED,
                                 NULL);

            if(INVALID_HANDLE_VALUE == pipe) {
                vtrc::common::raise(
                            vtrc::common::exception( GetLastError( ),
                                rpc::errors::CATEGORY_SYSTEM ) );
                return;
            } else {
                get_socket( ).assign( pipe );
            }
            connection_setup( );
            start_reading( );
        }

        void async_connect( const std::string &address,
                            common::system_closure_type closure )
        {
            connect( address );
            bsys::error_code ec(0, vtrc::get_system_category( ));
            closure(ec);
        }

        void connect( const std::wstring &address )
        {
            HANDLE pipe = CreateFileW( address.c_str( ),
                                 GENERIC_WRITE | GENERIC_READ,
                                 0,
                                 NULL, OPEN_EXISTING,
                                 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED,
                                 NULL);

            if(INVALID_HANDLE_VALUE == pipe) {
                vtrc::common::raise(
                    vtrc::common::exception( GetLastError( ),
                        rpc::errors::CATEGORY_SYSTEM ) );
                return;
            } else {
                get_socket( ).assign( pipe );
            }
            connection_setup( );
            start_reading( );
        }

        void async_connect( const std::wstring &address,
                            common::system_closure_type closure )
        {
            connect( address );
            bsys::error_code ec(0, vtrc::get_system_category( ));
            closure(ec);
        }

    };

    static vtrc::shared_ptr<socket_type> create_socket( basio::io_service &ios )
    {
        return vtrc::make_shared<socket_type>(vtrc::ref(ios));
    }

    client_win_pipe::client_win_pipe( VTRC_ASIO::io_service &ios,
                                      client::base *client,
                                      protocol_signals *callbacks )
        :common::transport_win_pipe(create_socket(ios))
        ,impl_(new impl(ios, client, callbacks ))
    {
        impl_->set_parent( this );
    }

    vtrc::shared_ptr<client_win_pipe> client_win_pipe::create( client::base *c,
                                                protocol_signals *callbacks )
    {
        vtrc::shared_ptr<client_win_pipe> new_inst
                    (new client_win_pipe( c->get_io_service( ),
                                          c, callbacks ));
        new_inst->init( );
        return new_inst;
    }

    client_win_pipe::~client_win_pipe( )
    {
        delete impl_;
    }

    void client_win_pipe::connect( const std::string &address )
    {
        impl_->connect( address );
    }

    void client_win_pipe::connect( const std::wstring &address )
    {
        impl_->connect( address );
    }

    void client_win_pipe::async_connect( const std::string &address,
                                   common::system_closure_type  closure )
    {
        impl_->async_connect( address, closure );
    }

    void client_win_pipe::async_connect( const std::wstring &address,
                                 common::system_closure_type  closure )
    {
        impl_->async_connect( address, closure );
    }

    const common::call_context *client_win_pipe::get_call_context( ) const
    {
        return impl_->get_call_context( );
    }

    void client_win_pipe::on_write_error( const bsys::error_code &err )
    {
        impl_->on_write_error( err );
        this->close( );
    }

    common::protocol_layer &client_win_pipe::get_protocol( )
    {
        return impl_->get_protocol( );
    }

    const common::protocol_layer &client_win_pipe::get_protocol( ) const
    {
        return impl_->get_protocol( );
    }

    common::environment &client_win_pipe::get_environment( )
    {
        return impl_->get_environment( );
    }

    bool client_win_pipe::active( ) const
    {
        return impl_->active( );
    }

    void client_win_pipe::init( )
    {
        impl_->init( );
    }

    void client_win_pipe::on_close( )
    {
        impl_->on_close( );
    }

    const std::string &client_win_pipe::id( ) const
    {
        return impl_->id( );
    }

    void client_win_pipe::raw_call_local (
                          vtrc::shared_ptr<rpc::lowlevel_unit> ll_mess,
                          common::empty_closure_type done )
    {
        impl_->raw_call_local( ll_mess, done );
    }

}}

#endif


text:
import datetime
import re

"""
Run the file to update the user_events.json and user_events_some_invalid.json files with more recent timestamp
"""

def update_events_timestamp(json_file):
    # Get the yesterday's date
    request_time = datetime.datetime.now() - datetime.timedelta(days=1)
    day = request_time.date().strftime("%Y-%m-%d")
    print(day)

    # Read in the file
    with open(json_file, 'r') as file:
        filedata = file.read()

    # Replace the target string  '"eventTime":"YYYY-mm-dd' with yesterday date
    filedata = re.sub('\"eventTime\":\"([0-9]{4})-([0-9]{2})-([0-9]{2})',
                      '\"eventTime\":\"' + day, filedata, flags=re.M)

    # Write the file out again
    with open(json_file, 'w') as file:
        file.write(filedata)
    print(f"The {json_file} is updated")

if __name__ == "__main__":
    update_events_timestamp("../resources/user_events.json")
    update_events_timestamp("../resources/user_events_some_invalid.json")


text:
package org.jetbrains.annotations;

import java.lang.annotation.*;

/**
 * A method/constructor annotated with TestOnly claims that it should be called from testing code only.
 * <p>
 * Apart from documentation purposes this annotation is intended to be used by static analysis tools
 * to validate against element contract violations.
 */
@Documented
@Retention(RetentionPolicy.SOURCE)
@Target({ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.TYPE})
public @interface TestOnly { }


text:
class ClientObjectManager : public EventListener
{
 public:
	void HandleEvent( Event *e );

	std::vector<std::shared_ptr<WorldNode>> worldNodes;
	std::vector<std::shared_ptr<Entity>>    entities;

	std::mutex managerMutex;

 private:

	void AddParent( unsigned int childId, unsigned int parentId );
	void RemoveParent( unsigned int childId, unsigned int parentId );

	void AddChild( unsigned int parentId, unsigned int childId );
	void RemoveChild( unsigned int parentId, unsigned int childId );
};


text:
Simple xlsx-processing library focused on not breaking anything.

Its use-case is when you just want to add some data into existing xlsx Workbook, and to preserve styles, forms, scripts and other stuff.

## Disclaimer

I'm writing this lib for my work needs. It means that mild-xlsx will contain only methods which I need, unless someone requests additional features. So feel free to do that :)

## Installation

NodeJS:
> npm install mild-xlsx

## API

I'm trying to mimic a MS COM Excel API. More info later.


text:
<?php

class HighRoller {

        public $chart;
        public $title;

        public $series = array();

        public function __construct() {

                $this->chart = new HighRollerChart();
                $this->title = new HighRollerTitle();
                $this->series = new HighRollerSeries();
                $this->drilldown = new stdClass();
                $this->drilldown->series = new HighRollerSeries();
        }

/** returns a javascript script tag with path to your Highcharts library source
 * @static
 * @param $location - path to your highcharts JS
 * @return string - html script tag markup with your source location
 */
        public static function setHighchartsLocation($location) {
                return $scriptTag = "<!-- High Roller - Highcharts Location-->
  <script type='text/javascript' src='" . $location . "'></script>";
        }

/** returns a javascript script tag with path to your Highcharts library THEME source
 * @static
 * @param $location - path to your highcharts theme file
 * @return string - html script tag markup with your source location
 */
        public static function setHighchartsThemeLocation($location) {
                return $scriptTag = "<!-- High Roller - Highcharts Theme Location-->
  <script type='text/javascript' src='" . $location . "'></script>";
        }

/** returns chart object with newly set obj property name
 * @param $objName - string, name of the HighRoller Object you're operating on
 * @param $propertyName - string, name of the property you want to set, can be a new property name
 * @param $value - mixed, value you wish to assign to the property
 * @return HighRoller
 */
        public function setProperty($objName, $propertyName, $value) {
                $this->$objName->$propertyName = $value;
                return $this;
        }

/** add data to plot in your chart
 * @param $chartdata - array, data provided in 1 of 3 Highcharts supported array formats (array, assoc array or mult-dimensional array)
 * @return void
 */
        public function addData($chartdata) {
                if (!is_array($chartdata)) {
                        die("HighRoller::addData() - data format must be an array.");
                }
                $this->series = array($chartdata);
        }

/** add series to your chart
 * @param $series - array, data provided in 1 of 3 Highcharts supported array formats (array, assoc array or mult-dimensional array)
 * @return void
 */
        public function addSeries($series) {
                if (!is_object($series)) {
                        die("HighRoller::addSeries() - series input format must be an object.");
                }

                if (is_object($this->series)) {   // if series is an object
                        $this->series = array($series);
                } else if (is_array($this->series)) {                        // else
                        array_push($this->series, $series);
                }
        }

        public function addDrillDownData($data) {

                if (!is_array($data)) {
                        die("HighRoller::addDrillDownData() - data format must be an array.");
                }

                $this->drilldown->series = $data;
        }

/** enable auto-step calc for xAxis labels for very large data sets.
 * @return void
 */
        public function enableAutoStep() {

                if (is_array($this->series)) {
                        $count = count($this->series[0]->data);
                        $step = number_format(sqrt($count));
                        if ($count > 1000) {
                                $step = number_format(sqrt($count / $step));
                        }

                        $this->xAxis->labels->step = $step;
                }
        }

/** returns new Highcharts javascript
 * @return string - highcharts!
 */
        public function renderChart($engine = 'jquery') {
                $options = new HighRollerOptions();   // change file/class name to new HighRollerGlobalOptions()

                if ($engine == 'mootools') {
                        $chartJS = 'window.addEvent(\'domready\', function() {';
                }
                else {
                        $chartJS = '$(document).ready(function() {';
                }

                $chartJS .= "\n\n    // HIGHROLLER - HIGHCHARTS UTC OPTIONS ";

                $chartJS .= "\n    Highcharts.setOptions(\n";
                $chartJS .= "       " . json_encode($options) . "\n";
                $chartJS .= "    );\n";
                $chartJS .= "\n\n    // HIGHROLLER - HIGHCHARTS '" . $this->title->text . "' " . $this->chart->type . " chart";
                $chartJS .= "\n    var " . $this->chart->renderTo . " = new Highcharts.Chart(\n";
                $chartJS .= "       " . $this->getChartOptionsObject() . "\n";
                $chartJS .= "    );\n";
                $chartJS .= "\n  });\n";
                return trim($chartJS);
        }

/** returns valid Highcharts javascript object containing your HighRoller options, for manipulation between the markup script tags on your page`
 * @return string - highcharts options object!
 */
        public function getChartOptionsObject() {
                return trim(json_encode($this));
        }

/** returns new Highcharts.Chart() using your $varname
 * @param $varname - name of your javascript object holding getChartOptionsObject()
 * @return string - a new Highcharts.Chart() object with the highroller chart options object
 */
        public function renderChartOptionsObject($varname) {
                return "new Highcharts.Chart(" . $varname . ")";
        }

}


text:
package com.topie.internal.whitelist.persistence.domain;

// Generated by Hibernate Tools
import java.util.HashSet;
import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

/**
 * WhitelistType .
 *
 * @author Lingo
 */
@Entity
@Table(name = "WHITELIST_TYPE")
public class WhitelistType implements java.io.Serializable {
    private static final long serialVersionUID = 0L;

    /** null. */
    private Long id;

    /** null. */
    private String name;

    /** null. */
    private String code;

    /** null. */
    private String tenantId;

    /** . */
    private Set<WhitelistApp> whitelistApps = new HashSet<WhitelistApp>(0);

    public WhitelistType() {
    }

    public WhitelistType(Long id) {
        this.id = id;
    }

    public WhitelistType(Long id, String name, String code, String tenantId,
            Set<WhitelistApp> whitelistApps) {
        this.id = id;
        this.name = name;
        this.code = code;
        this.tenantId = tenantId;
        this.whitelistApps = whitelistApps;
    }

    /** @return null. */
    @Id
    @Column(name = "ID", unique = true, nullable = false)
    public Long getId() {
        return this.id;
    }

    /**
     * @param id
     *            null.
     */
    public void setId(Long id) {
        this.id = id;
    }

    /** @return null. */
    @Column(name = "NAME", length = 50)
    public String getName() {
        return this.name;
    }

    /**
     * @param name
     *            null.
     */
    public void setName(String name) {
        this.name = name;
    }

    /** @return null. */
    @Column(name = "CODE", length = 50)
    public String getCode() {
        return this.code;
    }

    /**
     * @param code
     *            null.
     */
    public void setCode(String code) {
        this.code = code;
    }

    /** @return null. */
    @Column(name = "TENANT_ID", length = 64)
    public String getTenantId() {
        return this.tenantId;
    }

    /**
     * @param tenantId
     *            null.
     */
    public void setTenantId(String tenantId) {
        this.tenantId = tenantId;
    }

    /** @return . */
    @OneToMany(fetch = FetchType.LAZY, mappedBy = "whitelistType")
    public Set<WhitelistApp> getWhitelistApps() {
        return this.whitelistApps;
    }

    /**
     * @param whitelistApps
     *            .
     */
    public void setWhitelistApps(Set<WhitelistApp> whitelistApps) {
        this.whitelistApps = whitelistApps;
    }
}


text:
import omit from 'lodash/omit'

const byId = (state = {}, action) => {
  switch (action.type) {
    case 'DDP_CHANGED':
    return {
      ...state,
      [action.response.doc.id]: {
        // merge the old doc with the changed fields
        ...state[action.response.doc.id],
        ...action.response.doc,
      },
    }
    case 'DDP_ADDED':
    return {
      ...state,
      [action.response.doc.id]: action.response.doc,
    }
    case 'DDP_REMOVED':
    return omit(state, action.response.id)
    default:
    return state
  }
}

export default byId

export const getContact = (state, id) => state[id]


text:
require 'test/unit'
require LibDirectory.file('init.rb')
require LibDirectory.file('enhanced_table')
require File.join(File.dirname(__FILE__), 'rest_loader')

class Test::Unit::TestCase

  def project(name)
    @project ||= RESTfulLoaders::ProjectLoader.new(name, nil, self).project
  end

  def errors
    @errors ||= []
  end

  def alert(message)
    errors << message
  end
end


text:
(function(ionic) {
'use strict';

  var ITEM_CLASS = 'item';
  var ITEM_CONTENT_CLASS = 'item-content';
  var ITEM_SLIDING_CLASS = 'item-sliding';
  var ITEM_OPTIONS_CLASS = 'item-options';
  var ITEM_PLACEHOLDER_CLASS = 'item-placeholder';
  var ITEM_REORDERING_CLASS = 'item-reordering';
  var ITEM_REORDER_BTN_CLASS = 'item-reorder';

  var DragOp = function() {};
  DragOp.prototype = {
    start: function(e) {
    },
    drag: function(e) {
    },
    end: function(e) {
    },
    isSameItem: function(item) {
      return false;
    }
  };

  var SlideDrag = function(opts) {
    this.dragThresholdX = opts.dragThresholdX || 10;
    this.el = opts.el;
    this.item = opts.item;
    this.canSwipe = opts.canSwipe;
  };

  SlideDrag.prototype = new DragOp();

  SlideDrag.prototype.start = function(e) {
    var content, buttons, offsetX, buttonsWidth;

    if (!this.canSwipe()) {
      return;
    }

    if (e.target.classList.contains(ITEM_CONTENT_CLASS)) {
      content = e.target;
    } else if (e.target.classList.contains(ITEM_CLASS)) {
      content = e.target.querySelector('.' + ITEM_CONTENT_CLASS);
    } else {
      content = ionic.DomUtil.getParentWithClass(e.target, ITEM_CONTENT_CLASS);
    }

    // If we don't have a content area as one of our children (or ourselves), skip
    if (!content) {
      return;
    }

    // Make sure we aren't animating as we slide
    content.classList.remove(ITEM_SLIDING_CLASS);

    // Grab the starting X point for the item (for example, so we can tell whether it is open or closed to start)
    offsetX = parseFloat(content.style[ionic.CSS.TRANSFORM].replace('translate3d(', '').split(',')[0]) || 0;

    // Grab the buttons
    buttons = content.parentNode.querySelector('.' + ITEM_OPTIONS_CLASS);
    if (!buttons) {
      return;
    }
    buttons.classList.remove('invisible');

    buttonsWidth = buttons.offsetWidth;

    this._currentDrag = {
      buttons: buttons,
      buttonsWidth: buttonsWidth,
      content: content,
      startOffsetX: offsetX
    };
  };

  /**
   * Check if this is the same item that was previously dragged.
   */
  SlideDrag.prototype.isSameItem = function(op) {
    if (op._lastDrag && this._currentDrag) {
      return this._currentDrag.content == op._lastDrag.content;
    }
    return false;
  };

  SlideDrag.prototype.clean = function(isInstant) {
    var lastDrag = this._lastDrag;

    if (!lastDrag || !lastDrag.content) return;

    lastDrag.content.style[ionic.CSS.TRANSITION] = '';
    lastDrag.content.style[ionic.CSS.TRANSFORM] = '';
    if (isInstant) {
      lastDrag.content.style[ionic.CSS.TRANSITION] = 'none';
      makeInvisible();
      ionic.requestAnimationFrame(function() {
        lastDrag.content.style[ionic.CSS.TRANSITION] = '';
      });
    } else {
      ionic.requestAnimationFrame(function() {
        setTimeout(makeInvisible, 250);
      });
    }
    function makeInvisible() {
      lastDrag.buttons && lastDrag.buttons.classList.add('invisible');
    }
  };

  SlideDrag.prototype.drag = ionic.animationFrameThrottle(function(e) {
    var buttonsWidth;

    // We really aren't dragging
    if (!this._currentDrag) {
      return;
    }

    // Check if we should start dragging. Check if we've dragged past the threshold,
    // or we are starting from the open state.
    if (!this._isDragging &&
        ((Math.abs(e.gesture.deltaX) > this.dragThresholdX) ||
        (Math.abs(this._currentDrag.startOffsetX) > 0))) {
      this._isDragging = true;
    }

    if (this._isDragging) {
      buttonsWidth = this._currentDrag.buttonsWidth;

      // Grab the new X point, capping it at zero
      var newX = Math.min(0, this._currentDrag.startOffsetX + e.gesture.deltaX);

      // If the new X position is past the buttons, we need to slow down the drag (rubber band style)
      if (newX < -buttonsWidth) {
        // Calculate the new X position, capped at the top of the buttons
        newX = Math.min(-buttonsWidth, -buttonsWidth + (((e.gesture.deltaX + buttonsWidth) * 0.4)));
      }

      this._currentDrag.content.style[ionic.CSS.TRANSFORM] = 'translate3d(' + newX + 'px, 0, 0)';
      this._currentDrag.content.style[ionic.CSS.TRANSITION] = 'none';
    }
  });

  SlideDrag.prototype.end = function(e, doneCallback) {
    var self = this;

    // There is no drag, just end immediately
    if (!self._currentDrag) {
      doneCallback && doneCallback();
      return;
    }

    // If we are currently dragging, we want to snap back into place
    // The final resting point X will be the width of the exposed buttons
    var restingPoint = -self._currentDrag.buttonsWidth;

    // Check if the drag didn't clear the buttons mid-point
    // and we aren't moving fast enough to swipe open
    if (e.gesture.deltaX > -(self._currentDrag.buttonsWidth / 2)) {

      // If we are going left but too slow, or going right, go back to resting
      if (e.gesture.direction == "left" && Math.abs(e.gesture.velocityX) < 0.3) {
        restingPoint = 0;

      } else if (e.gesture.direction == "right") {
        restingPoint = 0;
      }

    }

    ionic.requestAnimationFrame(function() {
      if (restingPoint === 0) {
        self._currentDrag.content.style[ionic.CSS.TRANSFORM] = '';
        var buttons = self._currentDrag.buttons;
        setTimeout(function() {
          buttons && buttons.classList.add('invisible');
        }, 250);
      } else {
        self._currentDrag.content.style[ionic.CSS.TRANSFORM] = 'translate3d(' + restingPoint + 'px,0,0)';
      }
      self._currentDrag.content.style[ionic.CSS.TRANSITION] = '';

      // Kill the current drag
      if (!self._lastDrag) {
        self._lastDrag = {};
      }
      ionic.extend(self._lastDrag, self._currentDrag);
      if (self._currentDrag) {
        self._currentDrag.buttons = null;
        self._currentDrag.content = null;
      }
      self._currentDrag = null;

      // We are done, notify caller
      doneCallback && doneCallback();
    });
  };

  var ReorderDrag = function(opts) {
    var self = this;

    self.dragThresholdY = opts.dragThresholdY || 0;
    self.onReorder = opts.onReorder;
    self.listEl = opts.listEl;
    self.el = self.item = opts.el;
    self.scrollEl = opts.scrollEl;
    self.scrollView = opts.scrollView;
    // Get the True Top of the list el http://www.quirksmode.org/js/findpos.html
    self.listElTrueTop = 0;
    if (self.listEl.offsetParent) {
      var obj = self.listEl;
      do {
        self.listElTrueTop += obj.offsetTop;
        obj = obj.offsetParent;
      } while (obj);
    }
  };

  ReorderDrag.prototype = new DragOp();

  ReorderDrag.prototype._moveElement = function(e) {
    var y = e.gesture.center.pageY +
      this.scrollView.getValues().top -
      (this._currentDrag.elementHeight / 2) -
      this.listElTrueTop;
    this.el.style[ionic.CSS.TRANSFORM] = 'translate3d(0, ' + y + 'px, 0)';
  };

  ReorderDrag.prototype.deregister = function() {
    this.listEl = this.el = this.scrollEl = this.scrollView = null;
  };

  ReorderDrag.prototype.start = function(e) {
    var content;

    var startIndex = ionic.DomUtil.getChildIndex(this.el, this.el.nodeName.toLowerCase());
    var elementHeight = this.el.scrollHeight;
    var placeholder = this.el.cloneNode(true);

    placeholder.classList.add(ITEM_PLACEHOLDER_CLASS);

    this.el.parentNode.insertBefore(placeholder, this.el);
    this.el.classList.add(ITEM_REORDERING_CLASS);

    this._currentDrag = {
      elementHeight: elementHeight,
      startIndex: startIndex,
      placeholder: placeholder,
      scrollHeight: scroll,
      list: placeholder.parentNode
    };

    this._moveElement(e);
  };

  ReorderDrag.prototype.drag = ionic.animationFrameThrottle(function(e) {
    // We really aren't dragging
    var self = this;
    if (!this._currentDrag) {
      return;
    }

    var scrollY = 0;
    var pageY = e.gesture.center.pageY;
    var offset = this.listElTrueTop;

    //If we have a scrollView, check scroll boundaries for dragged element and scroll if necessary
    if (this.scrollView) {

      var container = this.scrollView.__container;
      scrollY = this.scrollView.getValues().top;

      var containerTop = container.offsetTop;
      var pixelsPastTop = containerTop - pageY + this._currentDrag.elementHeight / 2;
      var pixelsPastBottom = pageY + this._currentDrag.elementHeight / 2 - containerTop - container.offsetHeight;

      if (e.gesture.deltaY < 0 && pixelsPastTop > 0 && scrollY > 0) {
        this.scrollView.scrollBy(null, -pixelsPastTop);
        //Trigger another drag so the scrolling keeps going
        ionic.requestAnimationFrame(function() {
          self.drag(e);
        });
      }
      if (e.gesture.deltaY > 0 && pixelsPastBottom > 0) {
        if (scrollY < this.scrollView.getScrollMax().top) {
          this.scrollView.scrollBy(null, pixelsPastBottom);
          //Trigger another drag so the scrolling keeps going
          ionic.requestAnimationFrame(function() {
            self.drag(e);
          });
        }
      }
    }

    // Check if we should start dragging. Check if we've dragged past the threshold,
    // or we are starting from the open state.
    if (!this._isDragging && Math.abs(e.gesture.deltaY) > this.dragThresholdY) {
      this._isDragging = true;
    }

    if (this._isDragging) {
      this._moveElement(e);

      this._currentDrag.currentY = scrollY + pageY - offset;

      // this._reorderItems();
    }
  });

  // When an item is dragged, we need to reorder any items for sorting purposes
  ReorderDrag.prototype._getReorderIndex = function() {
    var self = this;

    var placeholder = self._currentDrag.placeholder;
    var siblings = Array.prototype.slice.call(self._currentDrag.placeholder.parentNode.children)
      .filter(function(el) {
        return el.nodeName === self.el.nodeName && el !== self.el;
      });

    var dragOffsetTop = self._currentDrag.currentY;
    var el;
    for (var i = 0, len = siblings.length; i < len; i++) {
      el = siblings[i];
      if (i === len - 1) {
        if (dragOffsetTop > el.offsetTop) {
          return i;
        }
      } else if (i === 0) {
        if (dragOffsetTop < el.offsetTop + el.offsetHeight) {
          return i;
        }
      } else if (dragOffsetTop > el.offsetTop - el.offsetHeight / 2 &&
                 dragOffsetTop < el.offsetTop + el.offsetHeight) {
        return i;
      }
    }
    return self._currentDrag.startIndex;
  };

  ReorderDrag.prototype.end = function(e, doneCallback) {
    if (!this._currentDrag) {
      doneCallback && doneCallback();
      return;
    }

    var placeholder = this._currentDrag.placeholder;
    var finalIndex = this._getReorderIndex();

    // Reposition the element
    this.el.classList.remove(ITEM_REORDERING_CLASS);
    this.el.style[ionic.CSS.TRANSFORM] = '';

    placeholder.parentNode.insertBefore(this.el, placeholder);
    placeholder.parentNode.removeChild(placeholder);

    this.onReorder && this.onReorder(this.el, this._currentDrag.startIndex, finalIndex);

    this._currentDrag = {
      placeholder: null,
      content: null
    };
    this._currentDrag = null;
    doneCallback && doneCallback();
  };

  /**
   * The ListView handles a list of items. It will process drag animations, edit mode,
   * and other operations that are common on mobile lists or table views.
   */
  ionic.views.ListView = ionic.views.View.inherit({
    initialize: function(opts) {
      var self = this;

      opts = ionic.extend({
        onReorder: function(el, oldIndex, newIndex) {},
        virtualRemoveThreshold: -200,
        virtualAddThreshold: 200,
        canSwipe: function() {
          return true;
        }
      }, opts);

      ionic.extend(self, opts);

      if (!self.itemHeight && self.listEl) {
        self.itemHeight = self.listEl.children[0] && parseInt(self.listEl.children[0].style.height, 10);
      }

      self.onRefresh = opts.onRefresh || function() {};
      self.onRefreshOpening = opts.onRefreshOpening || function() {};
      self.onRefreshHolding = opts.onRefreshHolding || function() {};

      window.ionic.onGesture('release', function(e) {
        self._handleEndDrag(e);
      }, self.el);

      window.ionic.onGesture('drag', function(e) {
        self._handleDrag(e);
      }, self.el);
      // Start the drag states
      self._initDrag();
    },

    /**
     * Be sure to cleanup references.
     */
    deregister: function() {
      this.el = this.listEl = this.scrollEl = this.scrollView = null;

      // ensure no scrolls have been left frozen
      if (this.isScrollFreeze) {
        self.scrollView.freeze(false);
      }
    },

    /**
     * Called to tell the list to stop refreshing. This is useful
     * if you are refreshing the list and are done with refreshing.
     */
    stopRefreshing: function() {
      var refresher = this.el.querySelector('.list-refresher');
      refresher.style.height = '0';
    },

    /**
     * If we scrolled and have virtual mode enabled, compute the window
     * of active elements in order to figure out the viewport to render.
     */
    didScroll: function(e) {
      var self = this;

      if (self.isVirtual) {
        var itemHeight = self.itemHeight;

        // TODO: This would be inaccurate if we are windowed
        var totalItems = self.listEl.children.length;

        // Grab the total height of the list
        var scrollHeight = e.target.scrollHeight;

        // Get the viewport height
        var viewportHeight = self.el.parentNode.offsetHeight;

        // scrollTop is the current scroll position
        var scrollTop = e.scrollTop;

        // High water is the pixel position of the first element to include (everything before
        // that will be removed)
        var highWater = Math.max(0, e.scrollTop + self.virtualRemoveThreshold);

        // Low water is the pixel position of the last element to include (everything after
        // that will be removed)
        var lowWater = Math.min(scrollHeight, Math.abs(e.scrollTop) + viewportHeight + self.virtualAddThreshold);

        // Compute how many items per viewport size can show
        var itemsPerViewport = Math.floor((lowWater - highWater) / itemHeight);

        // Get the first and last elements in the list based on how many can fit
        // between the pixel range of lowWater and highWater
        var first = parseInt(Math.abs(highWater / itemHeight), 10);
        var last = parseInt(Math.abs(lowWater / itemHeight), 10);

        // Get the items we need to remove
        self._virtualItemsToRemove = Array.prototype.slice.call(self.listEl.children, 0, first);

        // Grab the nodes we will be showing
        var nodes = Array.prototype.slice.call(self.listEl.children, first, first + itemsPerViewport);

        self.renderViewport && self.renderViewport(highWater, lowWater, first, last);
      }
    },

    didStopScrolling: function(e) {
      if (this.isVirtual) {
        for (var i = 0; i < this._virtualItemsToRemove.length; i++) {
          var el = this._virtualItemsToRemove[i];
          //el.parentNode.removeChild(el);
          this.didHideItem && this.didHideItem(i);
        }
        // Once scrolling stops, check if we need to remove old items

      }
    },

    /**
     * Clear any active drag effects on the list.
     */
    clearDragEffects: function(isInstant) {
      if (this._lastDragOp) {
        this._lastDragOp.clean && this._lastDragOp.clean(isInstant);
        this._lastDragOp.deregister && this._lastDragOp.deregister();
        this._lastDragOp = null;
      }
    },

    _initDrag: function() {
      // Store the last one
      if (this._lastDragOp) {
        this._lastDragOp.deregister && this._lastDragOp.deregister();
      }
      this._lastDragOp = this._dragOp;

      this._dragOp = null;
    },

    // Return the list item from the given target
    _getItem: function(target) {
      while (target) {
        if (target.classList && target.classList.contains(ITEM_CLASS)) {
          return target;
        }
        target = target.parentNode;
      }
      return null;
    },

    _startDrag: function(e) {
      var self = this;

      var didStart = false;

      self._isDragging = false;

      var lastDragOp = self._lastDragOp;
      var item;

      // If we have an open SlideDrag and we're scrolling the list. Clear it.
      if (self._didDragUpOrDown && lastDragOp instanceof SlideDrag) {
          lastDragOp.clean && lastDragOp.clean();
      }

      // Check if this is a reorder drag
      if (ionic.DomUtil.getParentOrSelfWithClass(e.target, ITEM_REORDER_BTN_CLASS) && (e.gesture.direction == 'up' || e.gesture.direction == 'down')) {
        item = self._getItem(e.target);

        if (item) {
          self._dragOp = new ReorderDrag({
            listEl: self.el,
            el: item,
            scrollEl: self.scrollEl,
            scrollView: self.scrollView,
            onReorder: function(el, start, end) {
              self.onReorder && self.onReorder(el, start, end);
            }
          });
          self._dragOp.start(e);
          e.preventDefault();
        }
      }

      // Or check if this is a swipe to the side drag
      else if (!self._didDragUpOrDown && (e.gesture.direction == 'left' || e.gesture.direction == 'right') && Math.abs(e.gesture.deltaX) > 5) {

        // Make sure this is an item with buttons
        item = self._getItem(e.target);
        if (item && item.querySelector('.item-options')) {
          self._dragOp = new SlideDrag({
            el: self.el,
            item: item,
            canSwipe: self.canSwipe
          });
          self._dragOp.start(e);
          e.preventDefault();
          self.isScrollFreeze = self.scrollView.freeze(true);
        }
      }

      // If we had a last drag operation and this is a new one on a different item, clean that last one
      if (lastDragOp && self._dragOp && !self._dragOp.isSameItem(lastDragOp) && e.defaultPrevented) {
        lastDragOp.clean && lastDragOp.clean();
      }
    },

    _handleEndDrag: function(e) {
      var self = this;

      self.isScrollFreeze = self.scrollView.freeze(false);

      self._didDragUpOrDown = false;

      if (!self._dragOp) {
        return;
      }

      self._dragOp.end(e, function() {
        self._initDrag();
      });
    },

    /**
     * Process the drag event to move the item to the left or right.
     */
    _handleDrag: function(e) {
      var self = this, content, buttons;

      if (Math.abs(e.gesture.deltaY) > 5) {
        self._didDragUpOrDown = true;
      }

      // If we get a drag event, make sure we aren't in another drag, then check if we should
      // start one
      if (!self.isDragging && !self._dragOp) {
        self._startDrag(e);
      }

      // No drag still, pass it up
      if (!self._dragOp) {
        return;
      }

      e.gesture.srcEvent.preventDefault();
      self._dragOp.drag(e);
    }

  });

})(ionic);


text:
package com.canary.model;

import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.sunny.model.BasicParam;
import org.springframework.format.annotation.DateTimeFormat;

import java.util.Date;

/**
 * 用户模型
 *
 * @author sunny
 * @version 1.0.0
 * @since 2014-11-10
 */
@SuppressWarnings(value = "unused")
public class UserModel extends BasicParam {

    /**
     * 主键
     */
    private Long id;

    /**
     * 昵称
     */
    private String nickname;

    /**
     * 用户
     */
    private String username;

    /**
     * 密码
     */
    private String password;

    /**
     * 密保问题
     */
    private String question;

    /**
     * 密保答案
     */
    private String answer;

    /**
     * 角色
     */
    private String role;

    /**
     * 标记和密钥
     */
    private String sign;

    /**
     * 邮箱
     */
    private String email;

    /**
     * 手机
     */
    private String mobile;

    /**
     * qq
     */
    private String qq;

    /**
     * 性别
     */
    private String sex;

    /**
     * 年龄
     */
    private Integer age;

    /**
     * 生日
     */
    @JSONField(format = "yyyy-MM-dd HH:mm:ss")
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:ss:mm")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private Date birthday;

    /**
     * 头像
     */
    private String image;

    /**
     * 手机号码绑定状态
     */
    private String bindingMobileStatus;

    /**
     * 邮箱绑定状态
     */
    private String bindingEmailStatus;

    /**
     * 登陆失败次数
     */
    private Integer loginFailTimes;

    /**
     * 是否可用
     */
    private String enableStatus;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getNickname() {
        return nickname;
    }

    public void setNickname(String nickname) {
        this.nickname = nickname;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getQuestion() {
        return question;
    }

    public void setQuestion(String question) {
        this.question = question;
    }

    public String getAnswer() {
        return answer;
    }

    public void setAnswer(String answer) {
        this.answer = answer;
    }

    public String getRole() {
        return role;
    }

    public void setRole(String role) {
        this.role = role;
    }

    public String getSign() {
        return sign;
    }

    public void setSign(String sign) {
        this.sign = sign;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }

    public String getQq() {
        return qq;
    }

    public void setQq(String qq) {
        this.qq = qq;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }

    public String getBindingMobileStatus() {
        return bindingMobileStatus;
    }

    public void setBindingMobileStatus(String bindingMobileStatus) {
        this.bindingMobileStatus = bindingMobileStatus;
    }

    public String getBindingEmailStatus() {
        return bindingEmailStatus;
    }

    public void setBindingEmailStatus(String bindingEmailStatus) {
        this.bindingEmailStatus = bindingEmailStatus;
    }

    public String getEnableStatus() {
        return enableStatus;
    }

    public void setEnableStatus(String enableStatus) {
        this.enableStatus = enableStatus;
    }

    public Integer getLoginFailTimes() {
        return loginFailTimes;
    }

    public void setLoginFailTimes(Integer loginFailTimes) {
        this.loginFailTimes = loginFailTimes;
    }

}


text:
/*
 * linux/include/asm-sparc64/timex.h
 *
 * sparc64 architecture timex specifications
 */
#ifndef _ASMsparc64_TIMEX_H
#define _ASMsparc64_TIMEX_H

#include <asm/timer.h>

#define CLOCK_TICK_RATE	1193180 /* Underlying HZ */

/* Getting on the cycle counter on sparc64. */
typedef unsigned long cycles_t;
#define get_cycles()	tick_ops->get_tick()

#endif


text:
require 'rbconfig'

require 'guard/commander'
require 'guard/deprecated_methods'
require 'guard/deprecator'
require 'guard/dsl'
require 'guard/group'
require 'guard/guardfile'
require 'guard/interactor'
require 'guard/notifier'
require 'guard/plugin_util'
require 'guard/runner'
require 'guard/setuper'
require 'guard/ui'
require 'guard/watcher'

# Guard is the main module for all Guard related modules and classes.
# Also Guard plugins should use this namespace.
#
module Guard

  WINDOWS  = RbConfig::CONFIG['host_os'] =~ %r!(msdos|mswin|djgpp|mingw)!
  DEV_NULL = WINDOWS ? 'NUL' : '/dev/null'

  extend Commander
  extend DeprecatedMethods
  extend Setuper

  class << self
    attr_accessor :runner, :listener, :lock, :scope, :running

    # Smart accessor for retrieving specific plugins at once.
    #
    # @see Guard.plugin
    # @see Guard.group
    # @see Guard.groups
    #
    # @example Filter plugins by String or Symbol
    #   Guard.plugins('rspec')
    #   Guard.plugins(:rspec)
    #
    # @example Filter plugins by Regexp
    #   Guard.plugins(/rsp.+/)
    #
    # @example Filter plugins by Hash
    #   Guard.plugins(name: 'rspec', group: 'backend')
    #
    # @param [String, Symbol, Regexp, Hash] filter the filter to apply to the plugins
    # @return [Array<Plugin>] the filtered plugin(s)
    #
    def plugins(filter = nil)
      @plugins ||= []

      return @plugins if filter.nil?

      filtered_plugins = case filter
                        when String, Symbol
                          @plugins.find_all do |plugin|
                            plugin.name == filter.to_s.downcase.gsub('-', '')
                          end
                        when Regexp
                          @plugins.find_all do |plugin|
                            plugin.name =~ filter
                          end
                        when Hash
                          @plugins.find_all do |plugin|
                            filter.all? do |k, v|
                              case k
                              when :name
                                plugin.name == v.to_s.downcase.gsub('-', '')
                              when :group
                                plugin.group.name == v.to_sym
                              end
                            end
                          end
                        end

      filtered_plugins
    end

    # Smart accessor for retrieving a specific plugin.
    #
    # @see Guard.plugins
    # @see Guard.group
    # @see Guard.groups
    #
    # @example Find a plugin by String or Symbol
    #   Guard.plugin('rspec')
    #   Guard.plugin(:rspec)
    #
    # @example Find a plugin by Regexp
    #   Guard.plugin(/rsp.+/)
    #
    # @example Find a plugin by Hash
    #   Guard.plugin(name: 'rspec', group: 'backend')
    #
    # @param [String, Symbol, Regexp, Hash] filter the filter for finding the plugin
    #   the Guard plugin
    # @return [Plugin, nil] the plugin found, nil otherwise
    #
    def plugin(filter)
      plugins(filter).first
    end

    # Smart accessor for retrieving specific groups at once.
    #
    # @see Guard.plugin
    # @see Guard.plugins
    # @see Guard.group
    #
    # @example Filter groups by String or Symbol
    #   Guard.groups('backend')
    #   Guard.groups(:backend)
    #
    # @example Filter groups by Regexp
    #   Guard.groups(/(back|front)end/)
    #
    # @param [String, Symbol, Regexp] filter the filter to apply to the Groups
    # @return [Array<Group>] the filtered group(s)
    #
    def groups(filter = nil)
      @groups ||= []

      return @groups if filter.nil?

      filtered_groups = case filter
                        when String, Symbol
                          @groups.find_all { |group| group.name == filter.to_sym }
                        when Regexp
                          @groups.find_all { |group| group.name.to_s =~ filter }
                        end

      filtered_groups
    end

    # Smart accessor for retrieving a specific group.
    #
    # @see Guard.plugin
    # @see Guard.plugins
    # @see Guard.groups
    #
    # @example Find a group by String or Symbol
    #   Guard.group('backend')
    #   Guard.group(:backend)
    #
    # @example Find a group by Regexp
    #   Guard.group(/(back|front)end/)
    #
    # @param [String, Symbol, Regexp] filter the filter for finding the group
    # @return [Group] the group found, nil otherwise
    #
    def group(filter)
      groups(filter).first
    end

    # Add a Guard plugin to use.
    #
    # @param [String] name the Guard name
    # @param [Hash] options the plugin options (see the given Guard documentation)
    # @option options [String] group the group to which the Guard plugin belongs
    # @option options [Array<Watcher>] watchers the list of declared watchers
    # @option options [Array<Hash>] callbacks the list of callbacks
    # @return [Plugin] the added Guard plugin
    # @see Plugin
    #
    def add_plugin(name, options = {})
      plugin_instance = ::Guard::PluginUtil.new(name).initialize_plugin(options)
      @plugins << plugin_instance

      plugin_instance
    end

    # Add a Guard plugin group.
    #
    # @param [String] name the group name
    # @option options [Boolean] halt_on_fail if a task execution
    #   should be halted for all Guard plugins in this group if
    #   one Guard throws `:task_has_failed`
    # @return [Group] the group added (or retrieved from the `@groups`
    #   variable if already present)
    #
    # @see Group
    #
    def add_group(name, options = {})
      unless group = group(name)
        group = ::Guard::Group.new(name, options)
        @groups << group
      end

      group
    end

  end
end


text:
@class MNObject;
@class ANOption;

@interface APViewController : UIViewController <UIImagePickerControllerDelegate>
{
    ANOption *appOption;

    UIImageView *muiImageView;
    UIImagePickerController *muiImagePickCtrl;
    UIPopoverController *muiPopOver;
}

@property (strong) MNObject *mManager;
@property (strong) ANOption *appOption;

@property (nonatomic, retain) UIImageView *muiImageView;

@property (nonatomic, retain) UIImagePickerController *muiImagePickCtrl;
@property (nonatomic, retain) UIPopoverController *muiPopOver;

//@property (assign) OPSettingVC *mSettingVC;
@property (assign) int mstMode;

//@property (strong) NSArray *arrTest;

@end


text:
/*
 * A Bit of Everything
 *
 * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
 *
 * API version: 1.0
 * Contact: none@example.com
 * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git)
 */

package abe

type ExamplepbUpdateV2Request struct {
	Abe *ExamplepbABitOfEverything `json:"abe,omitempty"`
	UpdateMask *ProtobufFieldMask `json:"update_mask,omitempty"`
}


text:
require 'generators/glass'
require 'rails/generators'
require 'rails/generators/migration'

module Glass
  module Generators
    class ModelGenerator < ::Rails::Generators::Base
      argument :model_name, type: :string

      def self.source_root
        @source_root ||= File.expand_path(File.join(File.dirname(__FILE__), 'templates'))
      end

      def copy_glass_templates
        unless File.directory?("app/models/glass/")
          empty_directory("app/models/glass")
        end
      end
      def create_glass_model
        template("model.rb", "app/models/glass/#{model_name.underscore}.rb")
      end
    end
  end
end


text:
<?php

namespace Detail\Commanding;

use Detail\Commanding\Command\CommandInterface;

interface CommandDispatcherInterface
{
    public function register($commandName, $commandHandler);

    public function handle(CommandInterface $command);
}


text:
describe MangoPay::PayIn::DirectDebit::Direct, type: :feature do
  include_context 'payins'

  def check_type_and_status(payin)
    expect(payin['Type']).to eq('PAYIN')
    expect(payin['Nature']).to eq('REGULAR')
    expect(payin['PaymentType']).to eq('DIRECT_DEBIT')
    expect(payin['ExecutionType']).to eq('DIRECT')

    # FAILED: the related Mandate is not confirmed yet
    expect(payin['Status']).to eq('FAILED')
    expect(payin['ResultMessage']).to eq('The Status of this Mandate does not allow for payments')
    expect(payin['ExecutionDate']).to be_nil
  end

  describe 'CREATE' do
    it 'creates a directdebit direct payin' do
      created = new_payin_directdebit_direct
      expect(created['Id']).not_to be_nil
      check_type_and_status(created)
    end
  end

  describe 'FETCH' do
    it 'fetches a payin' do
      created = new_payin_directdebit_direct
      fetched = MangoPay::PayIn.fetch(created['Id'])
      expect(fetched['Id']).to eq(created['Id'])
      expect(fetched['CreationDate']).to eq(created['CreationDate'])
      expect(fetched['CreditedFunds']).to eq(created['CreditedFunds'])
      expect(fetched['CreditedWalletId']).to eq(created['CreditedWalletId'])
      check_type_and_status(created)
      check_type_and_status(fetched)
    end
  end

end


text:
package com.github.jxsd.xml.reflect;

import com.github.jxsd.xml.annotation.Required;
import com.github.jxsd.xml.annotation.Value;
import com.github.jxsd.xml.exception.ValueAlreadyDefinedException;
import org.junit.Test;

import java.util.Date;
import java.util.List;

import static com.github.jxsd.xml.NameNormalizer.FIRST_LOWER_CASE;
import static com.github.jxsd.xml.reflect.Reflect.elementFromClass;
import static org.junit.Assert.*;

public class ReflectTest {

    @Test(expected = NullPointerException.class)
    public void testElementFromClassNull() throws Exception {
        elementFromClass(null);
    }

    @Test
    public void testElementFromClassEmpty() {
        class a {
        }
        ElementTemplate element = elementFromClass(a.class);
        assertEquals(a.class, element.clazz);
        assertEquals("a", element.name);
        assertEquals(0, element.attributes.size());
        assertEquals(0, element.children.size());
        assertNull(element.getValue());
    }

    @Test
    public void testElementFromClassEmptyFirstLowerCaseNormalizer() {
        class Asd {
        }
        ElementTemplate element = elementFromClass(FIRST_LOWER_CASE, Asd.class);
        assertEquals(Asd.class, element.clazz);
        assertEquals("asd", element.name);
        assertEquals(0, element.attributes.size());
        assertEquals(0, element.children.size());
        assertNull(element.getValue());
    }

    @Test
    public void testElementFromClassFirstLowerCaseNormalizer() {
        class TestNode {
        }
        class Asd {
            String FirstAttribute;
            String secondAttribute;
            List<TestNode> Children;
        }
        ElementTemplate element = elementFromClass(FIRST_LOWER_CASE, Asd.class);
        assertEquals(Asd.class, element.clazz);
        assertEquals("asd", element.name);
        assertEquals(2, element.attributes.size());
        assertTrue(element.attributes.containsKey("firstAttribute"));
        assertTrue(element.attributes.containsKey("secondAttribute"));
        assertEquals(1, element.children.size());
        assertEquals("testNode", element.children.get(0).name);
        assertNull(element.getValue());
    }

    @Test
    public void testElementFromClassEmptyHasValue() {
        class a {
            @Value
            String value;
        }
        ElementTemplate element = elementFromClass(a.class);
        assertEquals(a.class, element.clazz);
        assertEquals("a", element.name);
        assertEquals(0, element.attributes.size());
        assertEquals(0, element.children.size());
        assertNotNull(element.getValue());
    }

    @Test(expected = ValueAlreadyDefinedException.class)
    public void testElementFromClass2Values() {
        class a {
            @Value
            String value;
            @Value
            String value2;
        }
        elementFromClass(a.class);
    }

    @Test
    public void testElementFromClassSingleAttribute() {
        class a {
            String name;
        }
        ElementTemplate element = elementFromClass(a.class);
        assertEquals(a.class, element.clazz);
        assertEquals("a", element.name);
        assertEquals(0, element.children.size());
        assertEquals(1, element.attributes.size());
        assertTrue(element.attributes.containsKey("name"));
        assertEquals(String.class, element.attributes.get("name").clazz);
        assertNull(element.getValue());
    }

    @Test
    public void testElementFromClassSingleAttributeAnnotation() {
        class a {
            @Required
            String name;
        }
        ElementTemplate element = elementFromClass(a.class);
        assertEquals(a.class, element.clazz);
        assertEquals("a", element.name);
        assertEquals(0, element.children.size());
        assertEquals(1, element.attributes.size());
        assertTrue(element.attributes.containsKey("name"));
        assertEquals(String.class, element.attributes.get("name").clazz);
        assertNotNull(element.attributes.get("name").annotations);
        assertEquals(1, element.attributes.get("name").annotations.length);
        assertEquals(Required.class, element.attributes.get("name").annotations[0]);
        assertNull(element.getValue());
    }

    @Test
    public void testElementFromClassSingleAttributeTransient() {
        class a {
            String name;
            transient String foo;
        }
        ElementTemplate element = elementFromClass(a.class);
        assertEquals(a.class, element.clazz);
        assertEquals("a", element.name);
        assertEquals(0, element.children.size());
        assertEquals(1, element.attributes.size());
        assertTrue(element.attributes.containsKey("name"));
        assertEquals(String.class, element.attributes.get("name").clazz);
        assertNull(element.getValue());
    }

    @Test
    public void testElementFromClassMultipleAttributes() {
        class a {
            String name;
            int age;
            Date born;
            Float weight;
        }
        ElementTemplate element = elementFromClass(a.class);
        assertEquals(a.class, element.clazz);
        assertEquals("a", element.name);
        assertEquals(0, element.children.size());
        assertEquals(4, element.attributes.size());
        assertTrue(element.attributes.containsKey("name"));
        assertEquals(String.class, element.attributes.get("name").clazz);
        assertTrue(element.attributes.containsKey("age"));
        assertEquals(int.class, element.attributes.get("age").clazz);
        assertTrue(element.attributes.containsKey("born"));
        assertEquals(Date.class, element.attributes.get("born").clazz);
        assertTrue(element.attributes.containsKey("weight"));
        assertEquals(Float.class, element.attributes.get("weight").clazz);
        assertNull(element.getValue());
    }

    @Test
    public void testElementFromClassChild() {
        class b {
        }
        class a {
            List<b> bs;
        }
        ElementTemplate element = elementFromClass(a.class);
        assertEquals(a.class, element.clazz);
        assertEquals("a", element.name);
        assertEquals(0, element.attributes.size());
        assertEquals(1, element.children.size());
        assertNull(element.getValue());
        ElementTemplate child = element.children.get(0);
        assertEquals(b.class, child.clazz);
        assertEquals("b", child.name);
        assertEquals(0, child.attributes.size());
        assertEquals(0, child.children.size());
        assertNull(element.getValue());
    }

    @Test(expected = DuplicateException.class)
    public void testElementFromClassChildDuplicate() {
        class b {
        }
        class a {
            List<b> bs;
            List<b> bs2;
        }
        elementFromClass(a.class);
    }
}


text:
from __future__ import unicode_literals

import django.core.validators
from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('reviews', '0003_auto_20160712_0137'),
    ]

    operations = [
        migrations.AlterField(
            model_name='review',
            name='ques2',
            field=models.PositiveIntegerField(validators=[django.core.validators.MinValueValidator(1), django.core.validators.MaxValueValidator(5)], verbose_name='How competent is this person in their domain of expertise (1-5)? (5 = most)'),
        ),
        migrations.AlterField(
            model_name='review',
            name='ques3',
            field=models.PositiveIntegerField(validators=[django.core.validators.MinValueValidator(1), django.core.validators.MaxValueValidator(5)], verbose_name='How much did you learn from this individual while working with them (1-5)? (5 = most)'),
        ),
        migrations.AlterField(
            model_name='userlevel',
            name='level',
            field=models.CharField(max_length=15),
        ),
    ]


text:
import unittest
import sys
import sqlite3
sys.path.append('../')
sys.path.append('../lib')
import SQLite

# TODO: Get a database connection for testing merge

def create_connections():
    cls.conn1 = sqlite3.connect(':memory:')
    cls.conn2 = sqlite3.connect(':memory:')

def close_connections():
    conn1.close()
    conn2.close()

def create_assignee_schema(cursor):
    cursor.executescript("""
        CREATE TABLE IF NOT EXISTS assignee (
            Patent VARCHAR(8),      AsgType INTEGER,        Assignee VARCHAR(30),
            City VARCHAR(10),       State VARCHAR(2),       Country VARCHAR(2),
            Nationality VARCHAR(2), Residence VARCHAR(2),   AsgSeq INTEGER);
        CREATE UNIQUE INDEX IF NOT EXISTS uqAsg ON assignee (Patent, AsgSeq);
        DROP INDEX IF EXISTS idx_pata;
        DROP INDEX IF EXISTS idx_patent;
        DROP INDEX IF EXISTS idx_asgtyp;
        DROP INDEX IF EXISTS idx_stt;
        DROP INDEX IF EXISTS idx_cty;
        """)

def initialize_assignees(conn):
    q = ('D0656296',2,'Frito-Lay North America, Inc.','Plano','TX','US','','',0)
    conn.cursor().execute("""INSERT OR IGNORE INTO assignee VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)""", q)
    conn.commit()

class TestSQLite(unittest.TestCase):

    @classmethod
    def setUp(cls):
        #print "Setting up..."
        cls.conn1 = sqlite3.connect(':memory:')
        cls.conn2 = sqlite3.connect(':memory:')
        #create_connections()

    @classmethod
    def tearDown(cls):
        #print "Tearing down..."
        cls.conn1.close()
        cls.conn2.close()
        #close_connections()

    def test_constructor_empty(self):
        s = SQLite.SQLite()
        assert(s.db == ':memory:')
        assert(s.tbl == 'main')

    def test_constructor_dbname(self):
        s = SQLite.SQLite(db='foobar.sqlite3')
        assert(s.db == 'foobar.sqlite3')
        assert(s.tbl == 'main')

    def test_constructor_dbname_tbl(self):
        s = SQLite.SQLite(db='foobar.sqlite3', tbl='tbl_foo')
        assert(s.db == 'foobar.sqlite3')
        assert(s.tbl == 'tbl_foo')

    def test_constructor_dbname_tbl_table(self):
        s = SQLite.SQLite(db='foobar.sqlite3', tbl='tbl_foo', table='table_foo')
        assert(s.db == 'foobar.sqlite3')
        assert(s.tbl == 'tbl_foo')

    def test_constructor_dbname_table(self):
        s = SQLite.SQLite(db='foobar.sqlite3', table='table_foo')
        assert(s.db == 'foobar.sqlite3')
        assert(s.tbl == 'table_foo')

#    def test_merge(self):
#        s = SQLite.SQLite()
#        s.merge(key=[['AsgNum', 'pdpass']], on=[['assigneeAsc', 'assignee']],
#                keyType=['INTEGER'], tableFrom='main', db='db')
#        assert(1 == 1)

    def test_index(self):
        s = SQLite.SQLite('test.sqlite3')
        create_assignee_schema(s.c)
        initialize_assignees(s.conn)
        assert(1 == 1)

if __name__ == '__main__':
    unittest.main()


text:
"""
api_system.py : Trovebox System API Classes
"""
from .api_base import ApiBase

class ApiSystem(ApiBase):
    """ Definitions of /system/ API endpoints """
    def version(self, **kwds):
        """
        Endpoint: /system/version.json

        Returns a dictionary containing the various server version strings
        """
        return self._client.get("/system/version.json", **kwds)["result"]

    def diagnostics(self, **kwds):
        """
        Endpoint: /system/diagnostics.json

        Runs a set of diagnostic tests on the server.
        Returns a dictionary containing the results.
        """
        # Don't process the result automatically, since this raises an exception
        # on failure, which doesn't provide the cause of the failure
        self._client.get("/system/diagnostics.json", process_response=False,
                         **kwds)
        return self._client.last_response.json()["result"]


text:
using System;
using System.Collections.Generic;
using System.Text;
using wojilu.IO;
using wojilu.Web.Templates.Parser;
using wojilu.Web.Templates.Tokens;

namespace wojilu.Web {

    /// <summary>
    /// Ä£°åÒýÇæ
    /// </summary>
    public class Template : ContentBlock, ITemplate {

        private static readonly ILog logger = LogManager.GetLogger( typeof( Template ) );

        public static readonly String loadedTemplates = "loadedTemplates";

        private String _templateContent;

        public Template() {
        }

        public Template( String absPath ) {

            InitPath( absPath );
        }

        public Template( String absPath, StringBuilder builder ) {

            //base.resultBuilder = builder;

            InitPath( absPath );
        }

        private static Dictionary<String, String> templates = new Dictionary<String, String>();

        private object objLockReadFile = new object();

        private void InitPath( String templatePath ) {

            Boolean isCache = Mvc.MvcConfig.Instance.IsCacheView;

            if (isCache) {
                String templateContent = getTemplateContent( templatePath );
                if (strUtil.HasText( templateContent )) {
                    logTemplate( templatePath );
                    InitContent( templatePath, templateContent );
                }
            }
            else {
                if (File.Exists( templatePath )) {
                    logTemplate( templatePath );
                    InitContent( File.Read( templatePath ) );
                }
                else
                    _isTemplateExist = false;

            }
        }

        private void logTemplate( string templatePath ) {
            //logger.Info( "load template=>" + templatePath );
            List<String> tplList = CurrentRequest.getItem( loadedTemplates ) as List<String>;
            if (tplList == null) tplList = new List<string>();
            tplList.Add( templatePath );
            CurrentRequest.setItem( loadedTemplates, tplList );
        }

        private String getTemplateContent( String templatePath ) {

            if (templates.ContainsKey( templatePath ) == false) {

                lock (objLockReadFile) {

                    if (templates.ContainsKey( templatePath ) == false) {

                        templates[templatePath] = readTemplateBodyToCache( templatePath );
                    }
                }
            }

            return templates[templatePath];
        }

        private String readTemplateBodyToCache( String templatePath ) {
            String templateContent = "";
            if (File.Exists( templatePath )) {
                templateContent = File.Read( templatePath );
            }
            if (strUtil.IsNullOrEmpty( templateContent )) _isTemplateExist = false;
            return templateContent;
        }

        public ITemplate InitContent( String content ) {
            _templateContent = content;

            TemplateParser parser = TemplateParser.GetParser( content );
            _thisToken = parser.getToken() as BlockToken;
            return this;
        }

        public ITemplate InitContent( String content, StringBuilder resultBuilder ) {
            //base.resultBuilder = resultBuilder;
            return InitContent( content );
        }

        public ITemplate InitContent( String absPath, String content ) {

            _templateContent = content;

            TemplateParser parser = TemplateParser.GetParser( absPath, content );
            _thisToken = parser.getToken() as BlockToken;

            return this;
        }

        public Boolean IsEmpty {
            get { return strUtil.IsNullOrEmpty( this._templateContent ); }
        }

        public void Replace( String lbl, String lblValue ) {
        }

        public override String ToString() {

            if (strUtil.IsNullOrEmpty( _templateContent )) return "";

            //logger.Info( "_templateContent=>" + _templateContent );
            return base.ToString();
        }

        public String getTemplateString() {
            return _templateContent;
        }

    }
}


text:
'use strict';

module.exports = function (math) {
  var util = require('../../util/index'),

      BigNumber = math.type.BigNumber,
      Complex = require('../../type/Complex'),
      Unit = require('../../type/Unit'),
      collection = math.collection,

      isNumber = util.number.isNumber,
      isBoolean = util['boolean'].isBoolean,
      isComplex = Complex.isComplex,
      isUnit = Unit.isUnit,
      isCollection = collection.isCollection,

      bigSech = util.bignumber.cosh_sinh_csch_sech;

  /**
   * Calculate the hyperbolic secant of a value,
   * defined as `sech(x) = 1 / cosh(x)`.
   *
   * For matrices, the function is evaluated element wise.
   *
   * Syntax:
   *
   *    math.sech(x)
   *
   * Examples:
   *
   *    // sech(x) = 1/ cosh(x)
   *    math.sech(0.5);       // returns 0.886818883970074
   *    1 / math.cosh(0.5);   // returns 0.886818883970074
   *
   * See also:
   *
   *    cosh, csch, coth
   *
   * @param {Number | Boolean | Complex | Unit | Array | Matrix | null} x  Function input
   * @return {Number | Complex | Array | Matrix} Hyperbolic secant of x
   */
  math.sech = function sech(x) {
    if (arguments.length != 1) {
      throw new math.error.ArgumentsError('sech', arguments.length, 1);
    }

    if (isNumber(x)) {
      return 2 / (Math.exp(x) + Math.exp(-x));
    }

    if (isComplex(x)) {
      var ep = Math.exp(x.re);
      var en = Math.exp(-x.re);
      var re = Math.cos(x.im) * (ep + en);
      var im = Math.sin(x.im) * (ep - en);
      var den = re * re + im * im;
      return new Complex(2 * re / den, -2 * im / den);
    }

    if (isUnit(x)) {
      if (!x.hasBase(Unit.BASE_UNITS.ANGLE)) {
        throw new TypeError ('Unit in function sech is no angle');
      }
      return sech(x.value);
    }

    if (isCollection(x)) {
      return collection.deepMap(x, sech);
    }

    if (isBoolean(x) || x === null) {
      return sech(x ? 1 : 0);
    }

    if (x instanceof BigNumber) {
      return bigSech(x, BigNumber, false, true);
    }

    throw new math.error.UnsupportedTypeError('sech', math['typeof'](x));
  };
};


text:
tinyMCELang['lang_insert_emotions_title'] = 'Insèrer un émoticon';
tinyMCELang['lang_emotions_desc'] = 'Émoticons';


text:
#import "UIWindow.h"

@interface SBWindow : UIWindow
{
    int _jailBehavior;
}

+ (struct CGRect)_actualBoundsForScreen:(id)arg1 withJailBehavior:(int)arg2;
+ (struct UIEdgeInsets)_jailInsetsForScreen:(id)arg1;
- (_Bool)_isClippedByScreenJail;
- (_Bool)_isConstrainedByScreenJail;
- (void)setAlpha:(double)arg1;
- (void)setScreen:(id)arg1;
@property(readonly, nonatomic) struct UIEdgeInsets jailInsets;
- (id)initWithFrame:(struct CGRect)arg1;
- (id)initWithScreen:(id)arg1 jailBehavior:(int)arg2;
- (void)setAlphaAndObeyBecauseIAmTheWindowManager:(double)arg1;

@end


text:
/*
 * CovarianceMatrixModelWithSubMatricesModel_Test_05012014Test.java
 *
 * The naming of this file is the name of the .java file being tested, combined
 * with test since this is the test file, combined with the creation date of
 * this file. The test at the end is so that the file runs from NetBeans when
 * testing an entire project.
 *
 * Created on May 1, 2014.
 *
 *
 *Version History:
 *May 1 2014: File Created.
 *May 2 2014: Constructor and most method tests done. Unfinished tests exist at
 *              at the bottom of the file.
 *
 *
 *Developed for the CIRDLES lab at the College of Charleston by Patrick Brewer.
 *
 *
 */

package org.earthtime.matrices.matrixModels;

import java.util.Map;
import Jama.Matrix;
import java.util.HashMap;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import org.junit.Test;

/**
 *
 * @author patrickbrewer
 */
public class CovarianceMatrixWithSubMatricesModelTest {

    /////////////////////////
    ////Constructor Tests////
    /////////////////////////

     /**
     * Test of CovarianceMatrixModelWithSubMatricesModel() method, of class CovarianceMatrixModelWithSubMatricesModel.
     */
    @Test
    public void test_constructor_0(){
	System.out.println("Testing CovarianceMatrixWithSubMatricesModel's CovarianceMatrixWithSubMatricesModel()");
        //Tests if values are correct
        CovarianceMatrixWithSubMatricesModel hi=new CovarianceMatrixWithSubMatricesModel();
        String result=hi.levelName;
        Map<Integer,String> ro=hi.rows;
        Map<String,Integer> cp=hi.cols;
        Matrix ma=hi.matrix;

        assertEquals("Covariances",result);
        assertEquals("{}",ro.toString());
        assertEquals("{}",cp.toString());
        assertEquals(null,ma);
        assertEquals(null,hi.getLambdasCovarianceMatrix());
        assertEquals(null,hi.getTracerCovarianceMatrix());
        assertEquals(null,hi.getAnalyticalCovarianceMatrix());
        assertEquals(false,hi.isSubMatricesExist());

        }

    ////////////////////
    ////Method Tests////
    ////////////////////

    /**
     * Test of copy method, of class CovarianceMatrixWithSubMatricesModel.
     */
    @Test
    public void test_Copy() {
        System.out.println("Testing CovarianceMatrixWithSubMatricesModel's copy(CovarianceMatrixWithSubMatricesModel parent)");
        CovarianceMatrixWithSubMatricesModel instance = new CovarianceMatrixWithSubMatricesModel();

        Matrix ma=new Matrix(1,1);
        ma.set(0, 0, 51);

        instance.setMatrix(ma);

        Map<Integer,String> co=new HashMap();
        Map<Integer,String> ro=new HashMap();
        co.put(1, "one");
        ro.put(2, "two");

        instance.setCols(co);
        instance.setRows(ro);

        instance.setSubMatricesExist(true);

        CovarianceMatrixWithSubMatricesModel b4=(CovarianceMatrixWithSubMatricesModel)instance.getLambdasCovarianceMatrix();
        CovarianceMatrixWithSubMatricesModel before=(CovarianceMatrixWithSubMatricesModel)instance.getTracerCovarianceMatrix();
        CovarianceMatrixWithSubMatricesModel b34=(CovarianceMatrixWithSubMatricesModel)instance.getAnalyticalCovarianceMatrix();

        CovarianceMatrixWithSubMatricesModel lamb=new CovarianceMatrixWithSubMatricesModel();
        instance.setLambdasCovarianceMatrix(lamb);

        CovarianceMatrixWithSubMatricesModel trac=new CovarianceMatrixWithSubMatricesModel();
        instance.setTracerCovarianceMatrix(trac);

        CovarianceMatrixWithSubMatricesModel anal=new CovarianceMatrixWithSubMatricesModel();
        instance.setAnalyticalCovarianceMatrix(anal);

        AbstractMatrixModel result = instance.copy();

        assertEquals("{one=1}",result.cols.toString() );
        assertEquals("{2=two}",result.rows.toString() );
        assertEquals(51,(int)result.getMatrix().get(0, 0) );
        assertEquals(true,((CovarianceMatrixWithSubMatricesModel)result).isSubMatricesExist());
        if(instance.getLambdasCovarianceMatrix().equals(b4))
            fail("Lambas should not be null!");
        if(instance.getTracerCovarianceMatrix().equals(before))
            fail("Lambas should not be null!");
        if(instance.getAnalyticalCovarianceMatrix().equals(b34))
            fail("Lambas should not be null!");
    }

        /**
     * Test of isSubMatricesExist method, of class CovarianceMatrixWithSubMatricesModel.
     *   */
    @Test
    public void test_IsSubMatricesExist() {
        System.out.println("Testing CovarianceMatrixWithSubMatricesModel's isSubMatricesExist()");
        CovarianceMatrixWithSubMatricesModel instance = new CovarianceMatrixWithSubMatricesModel();
        boolean expResult = false;
        boolean result = instance.isSubMatricesExist();
        assertEquals(expResult, result);
        expResult=true;
        instance.setSubMatricesExist(true);
        result=instance.isSubMatricesExist();
        assertEquals(expResult, result);
    }

        /**
     * Test of setSubMatricesExist method, of class CovarianceMatrixWithSubMatricesModel.
     * */
    @Test
    public void test_SetSubMatricesExist() {
        System.out.println("Testing CovarianceMatrixWithSubMatricesModel's setSubMatricesExist(boolean Existence)");
        boolean subMatricesExist = true;
        CovarianceMatrixWithSubMatricesModel instance = new CovarianceMatrixWithSubMatricesModel();
        instance.setSubMatricesExist(subMatricesExist);
        assertEquals(true,instance.isSubMatricesExist());
        subMatricesExist=false;
        instance.setSubMatricesExist(subMatricesExist);
        assertEquals(false,instance.isSubMatricesExist());

    }

    /**
     * Test of getLambdasCovarianceMatrix method, of class CovarianceMatrixWithSubMatricesModel.
    */
    @Test
    public void test_GetLambdasCovarianceMatrix() {
        System.out.println("Testing CovarianceMatrixWithSubMatricesModel's getLambdasCovarianceMatrix()");
        CovarianceMatrixWithSubMatricesModel instance = new CovarianceMatrixWithSubMatricesModel();
        AbstractMatrixModel expResult = null;

        CovarianceMatrixWithSubMatricesModel result=(CovarianceMatrixWithSubMatricesModel)instance.getLambdasCovarianceMatrix();
        assertEquals(expResult, result);

        CovarianceMatrixWithSubMatricesModel set = new CovarianceMatrixWithSubMatricesModel();
        instance.setLambdasCovarianceMatrix(set);

        CovarianceMatrixWithSubMatricesModel result2=(CovarianceMatrixWithSubMatricesModel)instance.getLambdasCovarianceMatrix();

        if(result2.equals(result))
            fail("Lambas should not be null!");
    }

        /**
     * Test of getTracerCovarianceMatrix method, of class CovarianceMatrixWithSubMatricesModel.
   */
    @Test
    public void test_GetTracerCovarianceMatrix() {
        System.out.println("Testing CovarianceMatrixWithSubMatricesModel's getTracerCovarianceMatrix()");
        CovarianceMatrixWithSubMatricesModel instance = new CovarianceMatrixWithSubMatricesModel();
        AbstractMatrixModel expResult = null;

        CovarianceMatrixWithSubMatricesModel result=(CovarianceMatrixWithSubMatricesModel)instance.getTracerCovarianceMatrix();
        assertEquals(expResult, result);

        CovarianceMatrixWithSubMatricesModel set = new CovarianceMatrixWithSubMatricesModel();
        instance.setTracerCovarianceMatrix(set);

        CovarianceMatrixWithSubMatricesModel result2=(CovarianceMatrixWithSubMatricesModel)instance.getTracerCovarianceMatrix();

        if(result2.equals(result))
            fail("Tracer should not be null!");
    }

        /**
     * Test of getAnalyticalCovarianceMatrix method, of class CovarianceMatrixWithSubMatricesModel.
     */
    @Test
    public void test_GetAnalyticalCovarianceMatrix() {
        System.out.println("Testing CovarianceMatrixWithSubMatricesModel's getAnalyticalCovarianceMatrix()");
        CovarianceMatrixWithSubMatricesModel instance = new CovarianceMatrixWithSubMatricesModel();
        AbstractMatrixModel expResult = null;

        CovarianceMatrixWithSubMatricesModel result=(CovarianceMatrixWithSubMatricesModel)instance.getAnalyticalCovarianceMatrix();
        assertEquals(expResult, result);

        CovarianceMatrixWithSubMatricesModel set = new CovarianceMatrixWithSubMatricesModel();
        instance.setAnalyticalCovarianceMatrix(set);

        CovarianceMatrixWithSubMatricesModel result2=(CovarianceMatrixWithSubMatricesModel)instance.getAnalyticalCovarianceMatrix();

        if(result2.equals(result))
            fail("Analytical should not be null!");
    }

        /**
     * Test of setLambdasCovarianceMatrix method, of class CovarianceMatrixWithSubMatricesModel.
    */
    @Test
    public void test_SetLambdasCovarianceMatrix() {
        System.out.println("Testing CovarianceMatrixWithSubMatricesModel's setLambdasCovarianceMatrix(CovarianceMatrixWithSubMatricesModel lambda)");
        CovarianceMatrixWithSubMatricesModel instance = new CovarianceMatrixWithSubMatricesModel();
        AbstractMatrixModel expResult = null;

        CovarianceMatrixWithSubMatricesModel result=(CovarianceMatrixWithSubMatricesModel)instance.getLambdasCovarianceMatrix();
        assertEquals(expResult, result);

        CovarianceMatrixWithSubMatricesModel set = new CovarianceMatrixWithSubMatricesModel();
        instance.setLambdasCovarianceMatrix(set);

        CovarianceMatrixWithSubMatricesModel result2=(CovarianceMatrixWithSubMatricesModel)instance.getLambdasCovarianceMatrix();

        if(result2.equals(result))
            fail("Lambas should not be null!");

        instance.setLambdasCovarianceMatrix(null);
        result=(CovarianceMatrixWithSubMatricesModel)instance.getLambdasCovarianceMatrix();
        assertEquals(expResult, result);

    }

        /**
     * Test of setTracerCovarianceMatrix method, of class CovarianceMatrixWithSubMatricesModel.
    */
    @Test
    public void test_SetTracerCovarianceMatrix() {
        System.out.println("Testing CovarianceMatrixWithSubMatricesModel's setTracerCovarianceMatrix(CovarianceMatrixWithSubMatricesModel tracer)");
        CovarianceMatrixWithSubMatricesModel instance = new CovarianceMatrixWithSubMatricesModel();
        AbstractMatrixModel expResult = null;

        CovarianceMatrixWithSubMatricesModel result=(CovarianceMatrixWithSubMatricesModel)instance.getTracerCovarianceMatrix();
        assertEquals(expResult, result);

        CovarianceMatrixWithSubMatricesModel set = new CovarianceMatrixWithSubMatricesModel();
        instance.setTracerCovarianceMatrix(set);

        CovarianceMatrixWithSubMatricesModel result2=(CovarianceMatrixWithSubMatricesModel)instance.getTracerCovarianceMatrix();

        if(result2.equals(result))
            fail("Lambas should not be null!");

        instance.setTracerCovarianceMatrix(null);
        result=(CovarianceMatrixWithSubMatricesModel)instance.getTracerCovarianceMatrix();
        assertEquals(expResult, result);

    }

        /**
     * Test of setAnalyticalCovarianceMatrix method, of class CovarianceMatrixWithSubMatricesModel.
     * */
    @Test
    public void test_SetAnalyticalCovarianceMatrix() {
        System.out.println("Testing CovarianceMatrixWithSubMatricesModel's setAnalyticalCovarianceMatrix(CovarianceMatrixWithSubMatricesModel analytical)");
        CovarianceMatrixWithSubMatricesModel instance = new CovarianceMatrixWithSubMatricesModel();
        AbstractMatrixModel expResult = null;

        CovarianceMatrixWithSubMatricesModel result=(CovarianceMatrixWithSubMatricesModel)instance.getAnalyticalCovarianceMatrix();
        assertEquals(expResult, result);

        CovarianceMatrixWithSubMatricesModel set = new CovarianceMatrixWithSubMatricesModel();
        instance.setAnalyticalCovarianceMatrix(set);

        CovarianceMatrixWithSubMatricesModel result2=(CovarianceMatrixWithSubMatricesModel)instance.getAnalyticalCovarianceMatrix();

        if(result2.equals(result))
            fail("Lambas should not be null!");

        instance.setAnalyticalCovarianceMatrix(null);
        result=(CovarianceMatrixWithSubMatricesModel)instance.getAnalyticalCovarianceMatrix();
        assertEquals(expResult, result);
    }

    ////////////////////////
    ////Unfinished Tests////
    ////////////////////////

    /*
     *
     *
     *CovarianceMatrixWithSubMatricesModel.setCovarianceCells(String covarianceName,double coVariance)
     *  This method has some comments in it that may or may not mean that
     *      functionality is not correct at the moment.
     *  These methods will simply involve too much time and effort to be
     *      implemented at this point in time, as it involves a lot of digging.
     *      I do not have enough time alotted to complete these at this time.
     *
     *
     *CovarianceMatrixWithSubMatricesModel.recalculateSubCovariances(String[] covaryingTerms, BigDecimal oneSigma, boolean lockVariancesTogether)
     *CovarianceMatrixWithSubMatricesModel.initializeMatrixModelWithVariances(Map<String, BigDecimal> variances)
     *  These methods will simply involve too much time and effort to be
     *      implemented at this point in time, as it involves a lot of digging.
     *      I do not have enough time alotted to complete these at this time.     *
     */

 }


text:
package jp.pigumer.sbt.cloud.aws.cloudformation

abstract class Parameters {
  def values: Map[String, String]
}

object Parameters {

  def apply(elems: Map[String, String]): Parameters =
    new Parameters {
      override def values: Map[String, String] = elems
    }
}