text:
package com.opengamma.strata.product.bond;

import static com.opengamma.strata.basics.currency.Currency.USD;
import static com.opengamma.strata.basics.date.HolidayCalendarIds.USNY;
import static com.opengamma.strata.collect.TestHelper.assertSerialization;
import static com.opengamma.strata.collect.TestHelper.coverBeanEquals;
import static com.opengamma.strata.collect.TestHelper.coverImmutableBean;
import static com.opengamma.strata.collect.TestHelper.date;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.assertj.core.data.Offset.offset;

import java.time.LocalDate;

import org.junit.jupiter.api.Test;

import com.opengamma.strata.basics.ReferenceData;
import com.opengamma.strata.basics.currency.Currency;
import com.opengamma.strata.basics.currency.Payment;
import com.opengamma.strata.basics.date.BusinessDayAdjustment;
import com.opengamma.strata.basics.date.BusinessDayConventions;
import com.opengamma.strata.product.PortfolioItemSummary;
import com.opengamma.strata.product.PortfolioItemType;
import com.opengamma.strata.product.ProductType;
import com.opengamma.strata.product.TradeInfo;

/**
 * Test {@link CapitalIndexedBondTrade}.
 */
public class CapitalIndexedBondTradeTest {

  private static final ReferenceData REF_DATA = ReferenceData.standard();
  private static final double QUANTITY = 10;
  private static final double QUANTITY2 = 20;
  private static final double PRICE = 0.995;
  private static final double PRICE2 = 0.9;
  private static final BusinessDayAdjustment SCHEDULE_ADJ =
      BusinessDayAdjustment.of(BusinessDayConventions.FOLLOWING, USNY);
  private static final CapitalIndexedBond PRODUCT = CapitalIndexedBondTest.sut();
  private static final CapitalIndexedBond PRODUCT1 = CapitalIndexedBondTest.sut1();
  private static final CapitalIndexedBond PRODUCT2 = CapitalIndexedBondTest.sut2();
  private static final LocalDate START = PRODUCT.getAccrualSchedule().getStartDate();
  private static final LocalDate TRADE = START.plusDays(7);
  private static final LocalDate SETTLEMENT_DATE = SCHEDULE_ADJ.adjust(TRADE, REF_DATA);
  private static final TradeInfo TRADE_INFO =
      TradeInfo.builder().tradeDate(TRADE).settlementDate(SETTLEMENT_DATE).build();
  private static final TradeInfo TRADE_INFO_EARLY =
      TradeInfo.builder().tradeDate(date(2008, 1, 1)).settlementDate(date(2008, 1, 1)).build();

  //-------------------------------------------------------------------------
  @Test
  public void test_builder() {
    CapitalIndexedBondTrade test = sut();
    assertThat(test.getInfo()).isEqualTo(TRADE_INFO);
    assertThat(test.getProduct()).isEqualTo(PRODUCT);
    assertThat(test.getQuantity()).isEqualTo(QUANTITY);
    assertThat(test.getPrice()).isEqualTo(PRICE);
    assertThat(test.withInfo(TRADE_INFO).getInfo()).isEqualTo(TRADE_INFO);
    assertThat(test.withQuantity(129).getQuantity()).isCloseTo(129d, offset(0d));
    assertThat(test.withPrice(129).getPrice()).isCloseTo(129d, offset(0d));
  }

  //-------------------------------------------------------------------------
  private static final CapitalIndexedBondPaymentPeriod SETTLEMENT = CapitalIndexedBondPaymentPeriod.builder()
      .startDate(SCHEDULE_ADJ.adjust(START, REF_DATA))
      .unadjustedStartDate(START)
      .endDate(SETTLEMENT_DATE)
      .currency(USD)
      .rateComputation(PRODUCT.getRateCalculation().createRateComputation(SETTLEMENT_DATE))
      .notional(
          -PRODUCT.getNotional() * QUANTITY *
              (PRICE + PRODUCT.resolve(REF_DATA).accruedInterest(SETTLEMENT_DATE) / PRODUCT.getNotional()))
      .realCoupon(1d)
      .build();

  private static final KnownAmountBondPaymentPeriod SETTLEMENT1 = KnownAmountBondPaymentPeriod
      .builder()
      .startDate(SCHEDULE_ADJ.adjust(START, REF_DATA))
      .unadjustedStartDate(START)
      .endDate(SETTLEMENT_DATE)
      .payment(
          Payment.of(USD, -PRODUCT1.getNotional() * QUANTITY *
              (PRICE + PRODUCT1.resolve(REF_DATA).accruedInterest(SETTLEMENT_DATE) / PRODUCT1.getNotional()),
              SETTLEMENT_DATE))
      .build();

  //-------------------------------------------------------------------------
  @Test
  public void test_summarize() {
    CapitalIndexedBondTrade trade = sut();
    PortfolioItemSummary expected = PortfolioItemSummary.builder()
        .id(TRADE_INFO.getId().orElse(null))
        .portfolioItemType(PortfolioItemType.TRADE)
        .productType(ProductType.BOND)
        .currencies(Currency.USD)
        .description("Bond x 10")
        .build();
    assertThat(trade.summarize()).isEqualTo(expected);
  }

  //-------------------------------------------------------------------------
  @Test
  public void test_resolve() {
    ResolvedCapitalIndexedBondTrade test = sut().resolve(REF_DATA);
    ResolvedCapitalIndexedBondTrade expected = ResolvedCapitalIndexedBondTrade.builder()
        .info(TRADE_INFO)
        .product(PRODUCT.resolve(REF_DATA))
        .quantity(QUANTITY)
        .settlement(ResolvedCapitalIndexedBondSettlement.of(SETTLEMENT_DATE, PRICE, SETTLEMENT))
        .build();
    assertThat(test).isEqualTo(expected);
  }

  @Test
  public void test_resolve1() {
    ResolvedCapitalIndexedBondTrade test = sut1().resolve(REF_DATA);
    ResolvedCapitalIndexedBondTrade expected = ResolvedCapitalIndexedBondTrade.builder()
        .info(TRADE_INFO)
        .product(PRODUCT1.resolve(REF_DATA))
        .quantity(QUANTITY)
        .settlement(ResolvedCapitalIndexedBondSettlement.of(SETTLEMENT_DATE, PRICE, SETTLEMENT1))
        .build();
    assertThat(test).isEqualTo(expected);
  }

  @Test
  public void test_resolve_invalid() {
    CapitalIndexedBondTrade test = sut().toBuilder().info(TRADE_INFO_EARLY).build();
    assertThatIllegalArgumentException()
        .isThrownBy(() -> test.resolve(REF_DATA));
  }

  @Test
  public void test_resolve_noTradeOrSettlementDate() {
    CapitalIndexedBondTrade test = CapitalIndexedBondTrade.builder()
        .info(TradeInfo.empty())
        .product(PRODUCT)
        .quantity(QUANTITY)
        .price(PRICE)
        .build();
    assertThatIllegalStateException()
        .isThrownBy(() -> test.resolve(REF_DATA));
  }

  //-------------------------------------------------------------------------
  @Test
  public void test_withQuantity() {
    CapitalIndexedBondTrade base = sut();
    double quantity = 3456d;
    CapitalIndexedBondTrade computed = base.withQuantity(quantity);
    CapitalIndexedBondTrade expected = CapitalIndexedBondTrade.builder()
        .info(TRADE_INFO)
        .product(PRODUCT)
        .quantity(quantity)
        .price(PRICE)
        .build();
    assertThat(computed).isEqualTo(expected);
  }

  @Test
  public void test_withPrice() {
    CapitalIndexedBondTrade base = sut();
    double price = 0.95;
    CapitalIndexedBondTrade computed = base.withPrice(price);
    CapitalIndexedBondTrade expected = CapitalIndexedBondTrade.builder()
        .info(TRADE_INFO)
        .product(PRODUCT)
        .quantity(QUANTITY)
        .price(price)
        .build();
    assertThat(computed).isEqualTo(expected);
  }

  //-------------------------------------------------------------------------
  @Test
  public void coverage() {
    coverImmutableBean(sut());
    coverBeanEquals(sut(), sut2());
  }

  @Test
  public void test_serialization() {
    assertSerialization(sut());
  }

  //-------------------------------------------------------------------------
  static CapitalIndexedBondTrade sut() {
    return CapitalIndexedBondTrade.builder()
        .info(TRADE_INFO)
        .product(PRODUCT)
        .quantity(QUANTITY)
        .price(PRICE)
        .build();
  }

  static CapitalIndexedBondTrade sut1() {
    return CapitalIndexedBondTrade.builder()
        .info(TRADE_INFO)
        .product(PRODUCT1)
        .quantity(QUANTITY)
        .price(PRICE)
        .build();
  }

  static CapitalIndexedBondTrade sut2() {
    return CapitalIndexedBondTrade.builder()
        .info(TradeInfo.builder().tradeDate(START.plusDays(7)).build())
        .product(PRODUCT2)
        .quantity(QUANTITY2)
        .price(PRICE2)
        .build();
  }

}


text:
var util = require('ui/util');
var styles = require('ui/handheld/loginWindow/styles');

function logics(win, model, delegate) {
	this.win = win;
	this.model = model;
	this.delegate = delegate;
	this.offset = 0;
	this.bottomOfScreenOffset = ((100*20)-Ti.Platform.displayCaps.platformHeight);;
	this.lastRowOffset =this.bottomOfScreenOffset-100;
};

logics.prototype.winOpen = function(e) {
	var self = this;
	self.updateBoardList(self.model.board.getBoardList());
	self.delegate.fireEvent('openBoard');
};

logics.prototype.updateBoardList = function(param) {
	var self = this;

	var data = self.model.board.getBoardList();
	var rowData = [];
	// rowData = [
		// {title:"Refresh",color:'#000',height:50},
		// {title:"Row 1",color:'#000',height:50},
		// {title:"Row 2",color:'#000',height:50},
		// {title:"Row 3",color:'#000',height:50},
		// {title:"Row 4",color:'#000',height:50},
		// {title:"Row 5",color:'#000',height:50},
		// {title:"Row 6",color:'#000',height:50},
		// {title:"Row 7",color:'#000',height:50},
		// {title:"Row 8",color:'#000',height:50},
		// {title:"Row 9",color:'#000',height:t50},
		// {title:"Row 10",color:'#000',height:50},
		// {title:"Row 11",color:'#000',height:50},
		// {title:"Row 12",color:'#000',height:50},
		// {title:"Row 13",color:'#000',height:50},
		// {title:"Row 14",color:'#000',height:50},
		// {title:"Row 15",color:'#000',height:50},
		// {title:"Row 16",color:'#000',height:50},
		// {title:"Row 17",color:'#000',height:50},
		// {title:"Row 18",color:'#000',height:50},
		// {title:"Load More",color:'#000',height:50}
	// ];

	rowData.push(Ti.UI.createTableViewRow({
		title:"Refresh",color:'#f00',height:50
	}));
	for (var i in data) {
		var styles = require('ui/handheld/boardListWindow/styles');

		// TODO getti 行はクラス的にバインド関数を作る
		var row = Ti.UI.createTableViewRow(styles.tvrBoard);

		// コンポーネント
		//row.img = Ti.UI.createView(styles.viewImg);
		row.name = Ti.UI.createLabel(styles.lblTitle);
		row.summary = Ti.UI.createLabel(styles.lblSummary);
		row.authorName = Ti.UI.createLabel(styles.lblAuthorName);
		row.updateDate = Ti.UI.createLabel(styles.lblUpdateDate)

		// レイアウト
		//util.setViewRect(row.img, 10, 5, 50, 50);
		util.setViewRect(row.name, 70, 5, '100%', 30);
		util.setViewRect(row.summary, 70, 35, '100%', 20);
		util.setViewRect(row.authorName, 70, 57, '100%', 20);
		util.setViewRect(row.updateDate, 70, 79, '100%', 20);

		//row.add(row.img);
		row.add(row.name);
		row.add(row.summary);
		row.add(row.authorName);
		row.add(row.updateDate);

		// データ設定
		row.data = data[i];
		row.title = data[i].title;
		row.name.text = data[i].title;
		row.summary.text = data[i].body;
		row.authorName.text = data[i].author;
		row.updateDate.text = data[i].createDate;

		rowData.push(row);
	}

	self.win.tvBoard.data = rowData;
	if(rowData.length > 0) self.win.tvBoard.scrollToIndex(1);
};

