text:
describe StarterFileGroupsController do
  shared_examples 'student and ta not permitted' do
    before { subject }
    context 'a grader' do
      let(:user) { create :ta }
      it 'should not be permitted' do
        expect(response.status).to eq 403
      end
    end
    context 'a student' do
      let(:user) { create :student }
      it 'should not be permitted' do
        expect(response.status).to eq 403
      end
    end
  end

  let(:user) { create :admin }
  let(:assignment) { create :assignment }
  describe '#create' do
    subject { post_as user, :create, params: { name: 'b', assignment_id: assignment.id } }
    it_behaves_like 'student and ta not permitted'
    before { subject }
    it 'should create a new starter file group' do
      expect(assignment.reload.starter_file_groups).not_to be_empty
    end
    it 'should set the name' do
      expect(assignment.reload.starter_file_groups.first.name).to eq 'b'
    end
  end
  describe '#destroy' do
    let(:starter_file_group) { create :starter_file_group_with_entries, assignment: assignment }
    subject { delete_as user, :destroy, params: { id: starter_file_group.id, assignment_id: assignment.id } }
    it_behaves_like 'student and ta not permitted'

    it 'should delete the starter file group' do
      subject
      expect { starter_file_group.reload }.to raise_error(ActiveRecord::RecordNotFound)
    end
  end
  describe '#download_file' do
    let(:starter_file_group) { create :starter_file_group_with_entries, assignment: assignment }
    let(:filename) { 'q2.txt' }
    subject do
      get_as user, :download_file, params: { file_name: filename,
                                             id: starter_file_group.id,
                                             assignment_id: assignment.id }
    end
    it_behaves_like 'student and ta not permitted'
    before { subject }
    context 'when a file exists' do
      it 'should download a file' do
        expect(response.body).to eq 'q2 content'
      end
    end
    context 'when a nested file exists' do
      let(:filename) { 'q1/q1.txt' }
      it 'should download a file' do
        expect(response.body).to eq 'q1 content'
      end
    end
    context 'when a file does not exist' do
      let(:filename) { 'q3.txt' }
      it 'should download a file with a warning message' do
        expect(response.body).to eq I18n.t('student.submission.missing_file', file_name: filename)
      end
    end
  end
  describe '#update' do
    subject { put_as user, :update, params: { name: 'b', assignment_id: assignment.id, id: starter_file_group.id } }
    let(:starter_file_group) { create :starter_file_group_with_entries, assignment: assignment, name: 'a' }
    it_behaves_like 'student and ta not permitted'
    it 'can update the name' do
      subject
      expect(starter_file_group.reload.name).to eq 'b'
    end
  end
  describe '#download_files' do
    subject { get_as user, :download_files, params: { assignment_id: assignment.id, id: starter_file_group.id } }
    let(:starter_file_group) { create :starter_file_group_with_entries, assignment: assignment, structure: {} }
    it_behaves_like 'student and ta not permitted'
    context 'when the starter file exists' do
      let(:starter_file_group) { create :starter_file_group_with_entries, assignment: assignment }
      it 'should send a zip file containing the correct content' do
        subject
        content = []
        Zip::InputStream.open(StringIO.new(response.body)) do |io|
          while (entry = io.get_next_entry)
            content << io.read.strip.force_encoding('utf-8') unless entry.name_is_directory?
          end
        end
        expect(content).to contain_exactly('q1 content', 'q2 content')
      end
    end
    context 'when the starter files do not exist' do
      it 'should send a zip file containing the correct content' do
        subject
        Zip::InputStream.open(StringIO.new(response.body)) do |io|
          expect(io.get_next_entry).to be_nil
        end
      end
    end
  end
  describe '#update_files' do
    let(:unzip) { true }
    let(:new_folders) { [] }
    let(:delete_folders) { [] }
    let(:delete_files) { [] }
    let(:new_files) { [] }
    let(:zipfile) { fixture_file_upload(File.join('/files', 'test_zip.zip'), 'application/zip') }
    let(:starter_file_group) { create :starter_file_group_with_entries, assignment: assignment }
    subject do
      put_as user, :update_files, params: { assignment_id: assignment.id,
                                            id: starter_file_group.id,
                                            unzip: unzip,
                                            new_folders: new_folders,
                                            delete_folders: delete_folders,
                                            delete_files: delete_files,
                                            new_files: new_files }
    end
    it_behaves_like 'student and ta not permitted'
    context 'uploading a zip file' do
      let(:new_files) { [zipfile] }
      let(:starter_file_group) { create :starter_file_group_with_entries, assignment: assignment, structure: {} }
      before { subject }
      context 'when unzip if false' do
        let(:unzip) { 'false' }
        it 'should upload the right files' do
          expect(starter_file_group.files_and_dirs).to contain_exactly('test_zip.zip')
        end
        it 'should create a new starter file entry' do
          expect(starter_file_group.starter_file_entries.pluck(:path)).to include('test_zip.zip')
        end
      end
      context 'when unzip if true' do
        it 'should upload the right files' do
          files = %w[test_zip test_zip/Shapes.java test_zip/zip_subdir test_zip/zip_subdir/TestShapes.java]
          expect(starter_file_group.files_and_dirs).to contain_exactly(*files)
        end
        it 'should create a new starter file entry' do
          expect(starter_file_group.starter_file_entries.pluck(:path)).to include('test_zip')
        end
      end
    end
    context 'uploading a folder' do
      let(:new_folders) { %w[new_folder q1/new_nested_folder] }
      before { subject }
      it 'should create a top level directory' do
        expect(starter_file_group.reload.files_and_dirs).to include('new_folder')
        expect(Dir.exist?(starter_file_group.path + 'new_folder')).to be true
      end
      it 'should create a new starter file entry' do
        expect(starter_file_group.starter_file_entries.pluck(:path)).to include('new_folder')
      end
      it 'should create a nested directory' do
        expect(starter_file_group.files_and_dirs).to include('q1/new_nested_folder')
        expect(Dir.exist?(starter_file_group.path + 'q1/new_nested_folder')).to be true
      end
    end
    context 'deleting a file' do
      let(:delete_files) { %w[q2.txt q1/q1.txt] }
      before { subject }
      it 'should delete a top level file' do
        expect(starter_file_group.reload.files_and_dirs).not_to include('q2.txt')
        expect(File.exist?(starter_file_group.path + 'q2.txt')).to be false
      end
      it 'should delete a nested file' do
        expect(starter_file_group.reload.files_and_dirs).not_to include('q1/q1.txt')
        expect(File.exist?(starter_file_group.path + 'q1/q1.txt')).to be false
      end
      it 'should delete a starter file entry for the top level file' do
        expect(starter_file_group.starter_file_entries.pluck(:path)).not_to include('q2.txt')
      end
      it 'should not delete a starter file entry for the nested file' do
        expect(starter_file_group.starter_file_entries.pluck(:path)).to include('q1')
      end
    end
    context 'deleting a folder' do
      let(:delete_folders) { %w[q1 q2/q2] }
      let(:structure) { { 'q1/': nil, 'q2/q2/': nil, 'q2/q2/q2.txt': 'content' } }
      let(:starter_file_group) { create :starter_file_group_with_entries, assignment: assignment, structure: structure }
      before { subject }
      it 'should delete a top level folder' do
        expect(starter_file_group.reload.files_and_dirs).not_to include('q1')
        expect(Dir.exist?(starter_file_group.path + 'q1')).to be false
      end
      it 'should delete a nested folder' do
        expect(starter_file_group.reload.files_and_dirs).not_to include('q2/q2')
        expect(Dir.exist?(starter_file_group.path + 'q2/q2')).to be false
      end
      it 'should delete a starter file entry for the top level file' do
        expect(starter_file_group.starter_file_entries.pluck(:path)).not_to include('q1')
      end
      it 'should not delete a starter file entry for the nested file' do
        expect(starter_file_group.starter_file_entries.pluck(:path)).to include('q2')
      end
    end
  end
end


text:
<?php

namespace Pheal\Exceptions;

/**
 * basic Pheal Exception, all Pheal exceptions should be derived from this
 */
class ConnectionException extends PhealException
{

}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Flightzilla\Model\Ticket\Source;

/**
 * Abstract for source-writer
 *
 * @author Hans-Peter Buniat <hpbuniat@googlemail.com>
 * @copyright 2012-2013 Hans-Peter Buniat <hpbuniat@googlemail.com>
 * @license http://opensource.org/licenses/BSD-3-Clause
 * @version Release: @package_version@
 * @link https://github.com/hpbuniat/flightzilla
 */
abstract class AbstractWriter {

    /**
     * The Ticket-Source
     *
     * @var \Flightzilla\Model\Ticket\AbstractSource
     */
    protected $_oSource;

    /**
     * The payload for the source
     *
     * @var string
     */
    protected $_aPayload;

    /**
     * Ticket-actions
     *
     * @var string
     */
    const TICKET_ASSIGN = 'assign';
    const TICKET_CONFIRM = 'confirm';
    const TICKET_RESOLVE = 'resolve';

    /**
     * Set the source, as the source knows the basic communication
     *
     * @param \Flightzilla\Model\Ticket\AbstractSource $oSource
     */
    public function __construct(\Flightzilla\Model\Ticket\AbstractSource $oSource) {
        $this->_oSource = $oSource;
    }

    /**
     * Get the payload-data
     *
     * @return array
     */
    abstract public function getPayload();

    /**
     * Set the initial testing-request
     *
     * @param  \Flightzilla\Model\Ticket\AbstractType $oTicket
     * @param  mixed $mPayload
     *
     * @return $this
     */
    abstract public function setTestingRequest(\Flightzilla\Model\Ticket\AbstractType $oTicket, $mPayload);

    /**
     * Re-test the ticket, after test was not successful
     *
     * @param  \Flightzilla\Model\Ticket\AbstractType $oTicket
     * @param  mixed $mPayload
     *
     * @return $this
     */
    abstract public function reTest(\Flightzilla\Model\Ticket\AbstractType $oTicket, $mPayload);

    /**
     * The ticket has been merged
     *
     * @param  \Flightzilla\Model\Ticket\AbstractType $oTicket
     * @param  mixed $mPayload
     *
     * @return $this
     */
    abstract public function setMerged(\Flightzilla\Model\Ticket\AbstractType $oTicket, $mPayload);

    /**
     * The ticket is now on the test-server
     *
     * @param  \Flightzilla\Model\Ticket\AbstractType $oTicket
     * @param  mixed $mPayload
     *
     * @return $this
     */
    abstract public function setStaged(\Flightzilla\Model\Ticket\AbstractType $oTicket, $mPayload);

    /**
     * The changes should be updated to the test-server
     *
     * @param  \Flightzilla\Model\Ticket\AbstractType $oTicket
     * @param  mixed $mPayload
     *
     * @return $this
     */
    abstract public function setUpdateTestserver(\Flightzilla\Model\Ticket\AbstractType $oTicket, $mPayload);

    /**
     * The db-changes of a ticket are now deployed
     *
     * @param  \Flightzilla\Model\Ticket\AbstractType $oTicket
     * @param  mixed $mPayload
     *
     * @return $this
     */
    abstract public function setDbChanged(\Flightzilla\Model\Ticket\AbstractType $oTicket, $mPayload);

    /**
     * Set a specific status
     *
     * @param  \Flightzilla\Model\Ticket\AbstractType $oTicket
     * @param  mixed $mPayload
     *
     * @return $this
     */
    abstract public function setStatus(\Flightzilla\Model\Ticket\AbstractType $oTicket, $mPayload);

    /**
     * Set the sprint of the ticket
     *
     * @param  \Flightzilla\Model\Ticket\AbstractType $oTicket
     * @param  mixed $mPayload
     *
     * @return $this
     */
    abstract public function setSprint(\Flightzilla\Model\Ticket\AbstractType $oTicket, $mPayload);

    /**
     * Set the status to resolved
     *
     * @param  \Flightzilla\Model\Ticket\AbstractType $oTicket
     * @param  mixed $mPayload
     *
     * @return $this
     */
    abstract public function setResolved(\Flightzilla\Model\Ticket\AbstractType $oTicket, $mPayload);

    /**
     * Set the status to assigned
     *
     * @param  \Flightzilla\Model\Ticket\AbstractType $oTicket
     * @param  mixed $mPayload
     *
     * @return $this
     */
    abstract public function setAssigned(\Flightzilla\Model\Ticket\AbstractType $oTicket, $mPayload);

    /**
     * Set the status to confirmed
     *
     * @param  \Flightzilla\Model\Ticket\AbstractType $oTicket
     * @param  mixed $mPayload
     *
     * @return $this
     */
    abstract public function setConfirmed(\Flightzilla\Model\Ticket\AbstractType $oTicket, $mPayload);

    /**
     * Set the estimation
     *
     * @param  \Flightzilla\Model\Ticket\AbstractType $oTicket
     * @param  mixed $mPayload
     *
     * @return $this
     */
    abstract public function setEstimation(\Flightzilla\Model\Ticket\AbstractType $oTicket, $mPayload);

    /**
     * Set the worked-hours
     *
     * @param  \Flightzilla\Model\Ticket\AbstractType $oTicket
     * @param  mixed $mPayload
     *
     * @return $this
     */
    abstract public function setWorked(\Flightzilla\Model\Ticket\AbstractType $oTicket, $mPayload);

    /**
     * Set a comment
     *
     * @param  \Flightzilla\Model\Ticket\AbstractType $oTicket
     * @param  mixed $mPayload
     *
     * @return $this
     */
    abstract public function setComment(\Flightzilla\Model\Ticket\AbstractType $oTicket, $mPayload);
}


text:
/*	$NetBSD: mvsocvar.h,v 1.8 2014/03/15 10:54:40 kiyohara Exp $	*/
/*
 * Copyright (c) 2007, 2010 KIYOHARA Takashi
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef _MVSOCVAR_H_
#define _MVSOCVAR_H_

#include <sys/bus.h>

struct mvsoc_softc {
        device_t sc_dev;

	bus_addr_t sc_addr;
	bus_space_tag_t sc_iot;
	bus_space_handle_t sc_ioh;
	bus_dma_tag_t sc_dmat;
};

typedef int (*mvsoc_irq_handler_t)(void *);

extern uint32_t mvPclk, mvSysclk, mvTclk;
extern vaddr_t mlmb_base;
extern int nwindow, nremap;
extern int gpp_npins, gpp_irqbase;
extern struct bus_space mvsoc_bs_tag;
extern struct arm32_bus_dma_tag mvsoc_bus_dma_tag;

#define read_mlmbreg(o)		(*(volatile uint32_t *)(mlmb_base + (o)))
#define write_mlmbreg(o, v)	(*(volatile uint32_t *)(mlmb_base + (o)) = (v))

void mvsoc_bootstrap(bus_addr_t);
uint16_t mvsoc_model(void);
uint8_t mvsoc_rev(void);
void *mvsoc_bridge_intr_establish(int, int, int (*)(void *), void *);

#include <dev/marvell/marvellvar.h>

enum mvsoc_tags {
	MVSOC_TAG_INTERNALREG  = MARVELL_TAG_MAX,

	ORION_TAG_PEX0_MEM,
	ORION_TAG_PEX0_IO,
	ORION_TAG_PEX1_MEM,
	ORION_TAG_PEX1_IO,
	ORION_TAG_PCI_MEM,
	ORION_TAG_PCI_IO,
	ORION_TAG_DEVICE_CS0,
	ORION_TAG_DEVICE_CS1,
	ORION_TAG_DEVICE_CS2,
	ORION_TAG_FLASH_CS,
	ORION_TAG_DEVICE_BOOTCS,
	ORION_TAG_CRYPT,

	KIRKWOOD_TAG_PEX_MEM,
	KIRKWOOD_TAG_PEX_IO,
	KIRKWOOD_TAG_PEX1_MEM,
	KIRKWOOD_TAG_PEX1_IO,
	KIRKWOOD_TAG_NAND,
	KIRKWOOD_TAG_SPI,
	KIRKWOOD_TAG_BOOTROM,
	KIRKWOOD_TAG_CRYPT,

	MV78XX0_TAG_DEVICE_CS0,
	MV78XX0_TAG_DEVICE_CS1,
	MV78XX0_TAG_DEVICE_CS2,
	MV78XX0_TAG_DEVICE_CS3,
	MV78XX0_TAG_DEVICE_BOOTCS,
	MV78XX0_TAG_SPI,
	MV78XX0_TAG_PEX0_MEM,
	MV78XX0_TAG_PEX01_MEM,
	MV78XX0_TAG_PEX02_MEM,
	MV78XX0_TAG_PEX03_MEM,
	MV78XX0_TAG_PEX0_IO,
	MV78XX0_TAG_PEX01_IO,
	MV78XX0_TAG_PEX02_IO,
	MV78XX0_TAG_PEX03_IO,
	MV78XX0_TAG_PEX1_MEM,
	MV78XX0_TAG_PEX11_MEM,
	MV78XX0_TAG_PEX12_MEM,
	MV78XX0_TAG_PEX13_MEM,
	MV78XX0_TAG_PEX1_IO,
	MV78XX0_TAG_PEX11_IO,
	MV78XX0_TAG_PEX12_IO,
	MV78XX0_TAG_PEX13_IO,
	MV78XX0_TAG_CRYPT,

	ARMADAXP_TAG_PEX00_MEM,
	ARMADAXP_TAG_PEX00_IO,
	ARMADAXP_TAG_PEX01_MEM,
	ARMADAXP_TAG_PEX01_IO,
	ARMADAXP_TAG_PEX02_MEM,
	ARMADAXP_TAG_PEX02_IO,
	ARMADAXP_TAG_PEX03_MEM,
	ARMADAXP_TAG_PEX03_IO,
	ARMADAXP_TAG_PEX2_MEM,
	ARMADAXP_TAG_PEX2_IO,
	ARMADAXP_TAG_PEX3_MEM,
	ARMADAXP_TAG_PEX3_IO,
};
int mvsoc_target(int, uint32_t *, uint32_t *, uint32_t *, uint32_t *);

extern int (*mvsoc_clkgating)(struct marvell_attach_args *);

void orion_intr_bootstrap(void);
void orion_getclks(bus_addr_t);

void kirkwood_intr_bootstrap(void);
void kirkwood_getclks(bus_addr_t);
int kirkwood_clkgating(struct marvell_attach_args *);

void mv78xx0_intr_bootstrap(void);
void mv78xx0_getclks(bus_addr_t);

void armadaxp_intr_bootstrap(bus_addr_t);
void armadaxp_getclks(void);
void armada370_getclks(void);
int armadaxp_clkgating(struct marvell_attach_args *);

#endif	/* _MVSOCVAR_H_ */


text:
<?php

defined("_VALID_ACCESS") || die('Direct access forbidden');

class Utils_TabbedBrowserInstall extends ModuleInstall {
	public function install() {
		Base_ThemeCommon::install_default_theme(Utils_TabbedBrowserInstall::module_name());
		return true;
	}

	public function uninstall() {
		Base_ThemeCommon::uninstall_default_theme(Utils_TabbedBrowserInstall::module_name());
		return true;
	}

	public function version() {
		return array('1.0');
	}
	public function requires($v) {
		return array(array('name'=>Base_ThemeInstall::module_name(),'version'=>0));
	}
}

?>


text:
@protocol TNDRTitleButtonDelegate <NSObject>
- (void)didDragInsideTitleButton;
- (void)didTouchDownInsideTitleButton;
- (void)didTouchUpInsideTitleButton;
@end


text:
/**
 * Created by brendan on 4/18/15.
 */

hyperApp.controller('loginCtrl', function ($scope, loginService) {

    $scope.login = function (user) {
        loginService.login(user, $scope);
    };

});
hyperApp.factory('loginService', function ($http, $location, $window, $timeout, sessionService, GApi, crypto) {

  return {

    login: function (user, scope) {
        var base_url = $window.location.host;
        var api_url = '';
        if (base_url.indexOf('localhost') > -1) {
            api_url = 'http://localhost:8080/api/login';
        }
        else {
            api_url = 'https://centralparkedu.appspot.com/api/login';
        }
        var s_user = {
            'email': user.email,
            'password': crypto.hash(user.password)
        };
        var $promise = $http.post(api_url, s_user);
        $promise.then(function (msg) {
        console.log(msg.data);
        user.problem = msg;
        if (msg.data.code == 200) {
          sessionService.set('token', msg.data.response.token);
          sessionService.set('user_id', msg.data.response.user_id);
          $location.path('/officers');
        }
        else if (msg.data.code >= 400) {
          sessionService.destroy('token');
          sessionService.destroy('user_id');
        }
        else {
          sessionService.destroy('token');
          sessionService.destroy('user_id');
        }
      }, function error(msg) {
        console.error(msg.message);
        scope.error = msg.message;
        sessionService.destroy('token');
        sessionService.destroy('user_id');
      });
    },
    isLogged: function () {
      if (sessionService.get('token')) {
        return true;
      }
    }
  };
});


text:
Controllers.controller("UserListCtrl", ["$scope", function ($scope)
{
    $scope.$on("$destroy", function () {
        delete $scope.users;
        delete $scope.selectedUser;
    });

    $scope.selectedUser = null;
}]);


text:
import scala.tools.nsc.doc.model._
import scala.tools.partest.ScaladocModelTest

object Test extends ScaladocModelTest {

  override def resourceFile = "t4360.scala"

  // no need for special settings
  def scaladocSettings = ""