logics.prototype.svBoardScroll = function(e) {
	var self = this;
	if (e.y != null) {
		self.offset = e.y;

		Ti.API.info('offset: '+ self.offset);
	}
};

logics.prototype.tvBoardTouched = function(e) {
	var self = this;
	var alertDialog = Titanium.UI.createAlertDialog({
		title: 'System Message',
		buttonNames: ['OK']
	});

	if (self.offset <= 0) {
		Ti.API.info('REFRESH !!!!');
		alertDialog.message = "REFRESH !!!!";
		//alertDialog.show();
		//self.win.svBoard.scrollTo(0, 50);
		self.win.tvBoard.scrollToIndex(1);
	} else if (self.offset < 50) {
		//self.win.svBoard.scrollTo(0, 50);
		self.win.tvBoard.scrollToIndex(1);
		Ti.API.info('Dont refresh, go back to base');
	// } else if (self.offset==self.bottomOfScreenOffset) {
		// Ti.API.info('LOAD MORE !!!!');
		// alertDialog.message = "LOAD MORE !!!!";
		// alertDialog.show();
		// self.win.svBoard.scrollTo(0,lastRowOffset);
	// } else if (self.offset > self.lastRowOffset) {
		// self.win.svBoard.scrollTo(0,lastRowOffset);
		// Ti.API.info('Dont load more, go back to base');
	}
};

logics.prototype.clickList = function(e) {
	var self = this;
//	var detailWindow = new (require('ui/handheld/boardDetailWindow/view'))(self.model, self.delegate);
//	detailWindow.update(e.row.data.groupId, e.row.data.id);
//	detailWindow.open({}, self.win);
};

module.exports = logics;

redpajama_set_name: RedPajamaGithub


text:
#pragma once

#ifdef __aarch64__
#include "../std_transforms_fixed.hpp"
#include "../bfloat.hpp"
#include "../performance_parameters.hpp"

#define ARGLIST  \
    unsigned int, const unsigned int *, \
    IndirectInputArg<bfloat16>, \
    size_t, size_t, \
    const bfloat16 *, \
    IndirectOutputArg<float>, \
    const float *, Activation, bool

namespace arm_gemm
{
// Actual kernel implementations
void a64_hybrid_bf16fp32_dot_6x16( ARGLIST );

class cls_a64_hybrid_bf16fp32_dot_6x16
{
public:
    typedef bfloat16 lhs_operand_type;
    typedef bfloat16 rhs_operand_type;
    typedef float result_type;

    typedef void (*kern_type)( ARGLIST );

    /* Kernel blocking parameters */
    static constexpr unsigned int out_height()
    {
        return 6;
    }

    static unsigned int out_width()
    {
        return 16;
    }

    static constexpr unsigned int k_unroll()
    {
        return 2;
    }

    static constexpr bool supports_accumulate()
    {
        return true;
    }

    StdTransformsFixed<rhs_operand_type, result_type, 6, 16, 2> transforms = {};
    template<typename T>
    static inline PerformanceParameters get_performance_parameters(const CPUInfo *ci)
    {
        if (std::is_same<T, bfloat16>::value) {
            switch (ci->get_cpu_model()) {
                default:
                    return { 15.83 };
                case CPUModel::A510:
                    return { 7.28 };
                case CPUModel::V1:
                    return { 27.34 };
            }
        }

        return { 1.0 };
    }

    // Default to the generic kernel
    kern_type kernel=a64_hybrid_bf16fp32_dot_6x16;
    cls_a64_hybrid_bf16fp32_dot_6x16(const CPUInfo *)
    {
    }
};

} // namespace arm_gemm

#undef ARGLIST

#endif // __aarch64__


text:
require 'spec_helper'

describe Admin::ConfigurationController do

  before(:each) do
    @admin_service = double("admin_service")
    @config_repository = double("config_repository")
    controller.stub(:admin_service).and_return(@admin_service)
    controller.stub(:config_repository).and_return(@config_repository)
  end

  describe "tab_name" do
    before :each do
      @config = {"content" => "config-content", "md5" => "md5", "location" => "/foo/bar"}
      cruise_config_revision = double('cruise config revision')
      @config_repository.should_receive(:getRevision).with(@config['md5']).and_return(cruise_config_revision)
    end

    it "should set tab name for show" do
      @admin_service.should_receive(:populateModel).with(anything).and_return(@config)
      get :show
      assigns[:tab_name].should == 'configuration-xml'
    end

    it "should set tab name for edit" do
      @admin_service.should_receive(:configurationMapForSourceXml).and_return(@config)
      get :edit
      assigns[:tab_name].should == 'configuration-xml'
    end
  end

  describe "view_title" do
    before :each do
      @config = {"content" => "config-content", "md5" => "md5", "location" => "/foo/bar"}
      cruise_config_revision = double('cruise config revision')
      @config_repository.should_receive(:getRevision).with(@config['md5']).and_return(cruise_config_revision)
    end

    it "should set tab name for show" do
      @admin_service.should_receive(:populateModel).with(anything).and_return(@config)

      get :show

      assigns[:view_title].should == 'Administration'
      assert_template layout: "admin"
    end

    it "should set tab name for edit" do
      @admin_service.should_receive(:configurationMapForSourceXml).and_return(@config)

      get :edit

      assigns[:view_title].should == 'Administration'
      assert_template layout: "admin"
    end
  end

  describe "routes" do
    it "view" do
      config_view_path.should == "/admin/config_xml"
      {:get => "/admin/config_xml"}.should route_to(:controller => "admin/configuration", :action => "show")
    end

    it "edit" do
      config_edit_path.should == "/admin/config_xml/edit"
      {:get => "/admin/config_xml/edit"}.should route_to(:controller => "admin/configuration", :action => "edit")
    end

    it "update" do
      config_update_path.should == "/admin/config_xml"
      {:put => "/admin/config_xml"}.should route_to(:controller => "admin/configuration", :action => "update")
    end
  end

  describe :show do
    it "should render view with config" do
      config = {"content" => "config-content", "md5" => "md5", "location" => "/foo/bar"}
      @admin_service.should_receive(:populateModel).with(anything).and_return(config)
      cruise_config_revision = double('cruise config revision')
      @config_repository.should_receive(:getRevision).with(config['md5']).and_return(cruise_config_revision)

      get :show

      response.should render_template "show"
      assigns[:go_config].content.should == "config-content"
      assigns[:go_config].md5.should == "md5"
      assigns[:go_config].location.should == "/foo/bar"
      assigns[:go_config_revision].should == cruise_config_revision
    end
  end

  describe :edit do
    it "should render edit" do
      config = {"content" => "config-content", "md5" => "md5", "location" => "/foo/bar"}
      @admin_service.should_receive(:configurationMapForSourceXml).and_return(config)
      cruise_config_revision = double('cruise config revision')
      @config_repository.should_receive(:getRevision).with(config['md5']).and_return(cruise_config_revision)

      get :edit

      response.should render_template "edit"
      assigns[:go_config].content.should == "config-content"
      assigns[:go_config].md5.should == "md5"
      assigns[:go_config].location.should == "/foo/bar"
      assigns[:go_config_revision].should == cruise_config_revision
    end
  end

  describe :update do
    it "should update the configuration" do
      param_map = {"content" => "config_content", "md5" => "md5"}
      @admin_service.should_receive(:updateConfig).with(param_map, an_instance_of(HttpLocalizedOperationResult)).and_return(GoConfigValidity::valid())

      put :update, :go_config => param_map

      flash[:success].should == 'Saved successfully.'
      assert_redirect config_view_path
    end

    it "should render edit page when config save fails" do
      current_config = {"content" => "config-content", "md5" => "current-md5", "location" => "/foo/bar"}
      submitted_copy = {"content" => "edited-content", "md5" => "md5"}
      config_validity = double('config validity')
      config_validity.should_receive(:isValid).and_return(false)
      config_validity.should_receive(:errorMessage).and_return('Wrong config xml')
      controller.stub(:switch_to_split_pane?).once.with(config_validity).and_return(false)
      @admin_service.should_receive(:configurationMapForSourceXml).and_return(current_config)
      @admin_service.should_receive(:updateConfig).with(submitted_copy, an_instance_of(HttpLocalizedOperationResult)).and_return(config_validity)
      cruise_config_revision = double('cruise config revision')
      @config_repository.should_receive(:getRevision).with(submitted_copy['md5']).and_return(cruise_config_revision)

      put :update, {:go_config => submitted_copy}

      response.should render_template "edit"
      flash.now[:error].should == 'Save failed, see errors below'
      assigns[:errors][0].should == "Wrong config xml"
      assigns[:go_config].content.should == "edited-content"
      assigns[:go_config].md5.should == "md5"
      assigns[:go_config].location.should == "/foo/bar"
      assigns[:go_config_revision].should == cruise_config_revision
    end

    it "should render split pane when config save fails because of merge conflict" do
      current_config = {"content" => "config-content", "md5" => "md5", "location" => "/foo/bar"}
      submitted_copy = {"content" => "content-which-caused-conflict", "md5" => "md5"}
      @admin_service.should_receive(:configurationMapForSourceXml).and_return(current_config)
      config_validity = double('config validity')
      config_validity.should_receive(:isValid).and_return(false)
      config_validity.should_receive(:errorMessage).and_return('Conflict in merging')
      controller.stub(:switch_to_split_pane?).once.with(config_validity).and_return(true)
      @admin_service.should_receive(:updateConfig).with(submitted_copy, an_instance_of(HttpLocalizedOperationResult)).and_return(config_validity)
      cruise_config_revision = double('cruise config revision')
      @config_repository.should_receive(:getRevision).with(current_config['md5']).and_return(cruise_config_revision)

      put :update, {:go_config => submitted_copy}

      response.should render_template "split_pane"
      flash.now[:error].should == "Someone has modified the configuration and your changes are in conflict. Please review, amend and retry."
      assigns[:errors][0].should == "Conflict in merging"
      assigns[:flash_help_link].should == "Help Topic: Configuration"
      assigns[:conflicted_config].content.should == submitted_copy['content']
      assigns[:conflicted_config].md5.should == submitted_copy['md5']
      assigns[:conflicted_config].location.should == submitted_copy['location']
      assigns[:go_config].content.should == current_config['content']
      assigns[:go_config].md5.should == current_config['md5']
      assigns[:go_config].location.should == current_config['location']
      assigns[:go_config_revision].should == cruise_config_revision
    end

    it "should render display configuration merged successfully when a merge happens" do
      submitted_copy = {"content" => "config_content_1", "md5" => "md5"}
      config_validity = double('config_validity')
      config_validity.should_receive(:isValid).and_return(true)
      config_validity.should_receive(:wasMerged).and_return(true)
      @admin_service.should_receive(:updateConfig).with(submitted_copy, an_instance_of(HttpLocalizedOperationResult)).and_return(config_validity)

      put :update, {:go_config => submitted_copy}

      flash[:success].should == 'Saved successfully. The configuration was modified by someone else, but your changes were merged successfully.'
      assert_redirect config_view_path
    end
  end

  describe :switch_to_split_pane? do
    it "should return false when config validity is valid" do
      config_validity = double('config validity')
      config_validity.should_receive(:isValid).and_return(true)
      config_validity.should_receive(:isMergeConflict).never
      config_validity.should_receive(:isPostValidationError).never
      actual = @controller.send(:switch_to_split_pane?, config_validity)
      actual.should == false
    end

    it "should return true when config validity says a merge failure" do
      config_validity = double('config validity')
      config_validity.should_receive(:isValid).and_return(false)
      config_validity.should_receive(:isMergeConflict).and_return(true)
      config_validity.should_receive(:isPostValidationError).never
      actual = @controller.send(:switch_to_split_pane?, config_validity)
      actual.should == true
    end

    it "should return true when config validity says a post validation error" do
      config_validity = double('config validity')
      config_validity.should_receive(:isValid).and_return(false)
      config_validity.should_receive(:isMergeConflict).and_return(false)
      config_validity.should_receive(:isPostValidationError).and_return(true)
      actual = @controller.send(:switch_to_split_pane?, config_validity)
      actual.should == true
    end
  end
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.Text;