  def testModel(rootPackage: Package) = {
    // get the quick access implicit defs in scope (_package(s), _class(es), _trait(s), object(s) _method(s), _value(s))
    import access._

    // just need to check the member exists, access methods will throw an error if there's a problem
    val base = rootPackage._package("scala")._package("test")._package("scaladoc")._package("prefix")

    val TEST = base._package("pack1")._package("c")._class("TEST")
    val fooCA = TEST._method("fooCA")
    val fooCB = TEST._method("fooCB")
    val fooCS = TEST._method("fooCS")
    val fooCL = TEST._method("fooCL")
    val fooPA = TEST._method("fooPA")
    val fooPB = TEST._method("fooPB")
    val fooPC = TEST._method("fooPC")

    val expected = List(
      (fooCA, "Z", 1),
      (fooCB, "B.Z", 1),
      (fooCS, "pack2.Z.Z", 1),
      (fooCL, "L.Z", 1),
      (fooPA, "a.C", 1),
      (fooPB, "b.C", 1),
      (fooPC, "C", 1)
    )

    for ((method, name, refs) <- expected) {
      assert(method.valueParams(0)(0).resultType.name == name,
             method.valueParams(0)(0).resultType.name + " == " + name + " (in " + method.qualifiedName + ")")
      assert(method.valueParams(0)(0).resultType.refEntity.size == refs,
             method.valueParams(0)(0).resultType.refEntity.size.toString + " == " + refs + " (in " + method.qualifiedName + ")")
    }

    val A = base._package("pack1")._package("c")._class("A")
    assert(A.linearizationTypes(0).name == "pack1.A",   A.linearizationTypes(0).name + " == pack1.A")
    assert(A.linearizationTypes(0).refEntity.size == 1, A.linearizationTypes(0).refEntity.size.toString + " == 1")
  }
}


text:
package FCS::Client;
use strict;
use warnings;
use Exporter qw(import);
use LWP::UserAgent;
use JSON;

sub new {
    my ($class, %args) = @_;
    return bless {%args}, $class;
}

sub copy {
    my ($self, $fromDir, $toDir, $file) = @_;
    return copyFile($self->{url}, $fromDir, $toDir, $file, 0);
}

sub move {
    my ($self, $fromDir, $toDir, $file) = @_;
    return copyFile($self->{url}, $fromDir, $toDir, $file, 1);
}

sub status {
    my ($self, $id) = @_;

    my $request = HTTP::Request->new(GET => $self->{url} . "/status/" . $id);
    $request->header("content-type", "application/json");
    return request($request);
}

sub request {
    my ($request) = @_;
    my $agent = LWP::UserAgent->new;
    my $response = $agent->request($request);
    if ($response->is_success) {
        my $json = JSON->new->allow_nonref->decode($response->decoded_content);
        return $json;
    } else {
        print $response->code, "\n";
        print $response->message, "\n";
        die("request failed");
    }
}

sub copyFile {
    my ($url, $fromDir, $toDir, $file, $move) = @_;

    my $fullFrom = $fromDir . "/" . $file;
    my $fullTo = $toDir . "/" . $file;
    my $doMove = $move ? "true" : "false";
    my $data = '{"source": "' . $fullFrom . '", "dest": "' . $fullTo . '", "move": ' . $doMove . '}';

    my $request = HTTP::Request->new(POST => $url . "/copy");
    $request->header("content-type", "application/json");
    $request->content($data);
    return request($request);
}

1;


text:
package org.flywaydb.maven;

import org.flywaydb.core.Flyway;
import org.apache.maven.project.MavenProject;
import org.h2.Driver;
import org.junit.Before;
import org.junit.Test;

import java.io.File;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;

/**
 * Test for AbstractFlywayMojo.
 */
public class AbstractFlywayMojoSmallTest {

    public static final String FLYWAY_MY_PROPERTY = "flyway.myProperty";

    @Before
    public void cleanCustomSystemProperty(){
        System.clearProperty(FLYWAY_MY_PROPERTY);
    }

    @Test
    public void execute() throws Exception {
        AbstractFlywayMojo mojo = new AbstractFlywayMojo() {
            @Override
            protected void doExecute(Flyway flyway) throws Exception {
                assertEquals(2, flyway.getSchemas().length);
                assertEquals("first", flyway.getSchemas()[0]);
                assertEquals("second", flyway.getSchemas()[1]);
            }
        };

        mojo.driver = Driver.class.getName();
        mojo.url = "jdbc:h2:mem:dummy";
        mojo.user = "sa";
        mojo.mavenProject = new MavenProject();
        mojo.mavenProject.setBasedir(new File("."));
        mojo.mavenProject.getProperties().setProperty("flyway.schemas", "first,second");
        mojo.execute();
    }

    @Test
    public void skipExecute() throws Exception {
        AbstractFlywayMojo mojo = new AbstractFlywayMojo() {
            @Override
            protected void doExecute(Flyway flyway) throws Exception {
                assertNull(flyway.getDataSource());
            }
        };

        mojo.skip = true;
        mojo.url = "jdbc:h2:mem:dummy";
        mojo.mavenProject = new MavenProject();
        mojo.execute();
    }

    @Test
    public void shouldHaveABooleanPropertyWithTrue() throws Exception {
        System.setProperty(FLYWAY_MY_PROPERTY, "true");
        AbstractFlywayMojo mojo = new AbstractFlywayMojo() {
            @Override
            protected void doExecute(Flyway flyway) throws Exception {
            }
        };

        boolean booleanProperty = mojo.getBooleanProperty(FLYWAY_MY_PROPERTY, false);
        assertEquals(true, booleanProperty);
    }

    @Test
    public void shouldHaveTheMavenPropertyWithFalse() throws Exception {
        AbstractFlywayMojo mojo = new AbstractFlywayMojo() {
            @Override
            protected void doExecute(Flyway flyway) throws Exception {
            }
        };

        boolean booleanProperty = mojo.getBooleanProperty(FLYWAY_MY_PROPERTY, false);
        assertEquals(false, booleanProperty);
    }
}


text:
using System.Security.Cryptography.X509Certificates;
using Autofac;

namespace EShopWorld.Tools.Commands.AzScan
{
    /// <summary>
    /// AutoFac module fo AzScan family
    /// </summary>
    // ReSharper disable once UnusedMember.Global
    public class AzScanModule : Module
    {
        /// <inheritdoc />
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterType<AzScanSqlCommand>();
            builder.RegisterType<AzScanCosmosDbCommand>();
            builder.RegisterType<AzScanRedisCommand>();
            builder.RegisterType<AzScanServiceBusCommand>();
            builder.RegisterType<AzScanAppInsightsCommand>();
            builder.RegisterType<AzScanDNSCommand>();
            builder.RegisterType<AzScanKustoCommand>();
            builder.RegisterType<AzScanKeyVaultManager>();
            builder.RegisterType<AzScanEnvironmentInfoCommand>();
            builder.RegisterType<ServiceFabricDiscoveryFactory>();
            builder.Register(c =>
            {
                var _x509Store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
                _x509Store.Open(OpenFlags.ReadWrite);

                return _x509Store;
            }).SingleInstance();
        }
    }
}


text:
package goa_test

import (
	"net/http"

	"github.com/goadesign/goa"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

var _ = Describe("PathSelectVersionFunc", func() {
	var pattern, zeroVersion string
	var request *http.Request

	var fn goa.SelectVersionFunc
	var version string

	JustBeforeEach(func() {
		fn = goa.PathSelectVersionFunc(pattern, zeroVersion)
		version = fn(request)
	})

	Context("using the default settings", func() {
		BeforeEach(func() {
			pattern = "/:version/"
			zeroVersion = "api"
		})

		Context("and a versioned request", func() {
			BeforeEach(func() {
				var err error
				request, err = http.NewRequest("GET", "/v1/foo", nil)
				Ω(err).ShouldNot(HaveOccurred())
			})

			It("routes to the versioned controller", func() {
				Ω(version).Should(Equal("v1"))
			})
		})

		Context("and an unversioned request", func() {
			BeforeEach(func() {
				var err error
				request, err = http.NewRequest("GET", "/api/foo", nil)
				Ω(err).ShouldNot(HaveOccurred())
			})

			It("routes to the unversioned controller", func() {
				Ω(version).Should(Equal(""))
			})
		})
	})

})


text:
Ext.define('KitchenSink.view.grid.XmlGrid', {
    extend: 'Ext.grid.Panel',
    requires: [
        'Ext.grid.column.Column',
        'KitchenSink.store.Books'
    ],
    xtype: 'xml-grid',
    store: {
        type: 'books'
    },
    stateful: true,
    collapsible: true,
    multiSelect: true,
    stateId: 'stateXmlGrid',
    height: 350,
    title: 'XML Grid',
    viewConfig: {
        enableTextSelection: true
    },
    //<example>
    exampleDescription: [
        '
This example shows how to create a grid from XML data.
',
        '
The grid is stateful so you can move or hide columns, reload the page,',
        'and come back to the grid in the same state you left it in.
',
        '
The cells are selectable due to use of the enableTextSelection ',
        'option.
'
    ],
    otherContent: [{
        type: 'Store',
        path: 'app/store/Books.js'
    },{
        type: 'Model',
        path: 'app/model/grid/Book.js'
    }],
    themes: {
        classic: {
            width: 600,
            percentChangeColumnWidth: 75,
            lastUpdatedColumnWidth: 85,
            green: 'green',
            red: 'red'
        },
        neptune: {
            width: 650,
            percentChangeColumnWidth: 100,
            lastUpdatedColumnWidth: 115,
            green: '#73b51e',
            red: '#cf4c35'
        }
    },
    //</example>

    initComponent: function () {
        var me = this;

        me.width = this.themeInfo.width;
        me.columns = [
            {text: "Author", flex: 1, dataIndex: 'Author'},
            {text: "Title", width: 180, dataIndex: 'Title'},
            {text: "Manufacturer", width: 115, dataIndex: 'Manufacturer'},
            {text: "Product Group", width: 100, dataIndex: 'ProductGroup'}
        ];

        me.callParent();

        this.on('afterlayout', this.loadStore, this, {
            delay: 1,
            single: true
        });
    },

    loadStore: function() {
        this.getStore().load();
    }
});


text:
angular.module('app', ['google.plus.auth'])
	.config(['googlePlusAuthProvider', function (googlePlusAuthProvider) {
		googlePlusAuthProvider.config({
			clientId: 'your client id'
		});
	}])
	.controller('AppCtrl', [
		'$scope',
		'googlePlusAuth',
		'googlePlusUser',
		function ($scope, googlePlusAuth, googlePlusUser) {

			$scope.user = googlePlusUser;

			$scope.login = function () {
				googlePlusAuth.login();
			};

			$scope.logout = function () {
				googlePlusAuth.logout();
			};
		}
	]);


text:
package com.github.mygreen.supercsv.builder;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Objects;

import org.supercsv.exception.SuperCsvReflectionException;
import org.supercsv.util.CsvContext;

import com.github.mygreen.supercsv.validation.CsvBindingErrors;
import com.github.mygreen.supercsv.validation.ValidationContext;

/**
 *
 *
 * @since 2.0
 * @author T.TSUCHIE
 *
 */
public class CallbackMethod implements Comparable<CallbackMethod> {

    protected final Method method;

    public CallbackMethod(final Method method) {
        Objects.requireNonNull(method);

        method.setAccessible(true);
        this.method = method;

    }

    /**
     * メソッドの実行
     * @param record Beanのオブジェクト
     * @param csvContext 現在のCSVのレコード情報
     * @param bindingErrors エラー情報。
     * @param beanMapping マッピング情報
     * @throws SuperCsvReflectionException メソッドの実行に失敗した場合。
     */
    public void invoke(final Object record, final CsvContext csvContext, final CsvBindingErrors bindingErrors,
            final BeanMapping<?> beanMapping) {

        // 引数の組み立て
        final Class<?>[] paramTypes = method.getParameterTypes();
        final Object[] paramValues =  new Object[paramTypes.length];

        for(int i=0; i < paramTypes.length; i++) {

            if(CsvContext.class.isAssignableFrom(paramTypes[i])) {
                paramValues[i] = csvContext;

            } else if(CsvBindingErrors.class.isAssignableFrom(paramTypes[i])) {
                paramValues[i] = bindingErrors;

            } else if(paramTypes[i].isArray() && Class.class.isAssignableFrom(paramTypes[i].getComponentType())) {
                paramValues[i] = beanMapping.getGroups();

            } else if(ValidationContext.class.isAssignableFrom(paramTypes[i])) {
                paramValues[i] = new ValidationContext<>(csvContext, beanMapping);

            } else if(beanMapping.getType().isAssignableFrom(paramTypes[i])) {
                paramValues[i] = record;

            } else {
                paramValues[i] = null;
            }

        }

        execute(record, paramValues);

    }

    protected void execute(final Object record, final Object[] paramValues) {
        try {
            method.invoke(record, paramValues);

        } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
            Throwable t = e.getCause() == null ? e : e.getCause();
            throw new SuperCsvReflectionException(
                    String.format("Fail execute method '%s#%s'.", record.getClass().getName(), method.getName()),
                    t);
        }

    }

    /**
     * メソッド名の昇順
     */
    @Override
    public int compareTo(final CallbackMethod o) {

        final String name1 = method.getDeclaringClass().getName() + "#" + method.getName();
        final String name2 = o.method.getDeclaringClass().getName() + "#" + o.method.getName();

        return name1.compareTo(name2);

    }

}