namespace CoffeeSyntax {

	using MlInfo = Tuple<string, string, CoffeeOverview.MultiLineType, string>;

	class CoffeeOverview {

		public enum MultiLineType {
			Comment, Backtick, StringSingle, StringDouble, HeredocSingle, HeredocDouble, Regex
		}

		public struct MultiLine {
			public MultiLine(ITrackingSpan span, MultiLineType type)
				: this() {
				this.Span = span;
				this.Type = type;
			}
			public ITrackingSpan Span { get; private set; }
			public MultiLineType Type { get; private set; }
			public SnapshotSpan GetSpan(ITextSnapshot ss) {
				return this.Span.GetSpan(ss);
			}
			public override string ToString() {
				return string.Format("{{ {0}, {1} }}", this.Span, this.Type);
			}
		}

		public class MultiLinesChangedEventArgs : EventArgs {
			public MultiLinesChangedEventArgs(IEnumerable<MultiLine> added, IEnumerable<MultiLine> removed) {
				this.Added = added;
				this.Removed = removed;
			}
			public IEnumerable<MultiLine> Added { get; private set; }
			public IEnumerable<MultiLine> Removed { get; private set; }
		}

		public CoffeeOverview(ITextBuffer textBuffer) {
			this.textBuffer = textBuffer;
			this.CalcMultiLines();
			textBuffer.Changed += (o, e) => {
				if (this.IsMultiLineChange(e)) {
					this.CalcMultiLines();
				}
			};
		}

		private ITextBuffer textBuffer;

		public IEnumerable<MultiLine> MultiLines { get; private set; }
		public event EventHandler<MultiLinesChangedEventArgs> MultiLinesChanged;

		private static MlInfo[] multiLinesDelimiters =
		{
			Tuple.Create("###", "###", MultiLineType.Comment, (string)null),
			Tuple.Create("/*", "*/", MultiLineType.Comment, (string)null),
			Tuple.Create("`", "`", MultiLineType.Backtick, (string)null),
			Tuple.Create("'", "'", MultiLineType.StringSingle, "\\'"),
			Tuple.Create("\"", "\"", MultiLineType.StringDouble, "\\\""),
			Tuple.Create("'''", "'''", MultiLineType.HeredocSingle, (string)null),
			Tuple.Create("\"\"\"", "\"\"\"", MultiLineType.HeredocDouble, (string)null),
			Tuple.Create("///", "///", MultiLineType.Regex, (string)null),
		};

		private static string[] multiLinesSigTexts =
			multiLinesDelimiters.SelectMany(x => new[] { x.Item1, x.Item2 }).Distinct().ToArray();

		private bool IsMultiLineChange(TextContentChangedEventArgs e) {
			return e.Changes.Any(change => {
				return multiLinesSigTexts.Any(sigText => {
					var len1 = sigText.Length - 1;
					var beforeStart = Math.Max(0, change.OldPosition - len1);
					var beforeEnd = Math.Min(e.Before.Length, change.OldPosition + change.OldLength + len1);
					var textOld = beforeEnd > beforeStart ? e.Before.GetText(beforeStart, beforeEnd - beforeStart) : "";
					var afterStart = Math.Max(0, change.NewPosition - len1);
					var afterEnd = Math.Min(e.After.Length, change.NewPosition + change.NewLength + len1);
					var textNew = afterEnd > afterStart ? e.After.GetText(afterStart, afterEnd - afterStart) : "";
					return textOld.Contains(sigText) || textNew.Contains(sigText);
				});
			});
		}

		private void CalcMultiLines() {
			var spans = new List<MultiLine>();
			var ss = this.textBuffer.CurrentSnapshot;
			var text = ss.GetText();
			MlInfo curMultiline = null;
			int startPos = -1;
			bool inComment = false;
			for (int i = 0, n = text.Length; i < n; i++) {
				if (inComment) {
					if (text[i].In('\r', '\n')) {
						inComment = false;
					}
				} else {
					if (curMultiline == null) {
						if (text[i] == '#') {
							inComment = true;
						} else {
							curMultiline = multiLinesDelimiters.FirstOrDefault(x => text.IsAt(i, x.Item1));
							if (curMultiline != null) {
								startPos = i;
								i += curMultiline.Item1.Length - 1 + curMultiline.Item2.Length - 1;
							}
						}
					} else {
						if (curMultiline.Item4 != null && text.IsAt(i, curMultiline.Item4)) {
							i += curMultiline.Item4.Length - 1;
						} else if (text.IsAt(i - (curMultiline.Item2.Length - 1), curMultiline.Item2)) {
							var trackingSpan = ss.CreateTrackingSpan(startPos, i - startPos + 1, SpanTrackingMode.EdgeExclusive);
							spans.Add(new MultiLine(trackingSpan, curMultiline.Item3));
							curMultiline = null;
						}
					}
				}
			}
			if (curMultiline != null) {
				if (ss.GetLineNumberFromPosition(startPos) != ss.GetLineNumberFromPosition(text.Length - 1)) {
					var trackingSpan = ss.CreateTrackingSpan(startPos, text.Length - startPos, SpanTrackingMode.EdgeExclusive);
					spans.Add(new MultiLine(trackingSpan, curMultiline.Item3));
				}
			}
			this.RaiseMultiLinesChanged(spans, this.MultiLines);
			this.MultiLines = spans;
		}

		private void RaiseMultiLinesChanged(IEnumerable<MultiLine> added, IEnumerable<MultiLine> removed) {
			if (this.MultiLinesChanged != null) {
				var eventArgs = new MultiLinesChangedEventArgs(added, removed);
				this.MultiLinesChanged(this, eventArgs);
			}
		}

	}
}


text:
package com.ervin.litepal.table;

import com.google.gson.annotations.SerializedName;

import org.litepal.annotation.Column;
import org.litepal.crud.DataSupport;

import java.util.Date;

/**
 * Created by Ervin on 2016/3/24.
 */
public class Meizhis extends DataSupport {

    @Column(unique = true, defaultValue = "unknown")
    public String url;

    public String type;

    @SerializedName("desc")  //Gson注解属性 Gson2.4注解新增加了一个属性alternate,可以设置多个别名(如下)
    public String desc;

    @SerializedName(value = "who",alternate = {"me","she","it"})
    public String who;

    public boolean used;

    public Date createdAt;

    public Date updatedAt;

    public Date publishedAt;

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }

    public String getWho() {
        return who;
    }

    public void setWho(String who) {
        this.who = who;
    }

    public boolean isUsed() {
        return used;
    }

    public void setUsed(boolean used) {
        this.used = used;
    }

    public Date getCreatedAt() {
        return createdAt;
    }

    public void setCreatedAt(Date createdAt) {
        this.createdAt = createdAt;
    }

    public Date getUpdatedAt() {
        return updatedAt;
    }

    public void setUpdatedAt(Date updatedAt) {
        this.updatedAt = updatedAt;
    }

    public Date getPublishedAt() {
        return publishedAt;
    }

    public void setPublishedAt(Date publishedAt) {
        this.publishedAt = publishedAt;
    }
}


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.tutorialspoint.hibernate.pojoAnnotation;

import javax.persistence.Column;
import javax.persistence.Embeddable;

@Embeddable
public class PhoneNumberAnnot {

	@Column(name = "AREA_CODE")
    private int areaCode = 0;

	@Column(name = "PHONE_NUMBER", length=10)
    private String phoneNumber;

	@Column(name = "NAME")
    private String name = null;

	public PhoneNumberAnnot() {
	}

	public PhoneNumberAnnot(int areaCode, String phoneNumber, String name) {
		this.areaCode = areaCode;
		this.phoneNumber = phoneNumber;
		this.name = name;
	}

	public int getAreaCode() {
		return areaCode;
	}
	public void setAreaCode(int areaCode) {
		this.areaCode = areaCode;
	}

	public String getPhoneNumber() {
		return phoneNumber;
	}

	public void setPhoneNumber(String phoneNumber) {
		this.phoneNumber = phoneNumber;
	}

	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}