text:
from __future__ import unicode_literals

from common import FieldExam
from marrow.mongo.field import Regex

class RegexField(FieldExam):
	__field__ = Regex


text:
package org.uma.jmetal.problem.multiobjective.dtlz;

import org.uma.jmetal.problem.doubleproblem.impl.AbstractDoubleProblem;
import org.uma.jmetal.solution.doublesolution.DoubleSolution;
import org.uma.jmetal.util.JMetalException;

import java.util.ArrayList;
import java.util.List;

/**
 * Class representing problem DTLZ6
 */
@SuppressWarnings("serial")
public class DTLZ6 extends AbstractDoubleProblem {
  /**
   * Creates a default DTLZ6 problem (12 variables and 3 objectives)
   */
  public DTLZ6() {
    this(12, 3);
  }

  /**
   * Creates a DTLZ6 problem instance
   *
   * @param numberOfVariables  Number of variables
   * @param numberOfObjectives Number of objective functions
   */
  public DTLZ6(Integer numberOfVariables, Integer numberOfObjectives) throws JMetalException {
    setNumberOfVariables(numberOfVariables);
    setNumberOfObjectives(numberOfObjectives);
    setName("DTLZ6");

    List<Double> lowerLimit = new ArrayList<>(getNumberOfVariables()) ;
    List<Double> upperLimit = new ArrayList<>(getNumberOfVariables()) ;

    for (int i = 0; i < getNumberOfVariables(); i++) {
      lowerLimit.add(0.0);
      upperLimit.add(1.0);
    }

    setVariableBounds(lowerLimit, upperLimit);
  }

  /** Evaluate() method */
  public void evaluate(DoubleSolution solution) {
    int numberOfVariables = getNumberOfVariables();
    int numberOfObjectives = getNumberOfObjectives() ;
    double[] theta = new double[numberOfObjectives - 1];

    double[] f = new double[numberOfObjectives];
    double[] x = new double[numberOfVariables] ;

    int k = getNumberOfVariables() - getNumberOfObjectives() + 1;

    for (int i = 0; i < numberOfVariables; i++) {
      x[i] = solution.getVariable(i) ;
    }

    double g = 0.0;
    for (int i = numberOfVariables - k; i < numberOfVariables; i++) {
      g += java.lang.Math.pow(x[i], 0.1);
    }

    double t = java.lang.Math.PI / (4.0 * (1.0 + g));
    theta[0] = x[0] * java.lang.Math.PI / 2;
    for (int i = 1; i < (numberOfObjectives - 1); i++) {
      theta[i] = t * (1.0 + 2.0 * g * x[i]);
    }

    for (int i = 0; i < numberOfObjectives; i++) {
      f[i] = 1.0 + g;
    }

    for (int i = 0; i < numberOfObjectives; i++) {
      for (int j = 0; j < numberOfObjectives - (i + 1); j++) {
        f[i] *= java.lang.Math.cos(theta[j]);
      }
      if (i != 0) {
        int aux = numberOfObjectives - (i + 1);
        f[i] *= java.lang.Math.sin(theta[aux]);
      }
    }

    for (int i = 0; i < numberOfObjectives; i++) {
      solution.setObjective(i, f[i]);
    }
  }
}


text:
- Beijing is increasingly focused on environmental issues — a marked shift from its traditional growth-at-all-costs philosophy.

- China's most famous tree is in danger of being 'loved to death'.

- HUANGSHAN, China — On one of the world's most beautiful mountains stands one of China's most famous trees.

- A specimen of rugged, flat-crowned evergreen that may be 1,000 years old, the Greeting Pine — or Yingkesong in Mandarin — overlooks
a dramatic landscape of granite peaks and mist-shrouded valleys of Huangshan.

- When he's on duty, every two hours, every day of the year, Hu has to inspect the tree and log details about its condition and the local
environment. He also guards the tree from squirrels and monkeys that could damage its branches, and he's there to support it through
snowstorms and typhoons.

- As income levels rise, ever-increasing numbers of Chinese are starting to travel domestically. Tens of millions of tourists now flock to
China's national parks every year.

- Air pollution in major cities like Beijing may be the more visible indications of China's struggle to contain the damage wrought by its rapid industrialization,
but scenic areas like Huangshan are increasingly on the front lines in the battle to protect the country's natural beauty and environment.

- In October, President Xi Jinping gave an annual speech to the National People's Congress — roughly analogous to America's State of the Union address.

- Over three hours, Xi mentioned the environment or related terms 89 times, according to an analysis by Bloomberg Intelligence, while mentioning the economy only 70 times.

- China must "ensure that the ecology and environment are fundamentally improved by 2035, and that our goal of building a beautiful China
is basically achieved," Xi told the People's Congress.


text:
<?php
  // Nick Martinez - Final Project
  require_once('functions.php');
  secureSession();

  $_SESSION = array();
  setcookie(session_name(), '', time() - 42000, $params["path"],
    $params["domain"], $params["secure"], $params["httponly"]);
  session_destroy();

  header('Location:../index.php');
?>


text:
package pl.mk5.gdx.fireapp.e2e.tests;

import com.badlogic.gdx.graphics.g2d.Batch;

import pl.mk5.gdx.fireapp.GdxFIRDatabase;
import pl.mk5.gdx.fireapp.e2e.runner.E2ETest;
import pl.mk5.gdx.fireapp.functional.Consumer;
import pl.mk5.gdx.fireapp.functional.Function;

public class DatabaseTransactionDefaultStringValueTest extends E2ETest {

    @Override
    public void action() {
        final String reference = "/test-trans";

        GdxFIRDatabase.promise()
                .then(GdxFIRDatabase.inst().inReference(reference).removeValue())
                .then(GdxFIRDatabase.inst().inReference(reference)
                        .transaction(String.class, new Function<String, String>() {
                            @Override
                            public String apply(String str) {
                                return str + "abc";
                            }
                        }))
                .then(GdxFIRDatabase.inst().inReference(reference).readValue(String.class))
                .then(new Consumer<String>() {
                    @Override
                    public void accept(String i) {
                        if (i.equals("abc")) {
                            success();
                        }
                    }
                });
    }

    @Override
    public void draw(Batch batch) {
    }

    @Override
    public void update(float dt) {

    }

    @Override
    public void dispose() {
    }
}


text:
int main(int argc,char *args[]) {
	if(argc < 2) {
		std::cout << "> missing arguments: source | destination" << std::endl;
	} else {
		CDBOConv *dboFile = new CDBOConv(std::string(args[1]));
		if(!dboFile->good()) {
			std::cout << "> loading: " << args[1] << " could not be found" << std::endl;
		} else {
			dboFile->create();
			dboFile->saveto(std::string(args[2])); //Warning! Deletes file loaded in memory!
		}

		dboFile->clean();
	}
	std::cin.get();

	return 0;
}


text:
---
layout: post
category: JUnit
title: JUnit4 使用进阶一
tags: ['Junit4']
author: 唐 治
email: tangzhi@asiainfo-linkage.com
description: JUnit4 使用进阶一,对JUnit4的下载安装、基本测试方法及运行,配合实例进行基础介绍。帮助读者看完之后,就可以将JUnit4运用到单元测试中去。
---

目录

简介

下载安装

一个简单的模版

运行测试

JUnit4的核心之一是断言

小结

### 一、简介

JUnit是一个Java语言的单元测试框架。它由Kent Beck和Erich Gamma建立,逐渐成为源于Kent Beck的sUnit的xUnit家族中为最成功的一个。来自JUnit的体验对测试驱动开发是很重要的,所以一些 JUnit知识经常 和测试驱动开发的讨论融合在一起。可以参考Kent Beck的 [《Test-Driven Development: By Example》][0]一书(有中文版和影印版)。

本文,对JUnit4的下载安装、基本测试方法及运行,配合实例进行基础介绍。帮助读者看完之后,就可以将JUnit4运用到单元测试中去。而JUnit4的更多功能可以参考后续的[JUnit4使用进阶二][1]。

[0]: http://book.douban.com/subject/1771049/

### 二、下载安装

JUnit当前版本是4.11,如果,你的工程是使用Maven进行管理构建,那么只需要在工程的pom.xml文件中添加如下依赖信息:

	<dependency>
  		<groupId>junit</groupId>
  		<artifactId>junit</artifactId>
  		<version>4.11</version>
  		<scope>test</scope>
	</dependency>