text:
"""Tests for Adadelta Optimizer."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import tensorflow.python.platform

import numpy as np
from six.moves import xrange  # pylint: disable=redefined-builtin
import tensorflow as tf

class AdadeltaOptimizerTest(tf.test.TestCase):

  def testBasic(self):
    with self.test_session():
      var0 = tf.Variable([1.0, 2.0])
      var1 = tf.Variable([3.0, 4.0])
      grads0 = tf.constant([0.1, 0.1])
      grads1 = tf.constant([0.01, 0.01])
      lr = 1.0
      rho = 0.95
      epsilon = 1e-8

      adadelta_opt = tf.train.AdadeltaOptimizer(lr, rho=rho, epsilon=epsilon)
      adadelta_update = adadelta_opt.apply_gradients(zip([grads0, grads1], [var0, var1]))
      tf.initialize_all_variables().run()

      # Check we have slots
      self.assertEqual(["accum", "accum_update"],
                       adadelta_opt.get_slot_names())
      slot0 = adadelta_opt.get_slot(var0, "accum")
      self.assertEquals(slot0.get_shape(), var0.get_shape())
      self.assertFalse(slot0 in tf.trainable_variables())

      slot0_update = adadelta_opt.get_slot(var0, "accum_update")
      self.assertEquals(slot0_update.get_shape(), var0.get_shape())
      self.assertFalse(slot0_update in tf.trainable_variables())

      slot1 = adadelta_opt.get_slot(var1, "accum")
      self.assertEquals(slot1.get_shape(), var1.get_shape())
      self.assertFalse(slot1 in tf.trainable_variables())

      slot1_update = adadelta_opt.get_slot(var1, "accum_update")
      self.assertEquals(slot1_update.get_shape(), var1.get_shape())
      self.assertFalse(slot1_update in tf.trainable_variables())

      # Fetch params to validate initial values
      self.assertAllClose([1.0, 2.0], var0.eval())
      self.assertAllClose([3.0, 4.0], var1.eval())

      adadelta_update.run()

      # Check that the accumulators have been updated.
      grad = 0.1
      accum = 0
      accum_update = 0

      accum = accum * rho + (grad**2) * (1 - rho)
      update1 = np.sqrt(accum_update + epsilon) * (1. / np.sqrt(accum + epsilon)) * grad
      accum_update = accum_update * rho + (update1**2) * (1.0 - rho)

      self.assertAllClose(np.array([accum, accum]), slot0.eval())
      self.assertAllClose(np.array([accum_update, accum_update]), slot0_update.eval())

      # Check that the parameters have been updated.
      self.assertAllClose(np.array([1.0 - update1 * lr,
                                    2.0 - update1 * lr]),
                          var0.eval(), rtol=1e-3)

      self.assertAllClose(np.array([3.0 - update1 * lr,
                                    4.0 - update1 * lr]),
                          var1.eval(), rtol=1e-3)

      # Step 2: the momentum accumulators contain the previous update.
      accum =  accum * rho + (grad**2) * (1 - rho)
      update2 = ((accum_update + epsilon)**0.5) * (1. / (accum + epsilon)**0.5) * grad
      accum_update = accum_update * rho + (update2**2) * (1.0 - rho)

      adadelta_update.run()

      # Check that the momentum accumulators have been updated.
      self.assertAllClose(np.array([accum, accum]), slot0.eval())
      self.assertAllClose(np.array([accum_update, accum_update]), slot0_update.eval())

      # Check that the parameters have been updated.
      self.assertAllClose(
          np.array([1.0 - update1 - update2,
                    2.0 - update1 - update2]),
          var0.eval(), rtol=1e-3)

      self.assertAllClose(np.array([3.0 - update1 - update2,
                                    4.0 - update1 - update2]),
                          var1.eval(), rtol=1e-3)

if __name__ == "__main__":
  tf.test.main()


text:
namespace button_drag_utils {

// Maximum width of the link drag image in pixels.
static const int kLinkDragImageMaxWidth = 200;

void SetURLAndDragImage(const GURL& url,
                        const string16& title,
                        const gfx::ImageSkia& icon,
                        ui::OSExchangeData* data,
                        views::Widget* widget) {
  DCHECK(url.is_valid() && data);

  data->SetURL(url, title);

  // Create a button to render the drag image for us.
  views::TextButton button(NULL,
                           title.empty() ? UTF8ToUTF16(url.spec()) : title);
  button.set_max_width(kLinkDragImageMaxWidth);
  if (icon.isNull()) {
    button.SetIcon(*ui::ResourceBundle::GetSharedInstance().GetImageNamed(
                   IDR_DEFAULT_FAVICON).ToImageSkia());
  } else {
    button.SetIcon(icon);
  }
  gfx::Size prefsize = button.GetPreferredSize();
  button.SetBounds(0, 0, prefsize.width(), prefsize.height());

  // Render the image.
  scoped_ptr<gfx::Canvas> canvas(
      views::GetCanvasForDragImage(widget, prefsize));
  button.PaintButton(canvas.get(), views::TextButton::PB_FOR_DRAG);
  drag_utils::SetDragImageOnDataObject(*canvas, prefsize,
      gfx::Vector2d(prefsize.width() / 2, prefsize.height() / 2), data);
}

}  // namespace button_drag_utils


text:
namespace DM {

static const bool kGPUDisabled = false;

static inline SkSurface* NewGpuSurface(GrContextFactory* grFactory,
                                       GrContextFactory::GLContextType type,
                                       GrGLStandard gpuAPI,
                                       SkImageInfo info,
                                       int samples) {
    return SkSurface::NewRenderTarget(grFactory->get(type, gpuAPI), info, samples, NULL);
}

}  // namespace DM

#else// !SK_SUPPORT_GPU

// Ganesh is not available.  Fake it.

enum GrGLStandard {
    kNone_GrGLStandard,
    kGL_GrGLStandard,
    kGLES_GrGLStandard
};

class GrContextFactory {
public:
    typedef int GLContextType;

    static const GLContextType kANGLE_GLContextType  = 0,
                               kDebug_GLContextType  = 0,
                               kMESA_GLContextType   = 0,
                               kNVPR_GLContextType   = 0,
                               kNative_GLContextType = 0,
                               kNull_GLContextType   = 0;
    void destroyContexts() {}

    void abandonContexts() {}
};

namespace DM {

static const bool kGPUDisabled = true;

static inline SkSurface* NewGpuSurface(GrContextFactory*,
                                       GrContextFactory::GLContextType,
                                       GrGLStandard,
                                       SkImageInfo,
                                       int) {
    return NULL;
}

}  // namespace DM

#endif//SK_SUPPORT_GPU

#endif//DMGpuSupport_DEFINED


text:
package org.jtwig.translate.locale;

import java.util.Locale;

public class JavaLocaleResolver implements LocaleResolver {
    @Override
    public Locale resolve(String localeIdentifier) {
        return Locale.forLanguageTag(localeIdentifier);
    }
}


text:
/*
 * Copyright (c) 2008 Travis Geiselbrecht
 *
 * Use of this source code is governed by a MIT-style
 * license that can be found in the LICENSE file or at
 * https://opensource.org/licenses/MIT
 */
#include <string.h>
#include <sys/types.h>

int
strcmp(char const *cs, char const *ct) {
    signed char __res;

    while (1) {
        if ((__res = *cs - *ct++) != 0 || !*cs++)
            break;
    }

    return __res;
}


text:
// The MIT License (MIT)

// Copyright (c) 2013 lailongwei<lailongwei@126.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#ifndef __PYLLBC_COMM_COMM_H__
#define __PYLLBC_COMM_COMM_H__

#include "pyllbc/common/Common.h"
#include "pyllbc/core/Core.h"

/**
 * Initialize the communication module.
 */
LLBC_HIDDEN void pyllbc_InitComm();

/**
 * Destroy the communication module.
 */
LLBC_HIDDEN void pyllbc_DestroyComm();

/**
 * Add all communication module methods to python.
 */
LLBC_HIDDEN void pyllbc_AddCommMethods();

/**
 * Ad all communication objs to python.
 */
LLBC_HIDDEN void pyllbc_AddCommObjs();

#endif // !__PYLLBC_COMM_COMM_H__


text:
using System;
using System.IO;
using System.Threading.Tasks;
using Autofac.Extras.FakeItEasy;
using Elasticsearch.Net.Connection;
using Elasticsearch.Net.Tests.Unit.Stubs;
using FakeItEasy;
using FluentAssertions;
using NUnit.Framework;

namespace Elasticsearch.Net.Tests.Unit.Exceptions
{
	[TestFixture]
	public class ExceptionsBubbleTests
	{
		private readonly ConnectionConfiguration _connectionConfig = new ConnectionConfiguration()
			.MaximumRetries(0);

		[Test]
		public void CallThrowsHardException_ShouldBubbleToCallee()
		{
			using (var fake = new AutoFake(callsDoNothing: true))
			{
				fake.Provide<IConnectionConfigurationValues>(_connectionConfig);
				FakeCalls.ProvideDefaultTransport(fake);

				var getCall = FakeCalls.GetSyncCall(fake);
				getCall.Throws<Exception>();

				var client = fake.Resolve<ElasticsearchClient>();

				Assert.Throws<Exception>(() => client.Info());
				getCall.MustHaveHappened(Repeated.Exactly.Once);

			}
		}

		[Test]
		public void Async_CallThrowsHardException_ShouldBubbleToCallee()
		{
			using (var fake = new AutoFake(callsDoNothing: true))
			{
				fake.Provide<IConnectionConfigurationValues>(_connectionConfig);
				FakeCalls.ProvideDefaultTransport(fake);
				var getCall = FakeCalls.GetCall(fake);

				//return a started task that throws
				getCall.Throws((c)=> new Exception("hard exception!"));

				var client = fake.Resolve<ElasticsearchClient>();

				var e = Assert.Throws<Exception>(async () => await client.InfoAsync());
				e.Message.Should().Be("hard exception!");
				getCall.MustHaveHappened(Repeated.Exactly.Once);

			}
		}

		[Test]
		public void Async_CallThrowsSoftException_ShouldBubbleToCallee()
		{
			using (var fake = new AutoFake(callsDoNothing: true))
			{
				fake.Provide<IConnectionConfigurationValues>(_connectionConfig);
				FakeCalls.ProvideDefaultTransport(fake);
				var getCall = FakeCalls.GetCall(fake);

				//return a started task that throws
				Func<ElasticsearchResponse<Stream>> badTask = () => { throw new Exception("soft exception."); };
				var t = new Task<ElasticsearchResponse<Stream>>(badTask);
				t.Start();
				getCall.Returns(t);

				var client = fake.Resolve<ElasticsearchClient>();

				var e = Assert.Throws<Exception>(async () => await client.InfoAsync());
				e.Message.Should().Be("soft exception.");
				getCall.MustHaveHappened(Repeated.Exactly.Once);

			}
		}

	}
}


text:
using System.Collections.Generic;

namespace BibliographicSystem.Models
{
    /// <summary>
    /// class that represents an article from the microsoft academic
    /// </summary>
    public class MicrosoftAcademicArticle
    {
        public string Title { get; set; }
        public string Description { get; set; }
        public int Year { get; set; }
        public int CitationCount { get; set; }
        public string ExtendedMetadata { get; set; }
        public List<string> References { get; set; }
        public List<Author> Authors { get; set; }
    }

    /// <summary>
    /// class that represents author of article
    /// </summary>
    public class Author
    {
        public string AuthorName { get; set; }
        public long AuthorId { get; set; }
    }
}


text:
package org.duncavage.recyclerviewdemo;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;

import org.duncavage.recyclerviewdemo.fragments.ListPagerFragment;

/**
 * Created by brett on 5/21/15.
 */
public class MainActivity extends AppCompatActivity {
    private Toolbar toolbar;
    private ImageButton toolbarButtonRight;

    public void setToolbarRightButtonClickListener(View.OnClickListener listener) {
        if (toolbarButtonRight == null) {
            toolbarButtonRight = (ImageButton)toolbar.findViewById(R.id.button_right);
        }
        toolbarButtonRight.setOnClickListener(listener);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        toolbar = (Toolbar)findViewById(R.id.toolbar);
        toolbar.setTitle(R.string.app_name);
        toolbar.setTitleTextColor(getResources().getColor(R.color.dark_text));
    }
}


text:
/**
 * ManageClassServlet.java
 * Manage classes in specified school.
 */
package com.ajh.futurestar.web.servlet;

import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.json.JSONArray;
import org.json.JSONObject;

import com.ajh.futurestar.web.common.DbVendor;
import com.ajh.futurestar.web.common.Request;
import com.ajh.futurestar.web.common.RetCode;
import com.ajh.futurestar.web.common.RetInfo;
import com.ajh.futurestar.web.common.ReturnX;
import com.ajh.futurestar.web.utils.Util;
import com.ajh.futurestar.web.utils.Util.DbConnectionAndStatementWrapper;

/**
 * @author Andy Jiang H
 *
 */
@WebServlet("/classmgmt.do")
public class BizClassMgmtServlet extends ManageExServlet {

	/**
	 *
	 */
	private static final long serialVersionUID = 8273769336541772993L;
	private String strSchoolId = null;

	@Override
	protected void generatePageBody(PrintWriter out, ReturnX result) {
		JSONObject obj = new JSONObject();
		obj.put("actionx", result.actionx); // String
		obj.put("retcode", result.retcode.ordinal()); // Convert enumeration to integer.
		obj.put("retinfo", result.retinfo); // String
		obj.put("retobjx", result.retobjx); // JSON object
		obj.put("curuser", result.curuser); // JSON object
		out.println(obj.toString());
	}

	@Override
	protected void doBusiness(HttpServletRequest req, HttpServletResponse rsp, ReturnX retx) {
		HttpSession session = req.getSession();
		Connection conn = null;
		Statement stmt = null;

//		if (!Util.checkAndSetUserLoginInfo(session, retx)) {
//			return;
//		}
//
//		Connection conn = null;
//		DbConnectionWrapper wrapperConn = Util.getDbConnection(retx);
//		if (wrapperConn.ok) {
//			conn = wrapperConn.conn;
//		} else {
//			return;
//		}
//
//		Statement stmt = null;
//		DbStatementWrapper wrapperStmt = Util.getDbStatement(conn, retx);
//		if (wrapperStmt.ok) {
//			stmt = wrapperStmt.stmt;
//		} else {
//			return;
//		}

		DbConnectionAndStatementWrapper wrapperDbMgmt = Util.checkPreconditionBeforeDoingBusiness(session, retx);
		if (wrapperDbMgmt.ok) {
			conn = wrapperDbMgmt.conn;
			stmt = wrapperDbMgmt.stmt;
		} else {
			return;
		}

		// DO NOT return when performing action.
		String strAction = req.getParameter(Request.PARAM_ACTION);
		if (strAction == null || strAction.equals("")) {
			retx.retcode  = RetCode.RETCODE_KO_MANAGE_CLASS_NULL_ACTION;
			retx.retinfo += RetInfo.RETINFO_REQ_PARAM_NULL_ACTION;
		} else {
			retx.actionx += strAction;
			if (strAction.equalsIgnoreCase(Request.VALUE_ACTION_SELECT)) {
				try {
					doActionSelect(conn, stmt, req, retx);
				} catch (SQLException e) {
					e.printStackTrace();
					retx.retcode  = RetCode.RETCODE_KO_MANAGE_CLASS_SELECT_FAILED;
					retx.retinfo += e.getMessage();
				}
			} else if (strAction.equalsIgnoreCase(Request.VALUE_ACTION_CREATE)) {
				try {
					doActionCreate(conn, stmt, req, retx);
				} catch (SQLException e) {
					e.printStackTrace();
					retx.retcode  = RetCode.RETCODE_KO_MANAGE_CLASS_CREATE_FAILED;
					retx.retinfo += e.getMessage();
				}
			} else {
				// TODO
			}
		}

		Util.closeDbConnectionAndStatement(conn, stmt); // No need to update return code when exception occurs.
	}

	private void doActionCreate(Connection conn, Statement stmt, HttpServletRequest req, ReturnX retx)
		throws SQLException {
		String strSchoolId = req.getParameter(Request.PARAM_CLASS_SCHOOLID);
		String strName = req.getParameter(Request.PARAM_CLASS_NAME);
		String strEnrollment = req.getParameter(Request.PARAM_CLASS_ENROLLMENT);

		if (strSchoolId == null || strSchoolId.equals("")) {
			retx.retcode  = RetCode.RETCODE_KO_MANAGE_CLASS_NULL_SCHOOLID;
			retx.retinfo += RetInfo.RETINFO_REQ_PARAM_NULL_CLASS_SCHOOLID;
			return;
		}

		if (strName == null || strName.equals("")) {
			retx.retcode  = RetCode.RETCODE_KO_MANAGE_CLASS_NULL_NAME;
			retx.retinfo += RetInfo.RETINFO_REQ_PARAM_NULL_CLASS_NAME;
			return;
		}

		if (strEnrollment == null || strEnrollment.equals("")) {
			retx.retcode  = RetCode.RETCODE_KO_MANAGE_CLASS_NULL_ENROLLMENT;
			retx.retinfo += RetInfo.RETINFO_REQ_PARAM_NULL_CLASS_ENROLLMENT;
			return;
		}

		// TODO - check enrollment format.

		String strInsert = "insert into T_CLASS_FROM_SCHOOL_" + strSchoolId;
		strInsert += "(NAME, ENROLLMENT) values(";
		strInsert += "'" + strName + "', ";
		strInsert += "'" + strEnrollment + "'";
		strInsert += ");";

		stmt.executeUpdate(strInsert);

		conn.commit();
	}

	private void doActionSelect(Connection conn, Statement stmt, HttpServletRequest req, ReturnX retx)
		throws SQLException {
		//
		// Get parameters.
		//
		String strSchoolId = req.getParameter("schoolid");
		if (strSchoolId == null || strSchoolId.equals("")) {
			retx.retcode  = RetCode.RETCODE_KO_MANAGE_CLASS_NULL_SCHOOLID;
			retx.retinfo += RetInfo.RETINFO_REQ_PARAM_NULL_CLASS_SCHOOLID;
			return;
		} else {
			this.strSchoolId = strSchoolId;
		}

		int nMode = Request.VALUE_ACTION_SELECT_MODE_BASEID_AND_INCREMENT;
		String strMode = req.getParameter(Request.PARAM_ACTION_SELECT_MODE);
		if (strMode != null) {
			nMode = Integer.parseInt(strMode);
		}

		String strBaseId = req.getParameter(Request.PARAM_ACTION_SELECT_BASEID);
		if (strBaseId == null) {
			strBaseId = "" + Request.VALUE_ACTION_SELECT_BASEID_DEFAULT;
		}

		int nRange = Request.VALUE_ACTION_SELECT_RANGE_DEFAULT;
		String strRange = req.getParameter(Request.PARAM_ACTION_SELECT_RANGE);
		if (strRange != null) {
			nRange = Integer.parseInt(strRange);
		}

		String strClassName = req.getParameter(Request.PARAM_CLASS_NAME);

		int nGoes = Request.VALUE_ACTION_SELECT_GOES_DOWN; // Default to goes down.
		String strGoes = req.getParameter(Request.PARAM_ACTION_SELECT_GOES);
		if (strGoes != null && strGoes.equalsIgnoreCase("up")) {
			nGoes = Request.VALUE_ACTION_SELECT_GOES_UP;
		}

		String strFromId = req.getParameter(Request.PARAM_ACTION_SELECT_FROMID);
		if (strFromId == null) {
			strFromId = "0";
		}
		String strToId = req.getParameter(Request.PARAM_ACTION_SELECT_TOID);
		if (strToId == null) {
			strToId = "0";
		}

		//
		// Construct query SQL string.
		//
		String strQuery = "";
		switch (nMode) {
		case Request.VALUE_ACTION_SELECT_MODE_BASEID_AND_INCREMENT:
			strQuery = composeSqlStrSelect(DbVendor.DB_SQLITE, strBaseId, nRange, strClassName, nGoes);
			break;
		case Request.VALUE_ACTION_SELECT_MODE_FROM_TO:
			strQuery = composeSqlStrSelect(DbVendor.DB_SQLITE, strFromId, strToId);
			break;
		default:
			break;
		}

		JSONObject retobjx = new JSONObject();
//		retobjx.put("schoolid", strSchoolId);

		// Query from view instead of table.
//		String strQuery = "select * FROM V_CLASS_FROM_SCHOOL_" + strSchoolId;
		getServletContext().log(strQuery);
		ResultSet rsClassList = stmt.executeQuery(strQuery);
		JSONArray arrayClass = new JSONArray();
		while (rsClassList.next()) {
			JSONObject obj = new JSONObject(); // Item in array.
			obj.put("ID", rsClassList.getString("ID"));
			obj.put("NAME", rsClassList.getString("NAME"));
			obj.put("ENROLLMENT", rsClassList.getString("ENROLLMENT"));
			obj.put("CREATION", rsClassList.getString("CREATION"));
			arrayClass.put(obj);
		}

		retobjx.put("schoolid", strSchoolId);
		retobjx.put("classes", arrayClass);

		retx.retobjx = retobjx;

		rsClassList.close();

	}

	private String composeSqlStrSelectAllFields()
	{
		// Query from view instead of table.
		return "select * FROM V_CLASS_FROM_SCHOOL_" + this.strSchoolId;
	}

	private String composeSqlStrSelect(DbVendor vendor, String baseid, int range, String classname, int goes)
	{
		String sql = composeSqlStrSelectAllFields();
		if (goes == Request.VALUE_ACTION_SELECT_GOES_DOWN) {
			sql += " where CREATION > '" + baseid + "'";
			if (classname != null && !classname.equals("")) {
//				getServletContext().log("School name is " + schoolname);
				sql += " and NAME like '%" + classname + "%'";
			}
			sql += " order by CREATION asc limit " + range + ";";
		} else {
			sql += " where CREATION in " +
				"( select CREATION from V_CLASS_FROM_SCHOOL_" + this.strSchoolId + " where CREATION < '" + baseid + "'";
			if (classname != null && !classname.equals("")) {
//				getServletContext().log("School name is " + schoolname);
				sql += " and NAME like '%" + classname + "%'";
			}
			sql += " order by CREATION desc limit " + range +");";
		}

		return sql;
	}

	private String composeSqlStrSelect(DbVendor vendor, String fromid, String toid)
	{
		String sql = composeSqlStrSelectAllFields();
		sql += " where CREATION >= '" + fromid + "' AND CREATION <= '" + toid + "';";

		return sql;
	}
}


text:
var app = angular.module('projects', ['ngMaterial', 'ngRoute']);
  app.controller('proCtrl', function($scope) {});
  app.config(function ($routeProvider) {
    $routeProvider
    .when("/", { templateUrl : "index.html" })
    .when("/pomodoro", { templateUrl : "./pomodoro/index.html" })
    .when("/simongame", { templateUrl : "./simongame/index.html" })
    .when("/tctactoe", { templateUrl : "./tictactoe/index.html" })
    .when("/calculator", { templateUrl : "./calculator/index.html" })
    .when("/weather", { templateUrl : "./weather/index.html" })
    .when("/twitchstatus", { templateUrl : "./twitchstatus/index.html" })
    .when("/quoter", { templateUrl : "./quoter/index.html" })
    .when("/wikisearch", { templateUrl : "./wikisearch/index.html" })
    .otherwise({ templateUrl : "index.html"});
  });


text:
"""Tests `imitation.rewards.reward_function` and `imitation.rewards.serialize`."""

import numpy as np
import pytest

from imitation.rewards import reward_function, serialize

OBS = np.random.randint(0, 10, (64, 100))
ACTS = NEXT_OBS = OBS
DONES = np.zeros(64, dtype=np.bool_)

def _funky_reward_fn(obs, act, next_obs, done):
    """Returns consecutive reward from 1 to batch size `len(obs)`."""
    # give each environment number from 1 to num_envs
    return (np.arange(len(obs))).astype("float32")

def _invalid_reward_fn(obs, act, next_obs, done):
    """Returns rewards for lesser number of observations."""
    return (np.arange(len(obs) - 1)).astype("float32")

def test_reward_fn_override():
    # test inheriting class from RewardFn works
    class InheritedFunkyReward(reward_function.RewardFn):
        """A reward inherited from RewardFn."""

        def __init__(self):
            super().__init__()

        def __call__(self, obs, act, next_obs, steps=None):
            """Returns consecutive reward from 0 to batch size -1 (`len(obs)` - 1)."""
            return (np.arange(len(obs))).astype("float32")

    inherited_funky_reward_fn = InheritedFunkyReward()
    inherited_funky_reward_fn(OBS, ACTS, NEXT_OBS)

def test_validate_rewardfn_class():
    validated_reward_fn = serialize.ValidateRewardFn(_funky_reward_fn)
    validated_reward_fn(OBS, ACTS, NEXT_OBS, DONES)

    with pytest.raises(AssertionError):
        invalidated_reward_fn = serialize.ValidateRewardFn(_invalid_reward_fn)
        invalidated_reward_fn(OBS, ACTS, NEXT_OBS, DONES)


text:
import os
import unittest

import pytest
import azure.mgmt.compute
from azure.profiles import ProfileDefinition
from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy

AZURE_LOCATION = 'eastus'

class TestMgmtComputeMultiVersion(AzureMgmtRecordedTestCase):

    def setup_method(self, method):
        # self.re_replacer.register_pattern_pair(
        #   '\"accessSAS\": \"https://.*\"',
        #   '\"accessSAS\": \"FakeUrl\"'
        # )
        self.mgmt_client = self.create_mgmt_client(
            azure.mgmt.compute.ComputeManagementClient
        )
        self.mgmt_client.profile = ProfileDefinition({
            self.mgmt_client._PROFILE_TAG: {
                None: "2019-07-01",
                'availability_sets': '2019-07-01',
                'dedicated_host_groups': '2019-07-01',
                'dedicated_hosts': '2019-07-01',
                'disk_encryption_sets': '2019-11-01',
                'disks': '2019-03-01',  # test old version
                'images': '2019-07-01',
                'log_analytics': '2019-07-01',
                'operations': '2019-07-01',
                'proximity_placement_groups': '2019-07-01',
                'resource_skus': '2019-04-01',
                'snapshots': '2019-11-01',
                'usage': '2019-07-01',
                'virtual_machine_extension_images': '2019-07-01',
                'virtual_machine_extensions': '2019-07-01',
                'virtual_machine_images': '2019-07-01',
                'virtual_machine_run_commands': '2019-07-01',
                'virtual_machine_scale_set_extensions': '2019-07-01',
                'virtual_machine_scale_set_rolling_upgrades': '2019-07-01',
                'virtual_machine_scale_set_vm_extensions': '2019-07-01',
                'virtual_machine_scale_set_vms': '2019-07-01',
                'virtual_machine_scale_sets': '2019-07-01',
                'virtual_machine_sizes': '2019-07-01',
                'virtual_machines': '2019-07-01',
            }},
            self.mgmt_client._PROFILE_TAG + " test"
        )

    @pytest.mark.skipif(os.getenv('AZURE_TEST_RUN_LIVE') not in ('true', 'yes'), reason='only run live test')
    @RandomNameResourceGroupPreparer(location=AZURE_LOCATION)
    @recorded_by_proxy
    def test_compute_disks_multi(self, resource_group):

        DISK_NAME = self.get_resource_name("disknamex")

        # Create an empty managed disk.[put]
        BODY = {
          "location": "eastus",
          "creation_data": {
            "create_option": "Empty"
          },
          "disk_size_gb": "200"
        }
        result = self.mgmt_client.disks.begin_create_or_update(resource_group.name, DISK_NAME, BODY)
        result = result.result()

        # Get information about a managed disk.[get]
        result = self.mgmt_client.disks.get(resource_group.name, DISK_NAME)

        # List all managed disks in a resource group.[get]
        result = self.mgmt_client.disks.list_by_resource_group(resource_group.name)

        # List all managed disks in a subscription.[get]
        result = self.mgmt_client.disks.list()

        # Update disk.[patch]
        BODY = {
          "disk_size_gb": "200"
        }
        result = self.mgmt_client.disks.begin_update(resource_group.name, DISK_NAME, BODY)
        result = result.result()

        # Grant acess disk
        BODY = {
          "access": "Read",
          "duration_in_seconds": "1800"
        }
        result = self.mgmt_client.disks.begin_grant_access(resource_group.name, DISK_NAME, BODY)
        result = result.result()

         # Revoke access disk
        result = self.mgmt_client.disks.begin_revoke_access(resource_group.name, DISK_NAME)
        result = result.result()

        # Delete disk
        result = self.mgmt_client.disks.begin_delete(resource_group.name, DISK_NAME)
        result = result.result()

class TestMgmtCompute(AzureMgmtRecordedTestCase):

    def setup_method(self, method):
        # self.re_replacer.register_pattern_pair(
        #   '\"accessSAS\": \"https://.*\"',
        #   '\"accessSAS\": \"FakeUrl\"'
        # )
        self.mgmt_client = self.create_mgmt_client(
            azure.mgmt.compute.ComputeManagementClient
        )
        if self.is_live:
            from azure.mgmt.keyvault import KeyVaultManagementClient
            self.keyvault_client = self.create_mgmt_client(
                KeyVaultManagementClient
            )
            # self.network_client = self.create_mgmt_client(
            #     azure.mgmt.network.NetworkManagementClient
            # )

    def create_key(self, group_name, location, key_vault, tenant_id, object_id):
        if self.is_live:
            result = self.keyvault_client.vaults.begin_create_or_update(
                group_name,
                key_vault,
                {
                  'location': location,
                  'properties': {
                    'sku': {
                      'family': "A",
                      'name': 'standard'
                    },
                    'tenant_id': tenant_id,
                    "access_policies": [
                      {
                        "tenant_id": tenant_id,
                        "object_id": object_id,
                        "permissions": {
                          "keys": [
                            "encrypt",
                            "decrypt",
                            "wrapKey",
                            "unwrapKey",
                            "sign",
                            "verify",
                            "get",
                            "list",
                            "create",
                            "update",
                            "import",
                            "delete",
                            "backup",
                            "restore",
                            "recover",
                            "purge"
                          ]
                        }
                      }
                    ],
                    'enabled_for_disk_encryption': True,
                  }
                }
            ).result()
            vault_url = result.properties.vault_uri
            vault_id = result.id

            from azure.keyvault.keys import KeyClient
            credentials = self.settings.get_azure_core_credentials()
            key_client = KeyClient(vault_url, credentials)

            # [START create_key]
            from dateutil import parser as date_parse
            expires_on = date_parse.parse("2050-02-02T08:00:00.000Z")

            key = key_client.create_key(
              "testkey",
              "RSA",
              size=2048,
              expires_on=expires_on
            )
            return (vault_id, key.id)
        else:
            return ('000', '000')

    @unittest.skip("The KEY_VAULT_NAME need artificially generated,skip for now")
    @RandomNameResourceGroupPreparer(location=AZURE_LOCATION)
    @recorded_by_proxy
    def test_compute_disk_encryption(self, resource_group):
        SUBSCRIPTION_ID = self.get_settings_value("SUBSCRIPTION_ID")
        TENANT_ID = self.settings.TENANT_ID
        CLIENT_OID = self.settings.CLIENT_OID if self.is_live else "000"
        RESOURCE_GROUP = resource_group.name
        KEY_VAULT_NAME = self.get_resource_name("keyvaultxmmkyxy")
        DISK_ENCRYPTION_SET_NAME = self.get_resource_name("diskencryptionset")

        VAULT_ID, KEY_URI = self.create_key(RESOURCE_GROUP, AZURE_LOCATION, KEY_VAULT_NAME, TENANT_ID, CLIENT_OID)

        # Create a disk encryption set.[put]
        BODY = {
          "location": "eastus",
          "identity": {
            "type": "SystemAssigned"
          },
          "active_key": {
            "source_vault": {
              # "id": "/subscriptions/" + SUBSCRIPTION_ID + "/resourceGroups/" + RESOURCE_GROUP + "/providers/Microsoft.KeyVault/vaults/" + VAULT_NAME + ""
              "id": VAULT_ID
            },
            # "key_url": "https://myvmvault.vault-int.azure-int.net/keys/{key}/{key_version}"
            "key_url": KEY_URI
          }
        }
        result = self.mgmt_client.disk_encryption_sets.begin_create_or_update(resource_group.name, DISK_ENCRYPTION_SET_NAME, BODY)
        result = result.result()

        # # Get information about a disk encryption set.[get]
        result = self.mgmt_client.disk_encryption_sets.get(resource_group.name, DISK_ENCRYPTION_SET_NAME)

        # List all disk encryption sets in a resource group.[get]
        result = self.mgmt_client.disk_encryption_sets.list_by_resource_group(resource_group.name)

        # List all disk encryption sets in a subscription.[get]
        result = self.mgmt_client.disk_encryption_sets.list()

        # Update a disk encryption set.[patch]
        BODY = {
          "active_key": {
            "source_vault": {
              # "id": "/subscriptions/" + SUBSCRIPTION_ID + "/resourceGroups/" + RESOURCE_GROUP + "/providers/Microsoft.KeyVault/vaults/" + VAULT_NAME + ""
              "id": VAULT_ID
            },
            "key_url": KEY_URI
            # "key_url": "https://myvmvault.vault-int.azure-int.net/keys/{key}/{key_version}"
          },
          "tags": {
            "department": "Development",
            "project": "Encryption"
          }
        }
        result = self.mgmt_client.disk_encryption_sets.begin_update(resource_group.name, DISK_ENCRYPTION_SET_NAME, BODY)
        result = result.result()

        # # Delete a disk encryption set.[delete]
        result = self.mgmt_client.disk_encryption_sets.begin_delete(resource_group.name, DISK_ENCRYPTION_SET_NAME)
        result = result.result()

    @pytest.mark.skipif(os.getenv('AZURE_TEST_RUN_LIVE') not in ('true', 'yes'), reason='only run live test')
    @RandomNameResourceGroupPreparer(location=AZURE_LOCATION)
    @recorded_by_proxy
    def test_compute_shot(self, resource_group):
        SUBSCRIPTION_ID = self.get_settings_value("SUBSCRIPTION_ID")
        RESOURCE_GROUP = resource_group.name
        DISK_NAME = self.get_resource_name("disknamex")
        SNAPSHOT_NAME = self.get_resource_name("snapshotx")
        IMAGE_NAME = self.get_resource_name("imagex")

        # Create an empty managed disk.[put]
        BODY = {
          "location": "eastus",
          "creation_data": {
            "create_option": "Empty"
          },
          "disk_size_gb": "200"
        }
        result = self.mgmt_client.disks.begin_create_or_update(resource_group.name, DISK_NAME, BODY)
        result = result.result()

        # Create a snapshot by copying a disk.
        BODY = {
          "location": "eastus",
          "creation_data": {
            "create_option": "Copy",
            "source_uri": "/subscriptions/" + SUBSCRIPTION_ID + "/resourceGroups/" + RESOURCE_GROUP + "/providers/Microsoft.Compute/disks/" + DISK_NAME
          }
        }
        result = self.mgmt_client.snapshots.begin_create_or_update(resource_group.name, SNAPSHOT_NAME, BODY)
        result = result.result()

        # Create a virtual machine image from a snapshot.[put]
        BODY = {
          "location": "eastus",
          "storage_profile": {
            "os_disk": {
              "os_type": "Linux",
              "snapshot": {
                "id": "subscriptions/" + SUBSCRIPTION_ID + "/resourceGroups/" + RESOURCE_GROUP + "/providers/Microsoft.Compute/snapshots/" + SNAPSHOT_NAME
              },
              "os_state": "Generalized"
            },
            "zone_resilient": False
          },
          "hyper_v_generation": "V1"  # TODO: required
        }
        result = self.mgmt_client.images.begin_create_or_update(resource_group.name, IMAGE_NAME, BODY)
        result = result.result()

        # Get information about a snapshot.[get]
        result = self.mgmt_client.snapshots.get(resource_group.name, SNAPSHOT_NAME)

        # Get information about a virtual machine image.[get]
        result = self.mgmt_client.images.get(resource_group.name, IMAGE_NAME)

        # List all virtual machine images in a resource group.[get]
        result = self.mgmt_client.images.list_by_resource_group(resource_group.name)

        # List all snapshots in a resource group.[get]
        result = self.mgmt_client.snapshots.list_by_resource_group(resource_group.name)

        # List all virtual machine images in a subscription.[get]
        result = self.mgmt_client.images.list()

        # List all snapshots in a subscription.[get]
        result = self.mgmt_client.snapshots.list()

        # Updates tags of an Image.[patch]
        BODY = {
          # "properties": {
          #   "source_virtual_machine": {
          #     "id": "/subscriptions/" + SUBSCRIPTION_ID + "/resourceGroups/" + RESOURCE_GROUP + "/providers/Microsoft.Compute/virtualMachines/" + VIRTUAL_MACHINE_NAME + ""
          #   },
          #   "hyper_vgeneration": "V1"
          # },
          "tags": {
            "department": "HR"
          }
        }
        result = self.mgmt_client.images.begin_update(resource_group.name, IMAGE_NAME, BODY)
        result = result.result()

        # Update a snapshot by
        BODY = {
          "creation_data": {
            "create_option": "Copy",
            "source_uri": "/subscriptions/" + SUBSCRIPTION_ID + "/resourceGroups/" + RESOURCE_GROUP + "/providers/Microsoft.Compute/disks/" + DISK_NAME
          }
        }
        result = self.mgmt_client.snapshots.begin_update(resource_group.name, SNAPSHOT_NAME, BODY)
        result = result.result()

        # Grant acess snapshot (TODO: need swagger file)
        BODY = {
          "access": "Read",
          "duration_in_seconds": "1800"
        }
        result = self.mgmt_client.snapshots.begin_grant_access(resource_group.name, SNAPSHOT_NAME, BODY)
        result = result.result()

        # Revoke access snapshot (TODO: need swagger file)
        result = self.mgmt_client.snapshots.begin_revoke_access(resource_group.name, SNAPSHOT_NAME)
        result = result.result()

        # Delete a image.  (TODO: need a swagger file)
        result = self.mgmt_client.images.begin_delete(resource_group.name, IMAGE_NAME)
        result = result.result()

        # Delete snapshot (TODO: need swagger file)
        result = self.mgmt_client.snapshots.begin_delete(resource_group.name, SNAPSHOT_NAME)
        result = result.result()

    @pytest.mark.skipif(os.getenv('AZURE_TEST_RUN_LIVE') not in ('true', 'yes'), reason='only run live test')
    @RandomNameResourceGroupPreparer(location=AZURE_LOCATION)
    @recorded_by_proxy
    def test_compute_disks(self, resource_group):

        DISK_NAME = self.get_resource_name("disknamex")

        # Create an empty managed disk.[put]
        BODY = {
          "location": "eastus",
          "creation_data": {
            "create_option": "Empty"
          },
          "disk_size_gb": "200"
        }
        result = self.mgmt_client.disks.begin_create_or_update(resource_group.name, DISK_NAME, BODY)
        result = result.result()

        # Get information about a managed disk.[get]
        result = self.mgmt_client.disks.get(resource_group.name, DISK_NAME)

        # List all managed disks in a resource group.[get]
        result = self.mgmt_client.disks.list_by_resource_group(resource_group.name)

        # List all managed disks in a subscription.[get]
        result = self.mgmt_client.disks.list()

        # Update disk.[patch]
        BODY = {
          "disk_size_gb": "200"
        }
        result = self.mgmt_client.disks.begin_update(resource_group.name, DISK_NAME, BODY)
        result = result.result()

        # Grant acess diski
        BODY = {
          "access": "Read",
          "duration_in_seconds": "1800"
        }
        result = self.mgmt_client.disks.begin_grant_access(resource_group.name, DISK_NAME, BODY)
        result = result.result()

         # Revoke access disk
        result = self.mgmt_client.disks.begin_revoke_access(resource_group.name, DISK_NAME)
        result = result.result()

        # Delete disk
        result = self.mgmt_client.disks.begin_delete(resource_group.name, DISK_NAME)
        result = result.result()


text:
__[Documentation](http://xsc.github.io/claro/)__ | __[Guides](doc)__

__claro__ is a library that allows you to streamline your data access, providing
powerful optimisations and abstractions along the way.

[![Build Status](https://travis-ci.org/xsc/claro.svg?branch=master)](https://travis-ci.org/xsc/claro)
[![Clojars Artifact](https://img.shields.io/clojars/v/claro.svg)](https://clojars.org/claro)
[![codecov](https://codecov.io/gh/xsc/claro/branch/master/graph/badge.svg)](https://codecov.io/gh/xsc/claro)

It is inspired by [muse][muse] and heavily influenced by [GraphQL][graphql].

claro requires Clojure ≥ 1.7.0.

[muse]: https://github.com/kachayev/muse
[graphql]: http://graphql.org/

## Features

claro is designed to be flexible and extensible. It'll make your data access
more elegant, efficient and testable, providing things like:

- __batched resolution__ of similar entities,
- automatic __caching__ of already known resolution results,
- __engine middlewares__ to hook into the resolution logic, allowing e.g.
  generic cache or circuit breaker implementations,
- pluggable __resolution strategies__ in the form of `Resolvable` selectors,
- an exchangeable __deferred implementation__, defaulting to
  [manifold][manifold],
- and pre-built middlewares for __data source mocking__, introspection and
  result transformation.

[manifold]: https://github.com/ztellman/manifold

## Quickstart

Data access is defined within records implementing the `Resolvable` interface.
Note that they can always produce more resolvables:

```clojure
(require '[claro.data :as data]
         '[manifold.deferred :as d])

(defrecord Person [id]
  data/Resolvable
  (resolve! [_ env]
    (d/future
      (fetch-person! (:db env) id)))
  data/Transform
  (transform [_ {:keys [friend-ids] :as person}]
    (assoc person :friends (map #(Person. %) friend-ids))))
```

Blindly resolving an infinite tree like this is usually not a good idea – but
claro offers _tree projections_ you can use to describe abstract transformations
of infinite structures:

```clojure
(require '[claro.projection :as projection])

(def person-with-friend-names
  {:id      projection/leaf
   :name    projection/leaf
   :friends [(projection/extract :name)]})
```

And here we go:

```clojure
(require '[claro.engine :as engine])

(engine/run!!
  (-> (->Person 1)
      (projection/apply person-with-friend-names)))
;; => {:id 1, :name "Sherlock Holmes", :friends ["Dr. Watson", "Ms. Hudson"]}
```

## Related Projects

| Library | Description |
|:------- |:----------- |
|[alumbra][alumbra]|GraphQL implementation on top of claro|
|[claro.circuit-breaker][claro-cb]|Circuit-breaker middleware based on [resilience4j][r4j]|

Feel free to open a pull request to add your project to this table.

[alumbra]: https://github.com/alumbra/alumbra
[claro-cb]:https://github.com/xsc/claro.circuit-breaker
[r4j]: https://github.com/resilience4j/resilience4j

## Documentation

1. [Basic Resolution](doc/00-basics.md)
2. [Projections](doc/01-projection.md)
3. [Advanced Projections](doc/02-advanced-projection.md)
4. [Engine](doc/03-engine.md)
5. [Testing & Debugging](doc/04-testing-and-debugging.md)
6. [Implementation Notes](doc/99-notes.md)

All these topics are also available in claro's [auto-generated
documentation][codox].

[codox]: http://xsc.github.io/claro/

## Contributing

Contributions are always welcome. Please take a look at the [Contribution
Guidelines](CONTRIBUTING.md) for a quick overview of how your changes can best
make it to master.

## License

```
MIT License

Copyright (c) 2015-2017 Yannick Scherer

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```


text:
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Spanners</title>
    <link>https://spanners.github.io/categories/test/index.xml</link>
    <description>Recent content on Spanners</description>
    <generator>Hugo -- gohugo.io</generator>
    <language>en-gb</language>
    <copyright>Released under the MIT license</copyright>
    <atom:link href="https://spanners.github.io/categories/test/index.xml" rel="self" type="application/rss+xml" />

    <item>
      <title>Test post</title>
      <link>https://spanners.github.io/posts/test/</link>
      <pubDate>Sat, 29 Oct 2016 00:00:00 +0000</pubDate>

      <guid>https://spanners.github.io/posts/test/</guid>
      <description>

Test post!

Hi, this is a test post

Sub-heading!

I&rsquo;m using a program called Hugo to deploy my static website. The command is simply:

hugo

That&rsquo;s it.

See more on gohugo.io

</description>
    </item>

    <item>
      <title>Just another sample post</title>
      <link>https://spanners.github.io/posts/newest/</link>
      <pubDate>Sat, 29 Mar 2014 00:00:00 +0000</pubDate>

      <guid>https://spanners.github.io/posts/newest/</guid>
      <description>

First Heading

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, consequatur aspernatur omnis iste. Voluptates, id inventore ea natus ab sed amet ipsa ratione sunt dignissimos. Soluta illum aliquid repellendus recusandae.

Sub

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Optio, perferendis saepe voluptatem a nesciunt architecto voluptas deleniti dolor tempora quasi quidem odit rem fugit magnam minima quam dolores vel id?

Conclusion

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Corporis, numquam ipsa ad! Quasi, deleniti quae sint consequatur error corporis dicta inventore alias soluta dignissimos? Molestias, quia ab deserunt repellat ut.

</description>
    </item>

    <item>
      <title>First Post</title>
      <link>https://spanners.github.io/posts/oldest/</link>
      <pubDate>Thu, 27 Mar 2014 00:00:00 +0000</pubDate>

      <guid>https://spanners.github.io/posts/oldest/</guid>
      <description>

Sample Post 1

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Sub-heading

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Est, non, ratione, molestiae illo optio quia sequi id fuga natus nihil ad architecto dolor alias ex sunt iste aperiam eius itaque.

foo

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quo, neque, eveniet voluptate eos debitis illum qui nostrum eius maxime ratione assumenda suscipit impedit deserunt voluptatibus odio ducimus non. Ex, ratione.

</description>
    </item>

  </channel>
</rss>


text:
using System;
using System.Xml.Serialization;
using System.Collections.Generic;
using Aop.Api.Domain;

namespace Aop.Api.Response
{
    /// <summary>
    /// KoubeiMarketingToolIsvMerchantQueryResponse.
    /// </summary>
    public class KoubeiMarketingToolIsvMerchantQueryResponse : AopResponse
    {
        /// <summary>
        /// 商户信息列表
        /// </summary>
        [XmlArray("merchant_infos")]
        [XmlArrayItem("isv_merchant_info")]
        public List<IsvMerchantInfo> MerchantInfos { get; set; }

        /// <summary>
        /// 门店总量
        /// </summary>
        [XmlElement("shop_count")]
        public string ShopCount { get; set; }

        /// <summary>
        /// 门店详情列表信息
        /// </summary>
        [XmlArray("shop_summary_infos")]
        [XmlArrayItem("shop_summary_info")]
        public List<ShopSummaryInfo> ShopSummaryInfos { get; set; }
    }
}


text:
package com.amazonaws.services.simpleemail.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.simpleemail.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.StringUtils;

/**
 * SendEmailRequest Marshaller
 */

@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class SendEmailRequestMarshaller implements Marshaller<Request<SendEmailRequest>, SendEmailRequest> {

    public Request<SendEmailRequest> marshall(SendEmailRequest sendEmailRequest) {

        if (sendEmailRequest == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        Request<SendEmailRequest> request = new DefaultRequest<SendEmailRequest>(sendEmailRequest, "AmazonSimpleEmailService");
        request.addParameter("Action", "SendEmail");
        request.addParameter("Version", "2010-12-01");
        request.setHttpMethod(HttpMethodName.POST);

        if (sendEmailRequest.getSource() != null) {
            request.addParameter("Source", StringUtils.fromString(sendEmailRequest.getSource()));
        }

        {
            Destination destination = sendEmailRequest.getDestination();
            if (destination != null) {

                if (!destination.getToAddresses().isEmpty()
                        || !((com.amazonaws.internal.SdkInternalList<String>) destination.getToAddresses()).isAutoConstruct()) {
                    com.amazonaws.internal.SdkInternalList<String> toAddressesList = (com.amazonaws.internal.SdkInternalList<String>) destination
                            .getToAddresses();
                    int toAddressesListIndex = 1;

                    for (String toAddressesListValue : toAddressesList) {
                        if (toAddressesListValue != null) {
                            request.addParameter("Destination.ToAddresses.member." + toAddressesListIndex, StringUtils.fromString(toAddressesListValue));
                        }
                        toAddressesListIndex++;
                    }
                }

                if (!destination.getCcAddresses().isEmpty()
                        || !((com.amazonaws.internal.SdkInternalList<String>) destination.getCcAddresses()).isAutoConstruct()) {
                    com.amazonaws.internal.SdkInternalList<String> ccAddressesList = (com.amazonaws.internal.SdkInternalList<String>) destination
                            .getCcAddresses();
                    int ccAddressesListIndex = 1;

                    for (String ccAddressesListValue : ccAddressesList) {
                        if (ccAddressesListValue != null) {
                            request.addParameter("Destination.CcAddresses.member." + ccAddressesListIndex, StringUtils.fromString(ccAddressesListValue));
                        }
                        ccAddressesListIndex++;
                    }
                }

                if (!destination.getBccAddresses().isEmpty()
                        || !((com.amazonaws.internal.SdkInternalList<String>) destination.getBccAddresses()).isAutoConstruct()) {
                    com.amazonaws.internal.SdkInternalList<String> bccAddressesList = (com.amazonaws.internal.SdkInternalList<String>) destination
                            .getBccAddresses();
                    int bccAddressesListIndex = 1;

                    for (String bccAddressesListValue : bccAddressesList) {
                        if (bccAddressesListValue != null) {
                            request.addParameter("Destination.BccAddresses.member." + bccAddressesListIndex, StringUtils.fromString(bccAddressesListValue));
                        }
                        bccAddressesListIndex++;
                    }
                }
            }
        }

        {
            Message message = sendEmailRequest.getMessage();
            if (message != null) {

                {
                    Content subject = message.getSubject();
                    if (subject != null) {

                        if (subject.getData() != null) {
                            request.addParameter("Message.Subject.Data", StringUtils.fromString(subject.getData()));
                        }

                        if (subject.getCharset() != null) {
                            request.addParameter("Message.Subject.Charset", StringUtils.fromString(subject.getCharset()));
                        }
                    }
                }

                {
                    Body body = message.getBody();
                    if (body != null) {

                        {
                            Content text = body.getText();
                            if (text != null) {

                                if (text.getData() != null) {
                                    request.addParameter("Message.Body.Text.Data", StringUtils.fromString(text.getData()));
                                }

                                if (text.getCharset() != null) {
                                    request.addParameter("Message.Body.Text.Charset", StringUtils.fromString(text.getCharset()));
                                }
                            }
                        }

                        {
                            Content html = body.getHtml();
                            if (html != null) {

                                if (html.getData() != null) {
                                    request.addParameter("Message.Body.Html.Data", StringUtils.fromString(html.getData()));
                                }

                                if (html.getCharset() != null) {
                                    request.addParameter("Message.Body.Html.Charset", StringUtils.fromString(html.getCharset()));
                                }
                            }
                        }
                    }
                }
            }
        }

        if (!sendEmailRequest.getReplyToAddresses().isEmpty()
                || !((com.amazonaws.internal.SdkInternalList<String>) sendEmailRequest.getReplyToAddresses()).isAutoConstruct()) {
            com.amazonaws.internal.SdkInternalList<String> replyToAddressesList = (com.amazonaws.internal.SdkInternalList<String>) sendEmailRequest
                    .getReplyToAddresses();
            int replyToAddressesListIndex = 1;

            for (String replyToAddressesListValue : replyToAddressesList) {
                if (replyToAddressesListValue != null) {
                    request.addParameter("ReplyToAddresses.member." + replyToAddressesListIndex, StringUtils.fromString(replyToAddressesListValue));
                }
                replyToAddressesListIndex++;
            }
        }

        if (sendEmailRequest.getReturnPath() != null) {
            request.addParameter("ReturnPath", StringUtils.fromString(sendEmailRequest.getReturnPath()));
        }

        if (sendEmailRequest.getSourceArn() != null) {
            request.addParameter("SourceArn", StringUtils.fromString(sendEmailRequest.getSourceArn()));
        }

        if (sendEmailRequest.getReturnPathArn() != null) {
            request.addParameter("ReturnPathArn", StringUtils.fromString(sendEmailRequest.getReturnPathArn()));
        }

        if (!sendEmailRequest.getTags().isEmpty() || !((com.amazonaws.internal.SdkInternalList<MessageTag>) sendEmailRequest.getTags()).isAutoConstruct()) {
            com.amazonaws.internal.SdkInternalList<MessageTag> tagsList = (com.amazonaws.internal.SdkInternalList<MessageTag>) sendEmailRequest.getTags();
            int tagsListIndex = 1;

            for (MessageTag tagsListValue : tagsList) {

                if (tagsListValue.getName() != null) {
                    request.addParameter("Tags.member." + tagsListIndex + ".Name", StringUtils.fromString(tagsListValue.getName()));
                }

                if (tagsListValue.getValue() != null) {
                    request.addParameter("Tags.member." + tagsListIndex + ".Value", StringUtils.fromString(tagsListValue.getValue()));
                }
                tagsListIndex++;
            }
        }

        if (sendEmailRequest.getConfigurationSetName() != null) {
            request.addParameter("ConfigurationSetName", StringUtils.fromString(sendEmailRequest.getConfigurationSetName()));
        }

        return request;
    }

}


text:
package org.theospi.portfolio.shared.model;

import java.io.Serializable;

public class ItemDefinitionMimeType implements Serializable {
   private String primary;
   private String secondary;
   static final long serialVersionUID = -6220810277272518156l;

   public ItemDefinitionMimeType() {
   }

   public ItemDefinitionMimeType(String primary, String secondary) {
      this.primary = primary;
      this.secondary = secondary;
   }

   public String getSecondary() {
      return secondary;
   }

   public void setSecondary(String secondary) {
      this.secondary = secondary;
   }

   public String getPrimary() {
      return primary;
   }

   public void setPrimary(String primary) {
      this.primary = primary;
   }

   public String getValue() {
      return this.toString();
   }

   public String toString() {
      StringBuilder buffer = new StringBuilder();
      buffer.append(getPrimary());
      if (getSecondary() != null && getSecondary().length() > 0) {
         buffer.append("/");
         buffer.append(getSecondary());
      }
      return buffer.toString();
   }

   public boolean equals(Object o) {
      if (this == o) return true;
      if (!(o instanceof ItemDefinitionMimeType)) return false;

      final ItemDefinitionMimeType itemDefinitionMimeType = (ItemDefinitionMimeType) o;

      if (!primary.equals(itemDefinitionMimeType.primary)) return false;
      if (secondary != null ? !secondary.equals(itemDefinitionMimeType.secondary) : itemDefinitionMimeType.secondary != null) return false;

      return true;
   }

   public int hashCode() {
      int result;
      result = primary.hashCode();
      result = 29 * result + (secondary != null ? secondary.hashCode() : 0);
      return result;
   }
}


text:
package sk.tomsik68.mclauncher.api.login;

import java.util.List;

/**
 * Session is what is obtained in login process.
 *
 * @author Tomsik68
 */
public interface ISession {
    /**
     * @return Username of this session
     */
    public String getUsername();

    /**
     * @return ID of the session
     */
    public String getSessionID();

    /**
     * @return Player's UUID
     */
    public String getUUID();

    /**
     * @return Type of this session
     */
    public ESessionType getType();

    /**
     * @return User properties tied with this session
     */
    public List<Prop> getProperties();

    /** A simple class for user properties. A property is a name-value pair. */
    public final class Prop {
        public String name, value;
    }

}


text:
'use strict';

eventsApp.controller('FilterSampleController', function FilterSampleController($scope, durationsFilter){
    $scope.data = {};

    $scope.data.duration1 = durationsFilter(1);
    $scope.data.duration2 = durationsFilter(2);
    $scope.data.duration3 = durationsFilter(3);
    $scope.data.duration4 = durationsFilter(4);

});