否则,在你的测试classpath中放置下面两个jar:`junit.jar`和`hamcrest-core.jar`,这两个jar可以在[这里](http://search.maven.org/)找到并下载。

### 三、一个简单的模版

	package com.example.foo;

	import static org.junit.Assert.assertEquals;

	import org.junit.Test;
	import org.junit.Ignore;
	import org.junit.runner.RunWith;
	import org.junit.runners.JUnit4;

	/**
	 * Tests for {@link Foo}.
	 *
	 * @author user@example.com (John Doe)
	 */
	@RunWith(JUnit4.class)
	public class FooTest {

    	@Test
    	public void thisAlwaysPasses() {
    	}

    	@Test
    	@Ignore
    	public void thisIsIgnored() {
    	}
	}

这个模版是不是很简单!

* 需要测试的方法,只需要通过`@Test`标注出来就可以了。

* 测试类只需要添加`@RunWith`注释,不再需要继承`junit.framework.TestCase`这个父类了。

当然了,JUnit4还提供了很多特色功能,后面我们会一一介绍。

### 四、运行测试

* 在命令行,对写好的测试类,进行测试很简单,只需要下面一个命令就ok了:

		java -cp .:/usr/share/java/junit.jar org.junit.runner.JUnitCore [test class name]

* 在IDE里面进行测试就更简单了,`Netbeans`, `Eclipse` 和 `IntelliJ Idea`都内置了图形化的测试运行器。

测试类如何运行,是由`@RunWith`注释来决定。JUnit4当前版本的默认基本测试方式是`JUnit4.class`。除此之外,还有一些其他特殊的,我们将在[JUnit4 使用进阶四][3]中进行介绍。

### 五、JUnit4的核心之一是断言

JUnit4框架主要是通过断言来判断运行结果正确与否,针对Java的原生类型(long,boolean,float...)或者Objects或者数组,JUnit都提供了对应的断言方法。

下面,我们先来看个例子:

    import static org.hamcrest.CoreMatchers.allOf;
    import static org.hamcrest.CoreMatchers.anyOf;
    import static org.hamcrest.CoreMatchers.equalTo;
    import static org.hamcrest.CoreMatchers.not;
    import static org.hamcrest.CoreMatchers.sameInstance;
    import static org.hamcrest.CoreMatchers.startsWith;
    import static org.junit.Assert.assertThat;
    import static org.junit.matchers.JUnitMatchers.both;
    import static org.junit.matchers.JUnitMatchers.containsString;
    import static org.junit.matchers.JUnitMatchers.everyItem;
    import static org.junit.matchers.JUnitMatchers.hasItems;

    import java.util.Arrays;

    import org.hamcrest.core.CombinableMatcher;
    import org.junit.Test;

    public class AssertTests {
      @Test
      public void testAssertArrayEquals() {
        byte[] expected = "trial".getBytes();
        byte[] actual = "trial".getBytes();
        org.junit.Assert.assertArrayEquals("failure - byte arrays not same", expected, actual);
      }

      @Test
      public void testAssertEquals() {
        org.junit.Assert.assertEquals("failure - strings not same", 5l, 5l);
      }

      @Test
      public void testAssertFalse() {
        org.junit.Assert.assertFalse("failure - should be false", false);
      }

      @Test
      public void testAssertNotNull() {
        org.junit.Assert.assertNotNull("should not be null", new Object());
      }

      @Test
      public void testAssertNotSame() {
        org.junit.Assert.assertNotSame("should not be same Object", new Object(), new Object());
      }

      @Test
      public void testAssertNull() {
        org.junit.Assert.assertNull("should be null", null);
      }

      @Test
      public void testAssertSame() {
        Integer aNumber = Integer.valueOf(768);
        org.junit.Assert.assertSame("should be same", aNumber, aNumber);
      }

      // JUnit Matchers assertThat
      @Test
      public void testAssertThatBothContainsString() {
        org.junit.Assert.assertThat("albumen", both(containsString("a")).and(containsString("b")));
      }

      @Test
      public void testAssertThathasItemsContainsString() {
        org.junit.Assert.assertThat(Arrays.asList("one", "two", "three"), hasItems("one", "three"));
      }

      @Test
      public void testAssertThatEveryItemContainsString() {
        org.junit.Assert.assertThat(Arrays.asList(new String[] { "fun", "ban", "net" }), everyItem(containsString("n")));
      }

      // Core Hamcrest Matchers with assertThat
      @Test
      public void testAssertThatHamcrestCoreMatchers() {
        assertThat("good", allOf(equalTo("good"), startsWith("good")));
        assertThat("good", not(allOf(equalTo("bad"), equalTo("good"))));
        assertThat("good", anyOf(equalTo("bad"), equalTo("good")));
        assertThat(7, not(CombinableMatcher.<Integer> either(equalTo(3)).or(equalTo(4))));
        assertThat(new Object(), not(sameInstance(new Object())));
      }
    }

**注意:**

1. `assertEquals`和`assertSame` 的区别在于,前者是调用`期待值`的`equals`方法来判断`真实值`(`expected.equals(actual)`),而后者是判断`期待值`和`真实值`是否是同一个对象(`expected == actual`)。
2. 例子中,这样调用`org.junit.Assert.assertEquals("failure - strings not same", 5l, 5l);`是不是觉得有点累,没关系,我们可以通过JDK1.5中的静态导入(`import static`)来简化这一切,看下面的代码。

简化后的例子:

    package tangzhi.mytest;

    import static org.hamcrest.CoreMatchers.allOf;
    import static org.hamcrest.CoreMatchers.anyOf;
    import static org.hamcrest.CoreMatchers.equalTo;
    import static org.hamcrest.CoreMatchers.not;
    import static org.hamcrest.CoreMatchers.sameInstance;
    import static org.hamcrest.CoreMatchers.startsWith;
    import static org.junit.Assert.assertThat;
    import static org.junit.matchers.JUnitMatchers.both;
    import static org.junit.matchers.JUnitMatchers.containsString;
    import static org.junit.matchers.JUnitMatchers.everyItem;
    import static org.junit.matchers.JUnitMatchers.hasItems;

    import static org.junit.Assert.*;

    import java.util.Arrays;

    import org.hamcrest.core.CombinableMatcher;
    import org.junit.Test;

    public class AppTest {
      @Test
      public void testAssertArrayEquals() {
        byte[] expected = "trial".getBytes();
        byte[] actual = "trial".getBytes();
        assertArrayEquals("failure - byte arrays not same", expected, actual);
      }

      @Test
      public void testAssertEquals() {
        assertEquals("failure - strings not same", 5l, 5l);
      }

      @Test
      public void testAssertFalse() {
        assertFalse("failure - should be false", false);
      }

      @Test
      public void testAssertNotNull() {
        assertNotNull("should not be null", new Object());
      }

      @Test
      public void testAssertNotSame() {
        assertNotSame("should not be same Object", new Object(), new Object());
      }

      @Test
      public void testAssertNull() {
        assertNull("should be null", null);
      }

      @Test
      public void testAssertSame() {
        Integer aNumber = Integer.valueOf(768);
        assertSame("should be same", aNumber, aNumber);
      }

      // JUnit Matchers assertThat
      @Test
      public void testAssertThatBothContainsString() {
        assertThat("albumen", both(containsString("a")).and(containsString("b")));
      }

      @Test
      public void testAssertThathasItemsContainsString() {
        assertThat(Arrays.asList("one", "two", "three"), hasItems("one", "three"));
      }

      @Test
      public void testAssertThatEveryItemContainsString() {
        assertThat(Arrays.asList(new String[] { "fun", "ban", "net" }), everyItem(containsString("n")));
      }

      // Core Hamcrest Matchers with assertThat
      @Test
      public void testAssertThatHamcrestCoreMatchers() {
        assertThat("good", allOf(equalTo("good"), startsWith("good")));
        assertThat("good", not(allOf(equalTo("bad"), equalTo("good"))));
        assertThat("good", anyOf(equalTo("bad"), equalTo("good")));
        assertThat(7, not(CombinableMatcher.<Integer> either(equalTo(3)).or(equalTo(4))));
        assertThat(new Object(), not(sameInstance(new Object())));
      }
    }

在上面的代码中,我们静态导入了`import static org.junit.Assert.*;`后,在测试类中就可以直接使用`assertEquals`这些方法了。是不是很方便!

**常用的断言方法有:**

    assertTrue([message ,] condition);
    assertFalse([message ,] condition);
    assertEquals([message ,] expected, actual);
    assertNotEquals([message ,] first, second);
    assertArrayEquals([message ,] expecteds, actuals);
    assertNotNull([message ,] object);
    assertNull([message ,] object);
    assertSame([message ,] expected, actual);
    assertNotSame([message ,] unexpected, actual);
    assertThat([message ,] actual, matcher);

**从上面的列表可以看出:**

1. 大部分断言方法的参数顺序都是:`[Message] 期待值  真实值`,第一个参数是个可选字符串,出错时的描述信息。第二个参数是期待值,第三个参数是真实值。

1. 只有一个断言方法`assertThat`的参数顺序例外:可选的出错提示信息、真实值和一个`Matcher`对象。它参数中的期待值与真实值的顺序,与其他断言方法的参数顺序正好相反。

这个`assertThat`方法是断言中的神器,后面我们会在[进阶三][2]介绍!敬请期待吧!

### 六、小结

前面我们介绍了JUnit4的基本知识。至此,你已经可以使用JUnit4进行代码测试了。如果你想知道更多信息,可以继续看看[JUnit 使用进阶二][1]。

[1]: junit-usage-2.html
[2]: junit-usage-3.html
[3]: junit-usage-4.html


text:
package lambda;

import java.util.*;
import java.util.concurrent.Callable;
import java.util.function.Consumer;
import java.util.function.Predicate;

/**
 * Created by songzhw on 3/16/16.
 */
public class Exercises02 {
    public static void main(String[] args) {
        Exercises02 obj = new Exercises02();
        obj.exer06();

        obj.exer08();

        obj.exer09();

    }

    private void printDivider() {
        System.out.println("====================================");
    }

    /*
    6. Didn't you always hate it that you had to deal with checked exceptions in  Runnable?
    Write a method "uncheck" that catches all checked exceptions
    and turns them into unchecked exception. For eaxmaple:
        new Thread( uncheck(
            ()->{sout("zz"; Thread.sleep(1000);} )).start();
            // Look, no catch InterruptedException.
     */
    private void exer06() {
        Runnable r = uncheck(() -> {
            Thread.sleep(1000);
            System.out.println("====== exer06 over ======");
        });
        new Thread(r).start();
    }

    private Runnable uncheck(RunnableEx ex) {
        return new Runnable() {
            @Override
            public void run() {
                try {
                    ex.run();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
    }

    // =======================================

    // 8. Write a static method "andThen" that takes as parameters two "Runnable" instances
    // and returns a "Runnable" that runs the first, then the second.
    // In the main method, pass two lambda expressions into a call to "andTehen",
    // and run the returned instance
    public void exer08(){
        String[] names = {"peter","paul","Mary"};
        List<Runnable> runners = new ArrayList<>();
        for(String name : names){
            runners.add( ()-> System.out.println(name));
        }

         /*
         * Error!!!
         *     (Because "i" is not effectively final, so lambda report illeagl!)
        for(int i = 0 ; i < names.length ; i++){
            runners.add( ()-> System.out.println(names[i]));
        }
         * */
    }

    // =======================================

    // 9. Form a subclass "Collection2" from "Collection" and add a default method "void forEachIf(Consumer action, Predicater filter)
    // t hat applies action to each element for which filter returns true. How could you use it?
    public void exer09(){
        Collection2<String> tmp = null; // just for example
        tmp.forEachIf(System.out::println,
                (String str) -> str.length() > 2);
        Comparator c;
    }

}

interface RunnableEx {
    void run() throws Exception;
}

interface Collection2<T> extends Collection<T> {
    default void forEachIf(Consumer<T> action, Predicate<T> filter){
        forEach( (T t) -> {
            if(filter.test(t)){
                action.accept(t);
            }
        });
    }
}


text:
struct Prop
{
	char* name;
	char* val;
	struct Prop* nxt;
};
typedef struct Prop* prop;

char* emptystring="";
struct Prop *Properties;

// retourne le contenu d'un fichier dans un buffer
// il ne faudra pas oublier de désalloué le buffer, par un appel à fileReleaseBuffer
char* fileLoadL(const char *filename,int *length)
{
	FILE* file;
	int size;
	char *buffer;

	file=fopen(filename,"rb");
	if (!file) return NULL;

	fseek(file,0,SEEK_END);
	size=ftell(file);
	fseek(file,0,SEEK_SET);

	buffer=(char*)malloc(size+1);
	size=fread((void*)buffer,1,size,file);
	buffer[size]=0;
	fclose(file);
	if (length) *length=size;
	return buffer;
}

char* fileLoad(const char *filename)
{
	return fileLoadL(filename,NULL);
}

// libère le buffer retourné par fileLoad
void fileReleaseBuffer(char* buffer)
{
	if (buffer) free((void*)buffer);
}

// lecture d'une chaîne hexadécimale (s'arrête au premier caractère incorrect)
int htoi(const char* src)
{
	int x,c;
	x=0;
	while(c=*src++)
	{
		if ((c>='0')&&(c<='9')) x=(x<<4)+c-'0';
		else if ((c>='A')&&(c<='F')) x=(x<<4)+c-'A'+10;
		else if ((c>='a')&&(c<='f')) x=(x<<4)+c-'a'+10;
		else return x;
	}
	return x;
}

// alloue une chaîne
char* stringStore(const char *src,int len)
{
	char* s=(char*)malloc(len+1);
	memcpy(s,src,len);
	s[len]=0;
	return s;
}

// désalloue une chaîne
void stringRelease(char *src)
{
	if (src) free((void*)src);
}

// fonction d'identification du premier mot d'une chaîne
// ignore les espaces initiaux, et s'arrête au premier espace ou caractère spécial rencontré
void suppspace(char* begin,int len, char **wordbegin, int *wordlen)
{
	int i=0;
	int j;

	while((i<len)&&(begin[i]>0)&&(begin[i]<=32)) i++;	// suppression des espaces
	*wordbegin=begin+i;

	j=i;
	while((j<len)&&((begin[j]>32)||(begin[j]<0))) j++;	// aller jusqu'au bout du tag
	*wordlen=j-i;
}

// allocation de mémoire pour la structure prop
prop propAlloc()
{
	prop pnt=(prop)malloc(sizeof(struct Prop));
	return pnt;
}

// désallocation de mémoire pour la structure prop
void propFree(prop pnt)
{
	if (pnt) free((void*)pnt);
}

// détruit une prop, avec tous ses champs
void propRelease(prop pnt)
{
	if (pnt)
	{
		propRelease(pnt->nxt);
		stringRelease(pnt->name);
		stringRelease(pnt->val);
		propFree(pnt);
	}
}

// ajout d'un champ à une structure prop 'nxt'
prop propAdd(const char *name,int namelen,const char *val,int vallen,prop nxt)
{
	char *sname,*sval;

	if (name[0] == ';')
		return nxt;

	prop pnt=propAlloc();
	sname=stringStore(name,namelen);
	sval=stringStore(val,vallen);

	pnt->name=sname;
	pnt->val=sval;
	pnt->nxt=nxt;
	return pnt;
}

// inverse la liste de propriétés
prop propReverse(prop pnt)
{
	prop last=NULL;
	prop nxt=NULL;
	while(pnt)
	{
		nxt=pnt->nxt;
		pnt->nxt=last;
		if (!nxt) return pnt;
		last=pnt;
		pnt=nxt;
	}
	return NULL;
}

// parsing d'un buffer rempli avec le contenu d'un fichier de prop
prop propParseInv(char *src)
{
	prop pnt=NULL;	// pointeur vers la property en construction
	int i,name_b,name_e,val_b,val_e;

	i=0;
	while(src[i])
	{
		while((src[i])&&(src[i]>0)&&(src[i]<=32)) i++;
		if (!src[i]) return pnt;
		name_b=i;
		while(src[i]>32) i++;
		if (!src[i]) return pnt;
		name_e=i;
		while((src[i])&&((src[i]==32)||(src[i]==9))) i++;
		if (!src[i]) return pnt;
		if (src[i]>32)	// il y a bien un argument
		{
			val_b=i;
			while((src[i]>=32)||(src[i]<0)) i++;
			val_e=i;
			pnt=propAdd(src+name_b,name_e-name_b,src+val_b,val_e-val_b,pnt);
		}
		else pnt=propAdd(src+name_b,name_e-name_b,src,0,pnt);
	}
	return pnt;
}

// parsing d'un buffer rempli avec le contenu d'un fichier de prop
prop propParse(char *src)
{
	return propReverse(propParseInv(src));
}

// retourne le premier élément
prop propFirst(prop pnt)
{
	return pnt;
}

// retourne l'élément suivant
prop propNext(prop pnt)
{
	return pnt->nxt;
}

// charge un fichier de prop
// retourne un pointeur vers la structure prop du dernier champ
prop propLoad(char *file)
{
	prop pnt=NULL;	// pointeur vers la property en construction
	char* src=fileLoad(file);

	if (!src) return NULL;
	pnt=propParse(src);
	fileReleaseBuffer(src);
	return pnt;
}

// dump d'une prop sur la sortie standard
void propDump(prop pnt)
{
	while(pnt)
	{
		my_printf(LOG_INIT, "%s := %s\n",pnt->name,pnt->val);
		pnt=pnt->nxt;
	}
}

// retourne la valeur d'un champ
char* propGet(prop pnt,char *field)
{
	while(pnt)
	{
		if (!strcmp(pnt->name,field)) return pnt->val;
		pnt=pnt->nxt;
	}
	return emptystring;
}

// retourne la valeur entière d'un champ
int propGetInt(prop pnt,char *field)
{
	char *p=propGet(pnt,field);
	if ((p[0]=='0')&&((p[1]=='x')||(p[1]=='X'))) return htoi(p+2);
	return atoi(p);
}

int PropLoad(char* file)
{
	Properties=propLoad(file);
	return 0;
}

// retourne la valeur d'un champ
char* PropGet(char *field)
{
	return propGet(Properties,field);
}

// retourne la valeur entière d'un champ
int PropGetInt(char *field)
{
	return propGetInt(Properties,field);
}

// efface la valeur d'un champ s'il est présent, chaine
void PropSet(const char *field, const char *val)
{
	prop tmp = Properties;

	while (tmp && strcmp(tmp->name, field))
		tmp = tmp->nxt;
	if (!tmp)
		Properties = propAdd(field,strlen(field),val,strlen(val),Properties);
	else
		{
			stringRelease(tmp->val);
			tmp->val = stringStore(val, strlen(val));
		}
}

// affiche toutes les prop sur la sortie standard
void PropDump()
{
	propDump(Properties);
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>nd4j</artifactId>
        <groupId>org.nd4j</groupId>
        <version>0.9.2-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>nd4j-common</artifactId>
    <packaging>jar</packaging>

    <name>nd4j-common</name>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>ch.qos.logback</groupId>
                <artifactId>logback-classic</artifactId>
                <version>${logback.version}</version>
            </dependency>
            <dependency>
                <groupId>ch.qos.logback</groupId>
                <artifactId>logback-core</artifactId>
                <version>${logback.version}</version>
            </dependency>

        </dependencies>
    </dependencyManagement>

    <dependencies>
        <dependency>
            <groupId>org.nd4j</groupId>
            <artifactId>jackson</artifactId>
            <version>${project.version}</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.reflections</groupId>
            <artifactId>reflections</artifactId>
            <version>${reflections.version}</version>
            <exclusions>
              <exclusion>
                <groupId>com.google.code.findbugs</groupId>
                <artifactId>*</artifactId>
              </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>${commons-io.version}</version>
        </dependency>

        <!-- used to alleviate licensing issues with findbugs -->
        <dependency>
          <groupId>com.github.stephenc.findbugs</groupId>
          <artifactId>findbugs-annotations</artifactId>
          <version>1.3.9-1</version>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-math3</artifactId>
            <version>${commons-math3.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>${commons-lang3.version}</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>${lombok.version}</version>
        </dependency>
    </dependencies>
</project>


text:
#ifndef ISL_STREAM_H
#define ISL_STREAM_H

#include <stdio.h>
#include <isl/hash.h>
#include <isl/aff_type.h>
#include <isl/obj.h>

#if defined(__cplusplus)
extern "C" {
#endif

enum isl_token_type { ISL_TOKEN_ERROR = -1,
			ISL_TOKEN_UNKNOWN = 256, ISL_TOKEN_VALUE,
			ISL_TOKEN_IDENT, ISL_TOKEN_GE,
			ISL_TOKEN_LE, ISL_TOKEN_GT, ISL_TOKEN_LT,
			ISL_TOKEN_NE, ISL_TOKEN_EQ_EQ,
			ISL_TOKEN_LEX_GE, ISL_TOKEN_LEX_LE,
			ISL_TOKEN_LEX_GT, ISL_TOKEN_LEX_LT,
			ISL_TOKEN_TO, ISL_TOKEN_AND,
			ISL_TOKEN_OR, ISL_TOKEN_EXISTS, ISL_TOKEN_NOT,
			ISL_TOKEN_DEF, ISL_TOKEN_INFTY, ISL_TOKEN_NAN,
			ISL_TOKEN_MIN, ISL_TOKEN_MAX, ISL_TOKEN_RAT,
			ISL_TOKEN_TRUE, ISL_TOKEN_FALSE,
			ISL_TOKEN_CEILD, ISL_TOKEN_FLOORD, ISL_TOKEN_MOD,
			ISL_TOKEN_STRING,
			ISL_TOKEN_MAP, ISL_TOKEN_AFF,
			ISL_TOKEN_LAST };

struct isl_token {
	int type;

	unsigned int on_new_line : 1;
	unsigned is_keyword : 1;
	int line;
	int col;

	union {
		isl_int	v;
		char	*s;
		isl_map *map;
		isl_pw_aff *pwaff;
	} u;
};

void isl_token_free(struct isl_token *tok);

struct isl_stream {
	struct isl_ctx	*ctx;
	FILE        	*file;
	const char  	*str;
	int	    	line;
	int	    	col;
	int	    	eof;

	char	    	*buffer;
	size_t	    	size;
	size_t	    	len;
	int	    	c;
	int		un[5];
	int		n_un;

	struct isl_token	*tokens[5];
	int	    	n_token;

	struct isl_hash_table	*keywords;
	enum isl_token_type	 next_type;
};

struct isl_stream* isl_stream_new_file(struct isl_ctx *ctx, FILE *file);
struct isl_stream* isl_stream_new_str(struct isl_ctx *ctx, const char *str);
void isl_stream_free(struct isl_stream *s);

void isl_stream_error(struct isl_stream *s, struct isl_token *tok, char *msg);

struct isl_token *isl_stream_next_token(struct isl_stream *s);
struct isl_token *isl_stream_next_token_on_same_line(struct isl_stream *s);
int isl_stream_next_token_is(struct isl_stream *s, int type);
void isl_stream_push_token(struct isl_stream *s, struct isl_token *tok);
void isl_stream_flush_tokens(struct isl_stream *s);
int isl_stream_eat_if_available(struct isl_stream *s, int type);
char *isl_stream_read_ident_if_available(struct isl_stream *s);
int isl_stream_eat(struct isl_stream *s, int type);
int isl_stream_is_empty(struct isl_stream *s);
int isl_stream_skip_line(struct isl_stream *s);

enum isl_token_type isl_stream_register_keyword(struct isl_stream *s,
	const char *name);

struct isl_obj isl_stream_read_obj(struct isl_stream *s);
__isl_give isl_multi_aff *isl_stream_read_multi_aff(struct isl_stream *s);
__isl_give isl_map *isl_stream_read_map(struct isl_stream *s);
__isl_give isl_set *isl_stream_read_set(struct isl_stream *s);
__isl_give isl_pw_qpolynomial *isl_stream_read_pw_qpolynomial(
	struct isl_stream *s);
__isl_give isl_union_map *isl_stream_read_union_map(struct isl_stream *s);

#if defined(__cplusplus)
}
#endif

#endif


text:
<templateSet group="JavaScript">
  <template name="clog" value="console.log($exp$);" description="Console Log" toReformat="false" toShortenFQNames="true">
    <variable name="exp" expression="" defaultValue="" alwaysStopAt="true" />
  </template>
</templateSet>


text:
#include <aws/migrationhuborchestrator/model/UpdateWorkflowStepRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::MigrationHubOrchestrator::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

UpdateWorkflowStepRequest::UpdateWorkflowStepRequest() :
    m_idHasBeenSet(false),
    m_stepGroupIdHasBeenSet(false),
    m_workflowIdHasBeenSet(false),
    m_nameHasBeenSet(false),
    m_descriptionHasBeenSet(false),
    m_stepActionType(StepActionType::NOT_SET),
    m_stepActionTypeHasBeenSet(false),
    m_workflowStepAutomationConfigurationHasBeenSet(false),
    m_stepTargetHasBeenSet(false),
    m_outputsHasBeenSet(false),
    m_previousHasBeenSet(false),
    m_nextHasBeenSet(false),
    m_status(StepStatus::NOT_SET),
    m_statusHasBeenSet(false)
{
}

Aws::String UpdateWorkflowStepRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_stepGroupIdHasBeenSet)
  {
   payload.WithString("stepGroupId", m_stepGroupId);

  }

  if(m_workflowIdHasBeenSet)
  {
   payload.WithString("workflowId", m_workflowId);

  }

  if(m_nameHasBeenSet)
  {
   payload.WithString("name", m_name);

  }

  if(m_descriptionHasBeenSet)
  {
   payload.WithString("description", m_description);

  }

  if(m_stepActionTypeHasBeenSet)
  {
   payload.WithString("stepActionType", StepActionTypeMapper::GetNameForStepActionType(m_stepActionType));
  }

  if(m_workflowStepAutomationConfigurationHasBeenSet)
  {
   payload.WithObject("workflowStepAutomationConfiguration", m_workflowStepAutomationConfiguration.Jsonize());

  }

  if(m_stepTargetHasBeenSet)
  {
   Aws::Utils::Array<JsonValue> stepTargetJsonList(m_stepTarget.size());
   for(unsigned stepTargetIndex = 0; stepTargetIndex < stepTargetJsonList.GetLength(); ++stepTargetIndex)
   {
     stepTargetJsonList[stepTargetIndex].AsString(m_stepTarget[stepTargetIndex]);
   }
   payload.WithArray("stepTarget", std::move(stepTargetJsonList));

  }

  if(m_outputsHasBeenSet)
  {
   Aws::Utils::Array<JsonValue> outputsJsonList(m_outputs.size());
   for(unsigned outputsIndex = 0; outputsIndex < outputsJsonList.GetLength(); ++outputsIndex)
   {
     outputsJsonList[outputsIndex].AsObject(m_outputs[outputsIndex].Jsonize());
   }
   payload.WithArray("outputs", std::move(outputsJsonList));

  }

  if(m_previousHasBeenSet)
  {
   Aws::Utils::Array<JsonValue> previousJsonList(m_previous.size());
   for(unsigned previousIndex = 0; previousIndex < previousJsonList.GetLength(); ++previousIndex)
   {
     previousJsonList[previousIndex].AsString(m_previous[previousIndex]);
   }
   payload.WithArray("previous", std::move(previousJsonList));

  }

  if(m_nextHasBeenSet)
  {
   Aws::Utils::Array<JsonValue> nextJsonList(m_next.size());
   for(unsigned nextIndex = 0; nextIndex < nextJsonList.GetLength(); ++nextIndex)
   {
     nextJsonList[nextIndex].AsString(m_next[nextIndex]);
   }
   payload.WithArray("next", std::move(nextJsonList));

  }

  if(m_statusHasBeenSet)
  {
   payload.WithString("status", StepStatusMapper::GetNameForStepStatus(m_status));
  }

  return payload.View().WriteReadable();
}


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });

const core_1 = require("@angular-devkit/core");
const schematics_1 = require("@angular-devkit/schematics");
const tasks_1 = require("@angular-devkit/schematics/tasks");
const dependencies_1 = require("../utility/dependencies");
const latest_versions_1 = require("../utility/latest-versions");
const lint_fix_1 = require("../utility/lint-fix");
const paths_1 = require("../utility/paths");
const validation_1 = require("../utility/validation");
const workspace_1 = require("../utility/workspace");
const workspace_models_1 = require("../utility/workspace-models");
function updateJsonFile(host, path, callback) {
    const source = host.read(path);
    if (source) {
        const sourceText = source.toString('utf-8');
        const json = core_1.parseJson(sourceText, core_1.JsonParseMode.Loose);
        callback(json);
        host.overwrite(path, JSON.stringify(json, null, 2));
    }
    return host;
}
function updateTsConfig(packageName, distRoot) {
    return (host) => {
        if (!host.exists('tsconfig.json')) {
            return host;
        }
        return updateJsonFile(host, 'tsconfig.json', (tsconfig) => {
            if (!tsconfig.compilerOptions.paths) {
                tsconfig.compilerOptions.paths = {};
            }
            if (!tsconfig.compilerOptions.paths[packageName]) {
                tsconfig.compilerOptions.paths[packageName] = [];
            }
            tsconfig.compilerOptions.paths[packageName].push(distRoot);
            // deep import & secondary entrypoint support
            const deepPackagePath = packageName + '/*';
            if (!tsconfig.compilerOptions.paths[deepPackagePath]) {
                tsconfig.compilerOptions.paths[deepPackagePath] = [];
            }
            tsconfig.compilerOptions.paths[deepPackagePath].push(distRoot + '/*');
        });
    };
}
function addDependenciesToPackageJson() {
    return (host) => {
        [
            {
                type: dependencies_1.NodeDependencyType.Dev,
                name: '@angular/compiler-cli',
                version: latest_versions_1.latestVersions.Angular,
            },
            {
                type: dependencies_1.NodeDependencyType.Dev,
                name: '@angular-devkit/build-ng-packagr',
                version: latest_versions_1.latestVersions.DevkitBuildNgPackagr,
            },
            {
                type: dependencies_1.NodeDependencyType.Dev,
                name: '@angular-devkit/build-angular',
                version: latest_versions_1.latestVersions.DevkitBuildAngular,
            },
            {
                type: dependencies_1.NodeDependencyType.Dev,
                name: 'ng-packagr',
                version: latest_versions_1.latestVersions.ngPackagr,
            },
            {
                type: dependencies_1.NodeDependencyType.Dev,
                name: 'tsickle',
                version: latest_versions_1.latestVersions.tsickle,
            },
            {
                type: dependencies_1.NodeDependencyType.Default,
                name: 'tslib',
                version: latest_versions_1.latestVersions.TsLib,
            },
            {
                type: dependencies_1.NodeDependencyType.Dev,
                name: 'typescript',
                version: latest_versions_1.latestVersions.TypeScript,
            },
        ].forEach(dependency => dependencies_1.addPackageJsonDependency(host, dependency));
        return host;
    };
}
function addAppToWorkspaceFile(options, projectRoot, projectName) {
    return workspace_1.updateWorkspace(workspace => {
        if (workspace.projects.size === 0) {
            workspace.extensions.defaultProject = projectName;
        }
        workspace.projects.add({
            name: projectName,
            root: projectRoot,
            sourceRoot: `${projectRoot}/src`,
            projectType: workspace_models_1.ProjectType.Library,
            prefix: options.prefix,
            targets: {
                build: {
                    builder: workspace_models_1.Builders.NgPackagr,
                    options: {
                        tsConfig: `${projectRoot}/tsconfig.lib.json`,
                        project: `${projectRoot}/ng-package.json`,
                    },
                },
                test: {
                    builder: workspace_models_1.Builders.Karma,
                    options: {
                        main: `${projectRoot}/src/test.ts`,
                        tsConfig: `${projectRoot}/tsconfig.spec.json`,
                        karmaConfig: `${projectRoot}/karma.conf.js`,
                    },
                },
                lint: {
                    builder: workspace_models_1.Builders.TsLint,
                    options: {
                        tsConfig: [
                            `${projectRoot}/tsconfig.lib.json`,
                            `${projectRoot}/tsconfig.spec.json`,
                        ],
                        exclude: [
                            '**/node_modules/**',
                        ],
                    },
                },
            },
        });
    });
}
function default_1(options) {
    return async (host) => {
        if (!options.name) {
            throw new schematics_1.SchematicsException(`Invalid options, "name" is required.`);
        }
        const prefix = options.prefix;
        validation_1.validateProjectName(options.name);
        // If scoped project (i.e. "@foo/bar"), convert projectDir to "foo/bar".
        const projectName = options.name;
        const packageName = core_1.strings.dasherize(projectName);
        let scopeName = null;
        if (/^@.*\/.*/.test(options.name)) {
            const [scope, name] = options.name.split('/');
            scopeName = scope.replace(/^@/, '');
            options.name = name;
        }
        const workspace = await workspace_1.getWorkspace(host);
        const newProjectRoot = workspace.extensions.newProjectRoot || '';
        const scopeFolder = scopeName ? core_1.strings.dasherize(scopeName) + '/' : '';
        const folderName = `${scopeFolder}${core_1.strings.dasherize(options.name)}`;
        const projectRoot = core_1.join(core_1.normalize(newProjectRoot), folderName);
        const distRoot = `dist/${folderName}`;
        const sourceDir = `${projectRoot}/src/lib`;
        const templateSource = schematics_1.apply(schematics_1.url('./files'), [
            schematics_1.applyTemplates({
                ...core_1.strings,
                ...options,
                packageName,
                projectRoot,
                distRoot,
                relativePathToWorkspaceRoot: paths_1.relativePathToWorkspaceRoot(projectRoot),
                prefix,
                angularLatestVersion: latest_versions_1.latestVersions.Angular.replace('~', '').replace('^', ''),
                folderName,
            }),
            schematics_1.move(projectRoot),
        ]);
        return schematics_1.chain([
            schematics_1.mergeWith(templateSource),
            addAppToWorkspaceFile(options, projectRoot, projectName),
            options.skipPackageJson ? schematics_1.noop() : addDependenciesToPackageJson(),
            options.skipTsConfig ? schematics_1.noop() : updateTsConfig(packageName, distRoot),
            schematics_1.schematic('module', {
                name: options.name,
                commonModule: false,
                flat: true,
                path: sourceDir,
                project: options.name,
            }),
            schematics_1.schematic('component', {
                name: options.name,
                selector: `${prefix}-${options.name}`,
                inlineStyle: true,
                inlineTemplate: true,
                flat: true,
                path: sourceDir,
                export: true,
                project: options.name,
            }),
            schematics_1.schematic('service', {
                name: options.name,
                flat: true,
                path: sourceDir,
                project: options.name,
            }),
            options.lintFix ? lint_fix_1.applyLintFix(sourceDir) : schematics_1.noop(),
            (_tree, context) => {
                if (!options.skipPackageJson && !options.skipInstall) {
                    context.addTask(new tasks_1.NodePackageInstallTask());
                }
            },
        ]);
    };
}
exports.default = default_1;


text:
package com.msb.test;

import com.msb.client.AnalyticsEngineSDK;
public class Test {
	public static void main(String[] args) {
		AnalyticsEngineSDK.onChargeSuccess("orderid123", "zhangsan");
		AnalyticsEngineSDK.onChargeRefund("orderid456", "lisi");
	}
}


text:
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Silverlight.Testing;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using citPOINT.eNeg.Infrastructure.ExceptionHandling;
using citPOINT.eNeg.Infrastructure.Logging;
using System.IO;

namespace citPOINT.eNeg.Infrastructure.ClientSideTest
{
    [TestClass]
    public class ClientExceptionHandling
    {

        /// <summary>
        ///A test for exception handling
        ///</summary>
        [TestMethod()]
        public void ClientExceptionTest()
        {
            LoggingProvider<ClientLoggingHandler>.Log("Test", Category.Common);

            IOException e = new IOException("File Not Exist");

            try
            {
                string result = string.Empty;
                string actual = string.Empty;

                ClientExceptionHandlerProvider.RepaireExceptionPolicies();

                ExceptionHandlingResult exceptionHandlingResult = ExceptionManager.Instance.HandleException(e, "Policy1");

                result = exceptionHandlingResult.Message;
                actual = "The process cannot access the file because it is being used by another process.";

                Assert.IsTrue(result == actual, "Exception error");

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

    }
}


text:
using System.Collections.Generic;

using Moq;
using Xunit;

using BundleTransformer.Core.Assets;
using BundleTransformer.Core.FileSystem;
using BundleTransformer.Core.Filters;
using BundleTransformer.Core.Helpers;

namespace BundleTransformer.Tests.Core.Filters
{
	public class StyleDuplicateAssetsFilterTests : IClassFixture<ApplicationSetupFixture>
	{
		private const string STYLES_DIRECTORY_VIRTUAL_PATH = "~/Content/";
		private const string ALTERNATIVE_STYLES_DIRECTORY_VIRTUAL_PATH = @"~/AlternativeContent/";

		private readonly IVirtualFileSystemWrapper _virtualFileSystemWrapper;

		public StyleDuplicateAssetsFilterTests()
		{
			_virtualFileSystemWrapper = new Mock<IVirtualFileSystemWrapper>().Object;
		}

		[Fact]
		public void DuplicateStyleAssetsRemovedIsCorrect()
		{
			// Arrange
			var siteAsset = new Asset(UrlHelpers.Combine(STYLES_DIRECTORY_VIRTUAL_PATH,
				"Site.css"), _virtualFileSystemWrapper);
			var jqueryUiAccordionMinAsset = new Asset(UrlHelpers.Combine(STYLES_DIRECTORY_VIRTUAL_PATH,
				"themes/base/jquery.ui.accordion.min.css"), _virtualFileSystemWrapper);
			var testCssComponentsPathsAsset = new Asset(UrlHelpers.Combine(ALTERNATIVE_STYLES_DIRECTORY_VIRTUAL_PATH,
				"css/TestCssComponentsPaths.css"), _virtualFileSystemWrapper);
			var testCssComponentsPathsMinAsset = new Asset(UrlHelpers.Combine(
				ALTERNATIVE_STYLES_DIRECTORY_VIRTUAL_PATH,
				"css/TestCssComponentsPaths.min.css"), _virtualFileSystemWrapper);
			var siteDuplicateAsset = new Asset(UrlHelpers.Combine(STYLES_DIRECTORY_VIRTUAL_PATH,
				"site.css"), _virtualFileSystemWrapper);
			var testLessAsset = new Asset(UrlHelpers.Combine(STYLES_DIRECTORY_VIRTUAL_PATH,
				"less/TestLess.less"), _virtualFileSystemWrapper);
			var testSassAsset = new Asset(UrlHelpers.Combine(STYLES_DIRECTORY_VIRTUAL_PATH,
				"sass/TestSass.sass"), _virtualFileSystemWrapper);
			var testScssAsset = new Asset(UrlHelpers.Combine(STYLES_DIRECTORY_VIRTUAL_PATH,
				"scss/TestScss.scss"), _virtualFileSystemWrapper);
			var duplicateTestLessAsset = new Asset(UrlHelpers.Combine(STYLES_DIRECTORY_VIRTUAL_PATH,
				"LESS/TestLess.less"), _virtualFileSystemWrapper);

			IList<IAsset> assets = new List<IAsset>
			{
				siteAsset,
				jqueryUiAccordionMinAsset,
				testCssComponentsPathsAsset,
				testCssComponentsPathsMinAsset,
				siteDuplicateAsset,
				testLessAsset,
				testSassAsset,
				testScssAsset,
				duplicateTestLessAsset
			};

			var styleDuplicateFilter = new StyleDuplicateAssetsFilter();

			// Act
			IList<IAsset> processedAssets = styleDuplicateFilter.Transform(assets);

			// Assert
			Assert.Equal(6, processedAssets.Count);
			Assert.Equal(UrlHelpers.Combine(STYLES_DIRECTORY_VIRTUAL_PATH,
				"Site.css"), processedAssets[0].VirtualPath);
			Assert.Equal(UrlHelpers.Combine(STYLES_DIRECTORY_VIRTUAL_PATH,
				"themes/base/jquery.ui.accordion.min.css"), processedAssets[1].VirtualPath);
			Assert.Equal(UrlHelpers.Combine(ALTERNATIVE_STYLES_DIRECTORY_VIRTUAL_PATH,
				"css/TestCssComponentsPaths.css"), processedAssets[2].VirtualPath);
			Assert.Equal(UrlHelpers.Combine(STYLES_DIRECTORY_VIRTUAL_PATH,
				"less/TestLess.less"), processedAssets[3].VirtualPath);
			Assert.Equal(UrlHelpers.Combine(STYLES_DIRECTORY_VIRTUAL_PATH,
				"sass/TestSass.sass"), processedAssets[4].VirtualPath);
			Assert.Equal(UrlHelpers.Combine(STYLES_DIRECTORY_VIRTUAL_PATH,
				"scss/TestScss.scss"), processedAssets[5].VirtualPath);
		}
	}
}


text:
brew update

# Upgrade any already-installed formulae.
brew upgrade

# Install GNU core utilities (those that come with macOS are outdated).
# Don't forget to add `$(brew --prefix coreutils)/libexec/gnubin` to `$PATH`.
brew install coreutils

# Install GNU `find`, `locate`, `updatedb`, and `xargs`, `g`-prefixed.
brew install findutils

# Install GNU `sed`, overwriting the built-in `sed`.
brew install gnu-sed --with-default-names

# Install Bash 4.
# Note: don't forget to add `/usr/local/bin/bash` to `/etc/shells` before
# running `chsh`.
brew install bash
brew install bash-completion2

# Switch to using brew-installed bash as default shell
if ! fgrep -q '/usr/local/bin/bash' /etc/shells; then
  echo '/usr/local/bin/bash' | sudo tee -a /etc/shells;
  chsh -s /usr/local/bin/bash;
fi;

# Install `wget` with IRI support.
brew install wget --with-iri

# Install GnuPG to enable PGP-signing commits.
brew install gnupg

# Install more recent versions of some macOS tools.
brew install vim --with-override-system-vi
brew install grep
brew install openssh

# Install other useful binaries.
brew install ack
brew install diff-so-fancy
brew install ffmpeg
brew install fzf
brew install git
brew install git-standup
brew install imagemagick --with-webp
brew install p7zip
brew install pgcli
brew install pigz
brew install rename
brew install rlwrap
brew install ssh-copy-id
brew install tree
brew install unrar
brew install watchman
brew install yarn
brew install youtube-dl
brew install z
brew install zopfli

# Remove outdated versions from the cellar.
brew cleanup