text:
//
// Created by Administrator on 2016/6/14.
//

#ifndef OS_VGA_H
#define OS_VGA_H

#define VGA_MAX_ROW 30
#define VGA_MAX_COL 80
#define VGA_TIME_COL 70

#define VGA_TAB_LEN 4

/*
 * The first 58 lines show the information of the console
 * The last 2 lines show the information of the system
 */
#define VGA_ROW_SYSTEM 2
#define VGA_ROW_CONSOLE (VGA_MAX_ROW - VGA_ROW_SYSTEM)

extern int cursor_row;
extern int cursor_col;
extern short* vga_buffer;

extern void init_vga(unsigned int buffer);
extern void clean_screen(int scope);
extern void set_cursor(int row, int col);

void set_cursor_short(int num);
void scroll_screen(int scope);

#endif //OS_VGA_H


text:
package com.opengamma.strata.pricer.capfloor;

import static com.opengamma.strata.basics.currency.Currency.EUR;
import static com.opengamma.strata.basics.index.IborIndices.EUR_EURIBOR_3M;
import static com.opengamma.strata.collect.TestHelper.date;
import static com.opengamma.strata.collect.TestHelper.dateUtc;
import static com.opengamma.strata.product.common.PayReceive.PAY;
import static com.opengamma.strata.product.common.PayReceive.RECEIVE;
import static com.opengamma.strata.product.common.PutCall.CALL;
import static com.opengamma.strata.product.common.PutCall.PUT;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;

import java.time.LocalDate;
import java.time.ZonedDateTime;

import org.testng.annotations.Test;

import com.opengamma.strata.basics.currency.CurrencyAmount;
import com.opengamma.strata.basics.value.ValueSchedule;
import com.opengamma.strata.collect.timeseries.LocalDateDoubleTimeSeries;
import com.opengamma.strata.market.param.CurrencyParameterSensitivities;
import com.opengamma.strata.market.sensitivity.PointSensitivityBuilder;
import com.opengamma.strata.pricer.rate.ImmutableRatesProvider;
import com.opengamma.strata.product.capfloor.IborCapletFloorletPeriod;
import com.opengamma.strata.product.capfloor.ResolvedIborCapFloorLeg;

/**
 * Test {@link SabrIborCapFloorLegPricer}.
 */
@Test
public class SabrIborCapFloorLegPricerTest {

  private static final double STRIKE = 0.015;
  private static final double NOTIONAL_VALUE = 100_000_000;
  private static final ValueSchedule STRIKE_SCHEDULE = ValueSchedule.of(STRIKE);
  private static final ValueSchedule NOTIONAL = ValueSchedule.of(NOTIONAL_VALUE);
  private static final LocalDate START = LocalDate.of(2011, 3, 17);
  private static final LocalDate END = LocalDate.of(2016, 3, 17);
  private static final ResolvedIborCapFloorLeg CAP =
      IborCapFloorDataSet.createCapFloorLeg(EUR_EURIBOR_3M, START, END, STRIKE_SCHEDULE, NOTIONAL, CALL, RECEIVE);
  private static final ResolvedIborCapFloorLeg FLOOR =
      IborCapFloorDataSet.createCapFloorLeg(EUR_EURIBOR_3M, START, END, STRIKE_SCHEDULE, NOTIONAL, PUT, PAY);
  // valuation before start
  private static final ZonedDateTime VALUATION = dateUtc(2011, 1, 20);
  private static final ImmutableRatesProvider RATES = IborCapletFloorletSabrRateVolatilityDataSet.getRatesProvider(
      VALUATION.toLocalDate(), EUR_EURIBOR_3M, LocalDateDoubleTimeSeries.empty());
  private static final SabrIborCapletFloorletVolatilities VOLS = IborCapletFloorletSabrRateVolatilityDataSet
      .getVolatilities(VALUATION, EUR_EURIBOR_3M);
  // valuation between fixing of 3rd period and payment of 2nd period
  private static final double OBS_INDEX_2 = 0.012;
  private static final double OBS_INDEX_3 = 0.0125;
  private static final LocalDateDoubleTimeSeries TIME_SERIES = LocalDateDoubleTimeSeries.builder()
      .put(date(2011, 6, 15), OBS_INDEX_2)
      .put(date(2011, 9, 15), OBS_INDEX_3)
      .build();
  private static final ZonedDateTime VALUATION_AFTER = dateUtc(2011, 9, 16);
  private static final ImmutableRatesProvider RATES_AFTER = IborCapletFloorletSabrRateVolatilityDataSet.getRatesProvider(
      VALUATION_AFTER.toLocalDate(), EUR_EURIBOR_3M, TIME_SERIES);
  private static final SabrIborCapletFloorletVolatilities VOLS_AFTER = IborCapletFloorletSabrRateVolatilityDataSet
      .getVolatilities(VALUATION_AFTER, EUR_EURIBOR_3M);
  // valuation at payment of 2nd period
  private static final ZonedDateTime VALUATION_PAY = dateUtc(2011, 9, 19);
  private static final ImmutableRatesProvider RATES_PAY =
      IborCapletFloorletDataSet.createRatesProvider(VALUATION_PAY.toLocalDate(), EUR_EURIBOR_3M, TIME_SERIES);
  private static final SabrIborCapletFloorletVolatilities VOLS_PAY = IborCapletFloorletSabrRateVolatilityDataSet
      .getVolatilities(VALUATION_PAY, EUR_EURIBOR_3M);

  private static final double TOL = 1.0e-14;
  private static final SabrIborCapFloorLegPricer PRICER = SabrIborCapFloorLegPricer.DEFAULT;
  private static final SabrIborCapletFloorletPeriodPricer PRICER_PERIOD = SabrIborCapletFloorletPeriodPricer.DEFAULT;

  public void test_presentValue() {
    CurrencyAmount capComputed = PRICER.presentValue(CAP, RATES, VOLS);
    CurrencyAmount floorComputed = PRICER.presentValue(FLOOR, RATES, VOLS);
    double capExpected = 0d;
    double floorExpected = 0d;
    int nPeriods = CAP.getCapletFloorletPeriods().size();
    for (int i = 0; i < nPeriods; ++i) {
      capExpected += PRICER_PERIOD.presentValue(CAP.getCapletFloorletPeriods().get(i), RATES, VOLS).getAmount();
      floorExpected += PRICER_PERIOD.presentValue(FLOOR.getCapletFloorletPeriods().get(i), RATES, VOLS).getAmount();
    }
    assertEquals(capComputed.getCurrency(), EUR);
    assertEquals(capComputed.getAmount(), capExpected);
    assertEquals(floorComputed.getCurrency(), EUR);
    assertEquals(floorComputed.getAmount(), floorExpected);
  }

  public void test_presentValue_after() {
    CurrencyAmount capComputed = PRICER.presentValue(CAP, RATES_AFTER, VOLS_AFTER);
    CurrencyAmount floorComputed = PRICER.presentValue(FLOOR, RATES_AFTER, VOLS_AFTER);
    double capExpected = 0d;
    IborCapletFloorletPeriod period = FLOOR.getCapletFloorletPeriods().get(1);
    double floorExpected = -(STRIKE - OBS_INDEX_2) * NOTIONAL_VALUE * period.getYearFraction() *
        RATES_AFTER.discountFactor(EUR, period.getPaymentDate());
    int nPeriods = CAP.getCapletFloorletPeriods().size();
    for (int i = 2; i < nPeriods; ++i) {
      capExpected += PRICER_PERIOD.presentValue(CAP.getCapletFloorletPeriods().get(i), RATES_AFTER, VOLS_AFTER).getAmount();
      floorExpected += PRICER_PERIOD.presentValue(FLOOR.getCapletFloorletPeriods().get(i), RATES_AFTER, VOLS_AFTER).getAmount();
    }
    assertEquals(capComputed.getCurrency(), EUR);
    assertEquals(capComputed.getAmount(), capExpected, TOL * NOTIONAL_VALUE);
    assertEquals(floorComputed.getCurrency(), EUR);
    assertEquals(floorComputed.getAmount(), floorExpected, TOL * NOTIONAL_VALUE);
  }

  //-------------------------------------------------------------------------
  public void test_presentValueDelta() {
    CurrencyAmount capComputed = PRICER.presentValueDelta(CAP, RATES, VOLS);
    CurrencyAmount floorComputed = PRICER.presentValueDelta(FLOOR, RATES, VOLS);
    double capExpected = 0d;
    double floorExpected = 0d;
    int nPeriods = CAP.getCapletFloorletPeriods().size();
    for (int i = 0; i < nPeriods; ++i) {
      capExpected += PRICER_PERIOD.presentValueDelta(CAP.getCapletFloorletPeriods().get(i), RATES, VOLS).getAmount();
      floorExpected += PRICER_PERIOD.presentValueDelta(FLOOR.getCapletFloorletPeriods().get(i), RATES, VOLS)
          .getAmount();
    }
    assertEquals(capComputed.getCurrency(), EUR);
    assertEquals(capComputed.getAmount(), capExpected, TOL * NOTIONAL_VALUE);
    assertEquals(floorComputed.getCurrency(), EUR);
    assertEquals(floorComputed.getAmount(), floorExpected, TOL * NOTIONAL_VALUE);
  }

  public void test_presentValueDelta_after() {
    CurrencyAmount capComputed = PRICER.presentValueDelta(CAP, RATES_AFTER, VOLS_AFTER);
    CurrencyAmount floorComputed = PRICER.presentValueDelta(FLOOR, RATES_AFTER, VOLS_AFTER);
    double capExpected = 0d;
    double floorExpected = 0d;
    int nPeriods = CAP.getCapletFloorletPeriods().size();
    for (int i = 2; i < nPeriods; ++i) {
      capExpected += PRICER_PERIOD.presentValueDelta(CAP.getCapletFloorletPeriods().get(i), RATES_AFTER, VOLS_AFTER)
          .getAmount();
      floorExpected += PRICER_PERIOD
          .presentValueDelta(FLOOR.getCapletFloorletPeriods().get(i), RATES_AFTER, VOLS_AFTER).getAmount();
    }
    assertEquals(capComputed.getCurrency(), EUR);
    assertEquals(capComputed.getAmount(), capExpected, TOL * NOTIONAL_VALUE);
    assertEquals(floorComputed.getCurrency(), EUR);
    assertEquals(floorComputed.getAmount(), floorExpected, TOL * NOTIONAL_VALUE);
  }

  //-------------------------------------------------------------------------
  public void test_presentValueGamma() {
    CurrencyAmount capComputed = PRICER.presentValueGamma(CAP, RATES, VOLS);
    CurrencyAmount floorComputed = PRICER.presentValueGamma(FLOOR, RATES, VOLS);
    double capExpected = 0d;
    double floorExpected = 0d;
    int nPeriods = CAP.getCapletFloorletPeriods().size();
    for (int i = 0; i < nPeriods; ++i) {
      capExpected += PRICER_PERIOD.presentValueGamma(CAP.getCapletFloorletPeriods().get(i), RATES, VOLS).getAmount();
      floorExpected += PRICER_PERIOD.presentValueGamma(FLOOR.getCapletFloorletPeriods().get(i), RATES, VOLS)
          .getAmount();
    }
    assertEquals(capComputed.getCurrency(), EUR);
    assertEquals(capComputed.getAmount(), capExpected, TOL * NOTIONAL_VALUE);
    assertEquals(floorComputed.getCurrency(), EUR);
    assertEquals(floorComputed.getAmount(), floorExpected, TOL * NOTIONAL_VALUE);
  }

  public void test_presentValueGamma_after() {
    CurrencyAmount capComputed = PRICER.presentValueGamma(CAP, RATES_AFTER, VOLS_AFTER);
    CurrencyAmount floorComputed = PRICER.presentValueGamma(FLOOR, RATES_AFTER, VOLS_AFTER);
    double capExpected = 0d;
    double floorExpected = 0d;
    int nPeriods = CAP.getCapletFloorletPeriods().size();
    for (int i = 2; i < nPeriods; ++i) {
      capExpected += PRICER_PERIOD.presentValueGamma(CAP.getCapletFloorletPeriods().get(i), RATES_AFTER, VOLS_AFTER)
          .getAmount();
      floorExpected += PRICER_PERIOD
          .presentValueGamma(FLOOR.getCapletFloorletPeriods().get(i), RATES_AFTER, VOLS_AFTER).getAmount();
    }
    assertEquals(capComputed.getCurrency(), EUR);
    assertEquals(capComputed.getAmount(), capExpected, TOL * NOTIONAL_VALUE);
    assertEquals(floorComputed.getCurrency(), EUR);
    assertEquals(floorComputed.getAmount(), floorExpected, TOL * NOTIONAL_VALUE);
  }

  //-------------------------------------------------------------------------
  public void test_presentValueTheta() {
    CurrencyAmount capComputed = PRICER.presentValueTheta(CAP, RATES, VOLS);
    CurrencyAmount floorComputed = PRICER.presentValueTheta(FLOOR, RATES, VOLS);
    double capExpected = 0d;
    double floorExpected = 0d;
    int nPeriods = CAP.getCapletFloorletPeriods().size();
    for (int i = 0; i < nPeriods; ++i) {
      capExpected += PRICER_PERIOD.presentValueTheta(CAP.getCapletFloorletPeriods().get(i), RATES, VOLS).getAmount();
      floorExpected += PRICER_PERIOD.presentValueTheta(FLOOR.getCapletFloorletPeriods().get(i), RATES, VOLS)
          .getAmount();
    }
    assertEquals(capComputed.getCurrency(), EUR);
    assertEquals(capComputed.getAmount(), capExpected, TOL * NOTIONAL_VALUE);
    assertEquals(floorComputed.getCurrency(), EUR);
    assertEquals(floorComputed.getAmount(), floorExpected, TOL * NOTIONAL_VALUE);
  }

  public void test_presentValueTheta_after() {
    CurrencyAmount capComputed = PRICER.presentValueTheta(CAP, RATES_AFTER, VOLS_AFTER);
    CurrencyAmount floorComputed = PRICER.presentValueTheta(FLOOR, RATES_AFTER, VOLS_AFTER);
    double capExpected = 0d;
    double floorExpected = 0d;
    int nPeriods = CAP.getCapletFloorletPeriods().size();
    for (int i = 2; i < nPeriods; ++i) {
      capExpected += PRICER_PERIOD.presentValueTheta(CAP.getCapletFloorletPeriods().get(i), RATES_AFTER, VOLS_AFTER)
          .getAmount();
      floorExpected += PRICER_PERIOD
          .presentValueTheta(FLOOR.getCapletFloorletPeriods().get(i), RATES_AFTER, VOLS_AFTER).getAmount();
    }
    assertEquals(capComputed.getCurrency(), EUR);
    assertEquals(capComputed.getAmount(), capExpected, TOL * NOTIONAL_VALUE);
    assertEquals(floorComputed.getCurrency(), EUR);
    assertEquals(floorComputed.getAmount(), floorExpected, TOL * NOTIONAL_VALUE);
  }

  //-------------------------------------------------------------------------
  public void test_presentValueSensitivityRatesStickyModel() {
    PointSensitivityBuilder capComputed = PRICER.presentValueSensitivityRatesStickyModel(CAP, RATES, VOLS);
    PointSensitivityBuilder floorComputed = PRICER.presentValueSensitivityRatesStickyModel(FLOOR, RATES, VOLS);
    PointSensitivityBuilder capExpected = PointSensitivityBuilder.none();
    PointSensitivityBuilder floorExpected = PointSensitivityBuilder.none();
    int nPeriods = CAP.getCapletFloorletPeriods().size();
    for (int i = 0; i < nPeriods; ++i) {
      capExpected = capExpected.combinedWith(
          PRICER_PERIOD.presentValueSensitivityRatesStickyModel(CAP.getCapletFloorletPeriods().get(i), RATES, VOLS));
      floorExpected = floorExpected.combinedWith(
          PRICER_PERIOD.presentValueSensitivityRatesStickyModel(FLOOR.getCapletFloorletPeriods().get(i), RATES, VOLS));
    }
    CurrencyParameterSensitivities capSensiComputed = RATES_AFTER.parameterSensitivity(capComputed.build());
    CurrencyParameterSensitivities floorSensiComputed = RATES_AFTER.parameterSensitivity(floorComputed.build());
    CurrencyParameterSensitivities capSensiExpected = RATES_AFTER.parameterSensitivity(capExpected.build());
    CurrencyParameterSensitivities floorSensiExpected = RATES_AFTER.parameterSensitivity(floorExpected.build());
    assertTrue(capSensiComputed.equalWithTolerance(capSensiExpected, NOTIONAL_VALUE * TOL));
    assertTrue(floorSensiComputed.equalWithTolerance(floorSensiExpected, NOTIONAL_VALUE * TOL));
  }

  public void test_presentValueSensitivityRatesStickyModel_after() {
    PointSensitivityBuilder capComputed = PRICER.presentValueSensitivityRatesStickyModel(CAP, RATES_AFTER, VOLS_AFTER);
    PointSensitivityBuilder floorComputed = PRICER.presentValueSensitivityRatesStickyModel(FLOOR, RATES_AFTER, VOLS_AFTER);
    PointSensitivityBuilder capExpected = PointSensitivityBuilder.none();
    IborCapletFloorletPeriod period = FLOOR.getCapletFloorletPeriods().get(1);
    PointSensitivityBuilder floorExpected = RATES_AFTER.discountFactors(EUR).zeroRatePointSensitivity(period.getPaymentDate())
        .multipliedBy(-(STRIKE - OBS_INDEX_2) * NOTIONAL_VALUE * period.getYearFraction());
    int nPeriods = CAP.getCapletFloorletPeriods().size();
    for (int i = 2; i < nPeriods; ++i) {
      capExpected = capExpected.combinedWith(
          PRICER_PERIOD.presentValueSensitivityRatesStickyModel(CAP.getCapletFloorletPeriods().get(i), RATES_AFTER, VOLS_AFTER));
      floorExpected = floorExpected.combinedWith(
          PRICER_PERIOD.presentValueSensitivityRatesStickyModel(
              FLOOR.getCapletFloorletPeriods().get(i), RATES_AFTER, VOLS_AFTER));
    }
    CurrencyParameterSensitivities capSensiComputed = RATES_AFTER.parameterSensitivity(capComputed.build());
    CurrencyParameterSensitivities floorSensiComputed = RATES_AFTER.parameterSensitivity(floorComputed.build());
    CurrencyParameterSensitivities capSensiExpected = RATES_AFTER.parameterSensitivity(capExpected.build());
    CurrencyParameterSensitivities floorSensiExpected = RATES_AFTER.parameterSensitivity(floorExpected.build());
    assertTrue(capSensiComputed.equalWithTolerance(capSensiExpected, NOTIONAL_VALUE * TOL));
    assertTrue(floorSensiComputed.equalWithTolerance(floorSensiExpected, NOTIONAL_VALUE * TOL));
  }

  public void test_presentValueSensitivityRates() {
    PointSensitivityBuilder capComputed = PRICER.presentValueSensitivityRates(CAP, RATES, VOLS);
    PointSensitivityBuilder floorComputed = PRICER.presentValueSensitivityRates(FLOOR, RATES, VOLS);
    PointSensitivityBuilder capExpected = PointSensitivityBuilder.none();
    PointSensitivityBuilder floorExpected = PointSensitivityBuilder.none();
    int nPeriods = CAP.getCapletFloorletPeriods().size();
    for (int i = 0; i < nPeriods; ++i) {
      capExpected = capExpected.combinedWith(
          PRICER_PERIOD.presentValueSensitivityRates(CAP.getCapletFloorletPeriods().get(i), RATES, VOLS));
      floorExpected = floorExpected.combinedWith(
          PRICER_PERIOD.presentValueSensitivityRates(FLOOR.getCapletFloorletPeriods().get(i), RATES, VOLS));
    }
    CurrencyParameterSensitivities capSensiComputed = RATES_AFTER.parameterSensitivity(capComputed.build());
    CurrencyParameterSensitivities floorSensiComputed = RATES_AFTER.parameterSensitivity(floorComputed.build());
    CurrencyParameterSensitivities capSensiExpected = RATES_AFTER.parameterSensitivity(capExpected.build());
    CurrencyParameterSensitivities floorSensiExpected = RATES_AFTER.parameterSensitivity(floorExpected.build());
    assertTrue(capSensiComputed.equalWithTolerance(capSensiExpected, NOTIONAL_VALUE * TOL));
    assertTrue(floorSensiComputed.equalWithTolerance(floorSensiExpected, NOTIONAL_VALUE * TOL));
  }

  public void test_presentValueSensitivityRates_after() {
    PointSensitivityBuilder capComputed = PRICER.presentValueSensitivityRates(CAP, RATES_AFTER, VOLS_AFTER);
    PointSensitivityBuilder floorComputed = PRICER.presentValueSensitivityRates(FLOOR, RATES_AFTER, VOLS_AFTER);
    PointSensitivityBuilder capExpected = PointSensitivityBuilder.none();
    IborCapletFloorletPeriod period = FLOOR.getCapletFloorletPeriods().get(1);
    PointSensitivityBuilder floorExpected = RATES_AFTER.discountFactors(EUR).zeroRatePointSensitivity(period.getPaymentDate())
        .multipliedBy(-(STRIKE - OBS_INDEX_2) * NOTIONAL_VALUE * period.getYearFraction());
    int nPeriods = CAP.getCapletFloorletPeriods().size();
    for (int i = 2; i < nPeriods; ++i) {
      capExpected = capExpected.combinedWith(
          PRICER_PERIOD.presentValueSensitivityRates(CAP.getCapletFloorletPeriods().get(i), RATES_AFTER, VOLS_AFTER));
      floorExpected = floorExpected.combinedWith(
          PRICER_PERIOD.presentValueSensitivityRates(FLOOR.getCapletFloorletPeriods().get(i), RATES_AFTER, VOLS_AFTER));
    }
    CurrencyParameterSensitivities capSensiComputed = RATES_AFTER.parameterSensitivity(capComputed.build());
    CurrencyParameterSensitivities floorSensiComputed = RATES_AFTER.parameterSensitivity(floorComputed.build());
    CurrencyParameterSensitivities capSensiExpected = RATES_AFTER.parameterSensitivity(capExpected.build());
    CurrencyParameterSensitivities floorSensiExpected = RATES_AFTER.parameterSensitivity(floorExpected.build());
    assertTrue(capSensiComputed.equalWithTolerance(capSensiExpected, NOTIONAL_VALUE * TOL));
    assertTrue(floorSensiComputed.equalWithTolerance(floorSensiExpected, NOTIONAL_VALUE * TOL));
  }

  //-------------------------------------------------------------------------
  public void test_presentValueSensitivityModelParamsSabr() {
    PointSensitivityBuilder capComputed = PRICER.presentValueSensitivityModelParamsSabr(CAP, RATES, VOLS);
    PointSensitivityBuilder floorComputed = PRICER.presentValueSensitivityModelParamsSabr(FLOOR, RATES, VOLS);
    CurrencyParameterSensitivities capExpected = CurrencyParameterSensitivities.empty();
    CurrencyParameterSensitivities floorExpected = CurrencyParameterSensitivities.empty();
    int nPeriods = CAP.getCapletFloorletPeriods().size();
    for (int i = 0; i < nPeriods; ++i) {
      capExpected = capExpected.combinedWith(VOLS.parameterSensitivity(PRICER_PERIOD
          .presentValueSensitivityModelParamsSabr(CAP.getCapletFloorletPeriods().get(i), RATES, VOLS).build()));
      floorExpected = floorExpected.combinedWith(VOLS.parameterSensitivity(PRICER_PERIOD
          .presentValueSensitivityModelParamsSabr(FLOOR.getCapletFloorletPeriods().get(i), RATES, VOLS).build()));
    }
    CurrencyParameterSensitivities capSensiComputed = VOLS.parameterSensitivity(capComputed.build());
    CurrencyParameterSensitivities floorSensiComputed = VOLS.parameterSensitivity(floorComputed.build());
    assertTrue(capSensiComputed.equalWithTolerance(capExpected, TOL * NOTIONAL_VALUE));
    assertTrue(floorSensiComputed.equalWithTolerance(floorExpected, TOL * NOTIONAL_VALUE));
  }

  public void test_presentValueSensitivityModelParamsSabr_after() {
    PointSensitivityBuilder capComputed = PRICER.presentValueSensitivityModelParamsSabr(CAP, RATES_AFTER, VOLS_AFTER);
    PointSensitivityBuilder floorComputed = PRICER.presentValueSensitivityModelParamsSabr(FLOOR, RATES_AFTER, VOLS_AFTER);
    CurrencyParameterSensitivities capExpected = CurrencyParameterSensitivities.empty();
    CurrencyParameterSensitivities floorExpected = CurrencyParameterSensitivities.empty();
    int nPeriods = CAP.getCapletFloorletPeriods().size();
    for (int i = 3; i < nPeriods; ++i) {
      capExpected = capExpected.combinedWith(VOLS_AFTER.parameterSensitivity(PRICER_PERIOD
          .presentValueSensitivityModelParamsSabr(CAP.getCapletFloorletPeriods().get(i), RATES_AFTER, VOLS_AFTER).build()));
      floorExpected = floorExpected.combinedWith(VOLS_AFTER.parameterSensitivity(PRICER_PERIOD
          .presentValueSensitivityModelParamsSabr(FLOOR.getCapletFloorletPeriods().get(i), RATES_AFTER, VOLS_AFTER)
          .build()));
    }
    CurrencyParameterSensitivities capSensiComputed = VOLS_AFTER.parameterSensitivity(capComputed.build());
    CurrencyParameterSensitivities floorSensiComputed = VOLS_AFTER.parameterSensitivity(floorComputed.build());
    assertTrue(capSensiComputed.equalWithTolerance(capExpected, TOL * NOTIONAL_VALUE));
    assertTrue(floorSensiComputed.equalWithTolerance(floorExpected, TOL * NOTIONAL_VALUE));
  }

  public void test_presentValueSensitivityModelParamsVolatility() {
    PointSensitivityBuilder capComputed = PRICER.presentValueSensitivityModelParamsVolatility(CAP, RATES, VOLS);
    PointSensitivityBuilder floorComputed = PRICER.presentValueSensitivityModelParamsVolatility(FLOOR, RATES, VOLS);
    CurrencyParameterSensitivities capExpected = CurrencyParameterSensitivities.empty();
    CurrencyParameterSensitivities floorExpected = CurrencyParameterSensitivities.empty();
    int nPeriods = CAP.getCapletFloorletPeriods().size();
    for (int i = 0; i < nPeriods; ++i) {
      capExpected = capExpected.combinedWith(VOLS.parameterSensitivity(PRICER_PERIOD
          .presentValueSensitivityModelParamsVolatility(CAP.getCapletFloorletPeriods().get(i), RATES, VOLS).build()));
      floorExpected = floorExpected.combinedWith(VOLS.parameterSensitivity(PRICER_PERIOD
          .presentValueSensitivityModelParamsVolatility(FLOOR.getCapletFloorletPeriods().get(i), RATES, VOLS).build()));
    }
    CurrencyParameterSensitivities capSensiComputed = VOLS.parameterSensitivity(capComputed.build());
    CurrencyParameterSensitivities floorSensiComputed = VOLS.parameterSensitivity(floorComputed.build());
    assertTrue(capSensiComputed.equalWithTolerance(capExpected, TOL * NOTIONAL_VALUE));
    assertTrue(floorSensiComputed.equalWithTolerance(floorExpected, TOL * NOTIONAL_VALUE));
  }

  public void test_presentValueSensitivityModelParamsVolatility_after() {
    PointSensitivityBuilder capComputed = PRICER.presentValueSensitivityModelParamsVolatility(CAP, RATES_AFTER, VOLS_AFTER);
    PointSensitivityBuilder floorComputed = PRICER.presentValueSensitivityModelParamsVolatility(FLOOR, RATES_AFTER, VOLS_AFTER);
    CurrencyParameterSensitivities capExpected = CurrencyParameterSensitivities.empty();
    CurrencyParameterSensitivities floorExpected = CurrencyParameterSensitivities.empty();
    int nPeriods = CAP.getCapletFloorletPeriods().size();
    for (int i = 3; i < nPeriods; ++i) {
      capExpected = capExpected.combinedWith(VOLS_AFTER.parameterSensitivity(PRICER_PERIOD
          .presentValueSensitivityModelParamsVolatility(CAP.getCapletFloorletPeriods().get(i), RATES_AFTER, VOLS_AFTER).build()));
      floorExpected = floorExpected.combinedWith(VOLS_AFTER.parameterSensitivity(PRICER_PERIOD
          .presentValueSensitivityModelParamsVolatility(FLOOR.getCapletFloorletPeriods().get(i), RATES_AFTER, VOLS_AFTER)
          .build()));
    }
    CurrencyParameterSensitivities capSensiComputed = VOLS_AFTER.parameterSensitivity(capComputed.build());
    CurrencyParameterSensitivities floorSensiComputed = VOLS_AFTER.parameterSensitivity(floorComputed.build());
    assertTrue(capSensiComputed.equalWithTolerance(capExpected, TOL * NOTIONAL_VALUE));
    assertTrue(floorSensiComputed.equalWithTolerance(floorExpected, TOL * NOTIONAL_VALUE));
  }

  //-------------------------------------------------------------------------
  public void test_currentCash() {
    CurrencyAmount capComputed = PRICER.currentCash(CAP, RATES, VOLS);
    CurrencyAmount floorComputed = PRICER.currentCash(FLOOR, RATES, VOLS);
    assertEquals(capComputed.getCurrency(), EUR);
    assertEquals(capComputed.getAmount(), 0d);
    assertEquals(floorComputed.getCurrency(), EUR);
    assertEquals(floorComputed.getAmount(), 0d);
  }

  public void test_currentCash_pay() {
    CurrencyAmount capComputed = PRICER.currentCash(CAP, RATES_PAY, VOLS_PAY);
    CurrencyAmount floorComputed = PRICER.currentCash(FLOOR, RATES_PAY, VOLS_PAY);
    double capExpected = 0d;
    IborCapletFloorletPeriod period = FLOOR.getCapletFloorletPeriods().get(1);
    double floorExpected = -(STRIKE - OBS_INDEX_2) * NOTIONAL_VALUE * period.getYearFraction();
    assertEquals(capComputed.getCurrency(), EUR);
    assertEquals(capComputed.getAmount(), capExpected);
    assertEquals(floorComputed.getCurrency(), EUR);
    assertEquals(floorComputed.getAmount(), floorExpected, TOL * NOTIONAL_VALUE);
  }

}

redpajama_set_name: RedPajamaGithub


text:
#ifndef XSLTExtensions_h
#define XSLTExtensions_h

#include <libxslt/xsltInternals.h>

namespace WebCore {

void registerXSLTExtensions(xsltTransformContextPtr ctxt);

}

#endif


text:
            <form data-ng-submit="signin()" autocomplete="off" class="reg-page elevated">

Login

                    Username:
                    <input type="text" id="username" name="username" data-ng-model="credentials.username" placeholder="Username"  class="form-control margin-bottom-20">

                    Password:
                    <input type="password" id="password" name="password" data-ng-model="credentials.password" placeholder="Password"  class="form-control margin-bottom-20">

                    <button type="submit" class="btn btn-a btn-a-awesome btn-block">Login</button>

or

                    Sign up

Forgot your password?

            </form>


text:
title: Creating a Simple Confirm Modal in Vanilla JS
published: true
description: Let's make a custom version of window.confirm() with the dialog element and the Promise API!
tags:
  - JS
  - HTML
layout: layouts/post.njk
date: 2019-09-25
---

Ever tried using `window.confirm()` before? It's a remarkable method that is very handy whenever you want your users to *really* be sure of what they're doing. However, have you tried styling it? Just like with `window.alert()` it's impossible, so we'll need to create our own Confirm Modal. I'll show you how!

## What to solve

First, it's useful to map out what we're trying to solve. It's important that our modal can do three things:

- Ask the user the question they should answer (e. g. 'Do you really want to delete your user account?')
- Let the user say 'Yes'
- Let the user say 'No'

Also, for developers, `window.confirm()` is *so* easy to use. We don't want to make it much harder for the developers using our custom confirm than it is to do `const theyAreSure = window.confirm('Are you sure');`.

Another thing the native modal comes with is the modal itself. We don't want the devs using our component to create a lot of markup every time they need to ask their users to confirm something, which means our custom modal needs to produce this markup automatically.

Ultimately, it should

- Be easy to use
- Not run any code before the user says 'yes'

## How to solve it

### Markup

For the sake of this tutorial, it's not too important to specify a convoluted markup, so let's just use this simple code as our HTML base:

```html
<dialog class="confirm-dialog">
  <div class="confirm-dialog-question">Do you really want to delete your user account?</div>
  <div class="confirm-dialog-button-group">
    <button class="confirm-dialog-button confirm-dialog-button--false" type="button">Noo</button>
    <button class="confirm-dialog-button confirm-dialog-button--true" type="button">Yes!</button>
  </div>
</dialog>
```

If you're unfamiliar with the `<dialog>` element, go check out [MDN's documentation about it](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dialog)! As a short introduction, it's a native element supported by Chrome, Firefox and Opera ([there is a polyfill as well](https://github.com/GoogleChrome/dialog-polyfill)) which you can use to show a modal with the `showModal()` method as such:

```javascript
function createDialog() {
  const dialog = document.createElement('dialog');
  dialog.textContent = '✨✨✨';

  document.body.appendChild(dialog);

  dialog.showModal();
}
```

### JavaScript API

By making use of the [Promise API](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) together with [`async`/`await`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function), we can solve two of the things we listed earlier: We can make the code easy to use and we can wait for a signal for when (or if) to actually run the code that deletes every user in the db.

Ultimately, we would want the use of our component to look something like this:

```javascript
async function deleteUsers() {
  const dialog = new ConfirmModal({
    questionText: 'Are you sure you want to delete every user?',
  });

  const deleteEveryUser = await dialog.confirm();
  if (deleteEveryUser) {
    // ...
  }
}
```

This makes for a easy to use component, but would this work?

JavaScript's `await`   stops code execution until the Promise that it's waiting for has been either **resolved** or **rejected**. The Promise can be resolved by  a function triggered by an Event and this is how we'll structure our code. When creating a new Promise, we will add an event listener to the two buttons and, depending on which of the buttons is clicked, resolve the Promise to either `true` or `false` - whether or not the user confirms.

## Solving it

Let's start by creating a `ConfirmModal` class for our component. Its constructor will need three things:

- The question text
- The 'Yes' button's text
- The 'No' button's text

```javascript
class ConfirmDialog {
  constructor({
    questionText,
    trueButtonText,
    falseButtonText
  }) {
    this.questionText = questionText || 'Are you sure?';
    this.trueButtonText = trueButtonText || 'Yes';
    this.falseButtonText = falseButtonText || 'No';

    this.dialog = undefined;
    this.trueButton = undefined;
    this.falseButton = undefined;
    this.parent = document.body;

    this._createDialog();
    this._appendDialog();
  }
}
```

I've created one method which creates the `<dialog>` element and its children, one which appends it to the `<body>`, and one which removes it from the body and then deletes our `ConfirmDialog` object. They look as such:

```javascript
  _createDialog() {
    this.dialog = document.createElement("dialog");
    this.dialog.classList.add("confirm-dialog");

    const question = document.createElement("div");
    question.textContent = this.questionText;
    question.classList.add("confirm-dialog-question");
    this.dialog.appendChild(question);

    const buttonGroup = document.createElement("div");
    buttonGroup.classList.add("confirm-dialog-button-group");
    this.dialog.appendChild(buttonGroup);

    this.falseButton = document.createElement("button");
    this.falseButton.classList.add(
      "confirm-dialog-button",
      "confirm-dialog-button--false"
    );
    this.falseButton.type = "button";
    this.falseButton.textContent = this.falseButtonText;
    buttonGroup.appendChild(this.falseButton);

    this.trueButton = document.createElement("button");
    this.trueButton.classList.add(
      "confirm-dialog-button",
      "confirm-dialog-button--true"
    );
    this.trueButton.type = "button";
    this.trueButton.textContent = this.trueButtonText;
    buttonGroup.appendChild(this.trueButton);
  }

  _appendDialog() {
    this.parent.appendChild(this.dialog);
  }

  _destroy() {
    this.parent.removeChild(this.dialog);
    delete this;
  }
```

Now, for the final part. Let's create the `confirm()` method. Inside it we need to show the modal, and to create event listeners for the two yes/no buttons and make them resolve to either `true` or `false` and then remove every trace of the component itself.

```javascript
confirm() {
  return new Promise((resolve, reject) => {
    const somethingWentWrongUponCreation =
      !this.dialog || !this.trueButton || !this.falseButton;
    if (somethingWentWrongUponCreation) {
      reject("Something went wrong upon modal creation");
    }

    this.dialog.showModal();

    this.trueButton.addEventListener("click", () => {
      resolve(true);
      this._destroy();
    });

    this.falseButton.addEventListener("click", () => {
      resolve(false);
      this._destroy();
    });
  });
}
```

Nice! I've tested it here:
{% codepen 'https://codepen.io/sindre/pen/RwbvObK' %}


text:
package robsonribeiroft.nucleus.helper;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import modelo.User;
import robsonribeiroft.nucleus.FormularioActivity;
import robsonribeiroft.nucleus.R;
import robsonribeiroft.nucleus.UsuarioActivity;
import robsonribeiroft.nucleus.singleton.Singleton;

public class Helper {

    private final User user;
    private ImageView campoFoto;
    private EditText campoNome;
    private EditText campoCpf;
    private EditText campoTelefone;
    private EditText campoEmail;
    private EditText campoCompanhia;
    private EditText campoAniversario;
    private EditText campoLocalizacao;
    private EditText campoWebsite;

    private TextView TVnome;
    private TextView TVcpf;
    private TextView TVtelefone;
    private TextView TVemail;
    private TextView TVcompanhia;
    private TextView TVaniversario;
    private TextView TVlocalizacao;
    private TextView TVwebsite;

    public Helper(FormularioActivity activity){
        user = new User();
        campoNome = (EditText) activity.findViewById(R.id.name);
        campoCpf = (EditText) activity.findViewById(R.id.cpf);
        campoTelefone = (EditText) activity.findViewById(R.id.phone);
        campoEmail = (EditText) activity.findViewById(R.id.email);
        campoCompanhia = (EditText) activity.findViewById(R.id.company);
        campoAniversario = (EditText) activity.findViewById(R.id.birthdate);
        campoLocalizacao = (EditText) activity.findViewById(R.id.location);
        campoWebsite = (EditText) activity.findViewById(R.id.url);
        campoFoto = (ImageView) activity.findViewById(R.id.mostrafoto);
    }

    public Helper(UsuarioActivity activity) {
        user = Singleton.getInstance().currentUser;
        TVnome = (TextView) activity.findViewById(R.id.TVnome);
        TVcpf = (TextView) activity.findViewById(R.id.TVcpf);
        TVtelefone = (TextView) activity.findViewById(R.id.TVtelefone);
        TVemail = (TextView) activity.findViewById(R.id.TVemail);
        TVcompanhia = (TextView) activity.findViewById(R.id.TVcompanhia);
        TVaniversario = (TextView) activity.findViewById(R.id.TVaniversario);
        TVlocalizacao = (TextView) activity.findViewById(R.id.TVlocalizacao);
        TVwebsite = (TextView) activity.findViewById(R.id.TVwebsite);

        TVnome.setText(user.getName());
        TVcpf.setText(user.getCpf());
        TVtelefone.setText(user.getPhone());
        TVemail.setText(user.getEmail());
        TVcompanhia.setText(user.getCompany());
        TVaniversario.setText(user.getBirthdate());
        TVlocalizacao.setText(user.getLocation());
        TVwebsite.setText(user.getUrl());
    }

    public User pegaUserDoFormulario(){
        user.setName(campoNome.getText().toString());
        user.setCpf(campoCpf.getText().toString().replaceAll("[.-]", ""));
        user.setPhone(campoTelefone.getText().toString());
        user.setEmail(campoEmail.getText().toString());
        user.setCompany(campoCompanhia.getText().toString());
        user.setBirthdate(campoAniversario.getText().toString());
        user.setLocation(campoLocalizacao.getText().toString());
        user.setUrl(campoWebsite.getText().toString());
        return user;
    }

    public void preencherFormulario(User userParaAlteracao) {

        campoNome.setText(userParaAlteracao.getName());
        campoCpf.setText(userParaAlteracao.getCpf());
        campoTelefone.setText(userParaAlteracao.getPhone());
        campoEmail.setText(userParaAlteracao.getEmail());
        campoCompanhia.setText(userParaAlteracao.getCompany());
        campoAniversario.setText(userParaAlteracao.getBirthdate());
        campoLocalizacao.setText(userParaAlteracao.getLocation());
        campoWebsite.setText(userParaAlteracao.getUrl());
        if (userParaAlteracao.getPhoto() != null){
            carregaImagem(userParaAlteracao.getPhoto());
        }
    }

    public void limparCampos() {
        campoNome.setText("");
        campoCpf.setText("");
        campoTelefone.setText("");
        campoEmail.setText("");
        campoCompanhia.setText("");
        campoAniversario.setText("");
        campoLocalizacao.setText("");
        campoWebsite.setText("");
    }

    public ImageView getFoto(){
        return campoFoto;
    }

    public void carregaImagem(String caminhoFoto) {
        Log.i("IMG", "Imagem a ser tratada");
        /*
        user.setPhoto(caminhoFoto);
        Bitmap imagem = BitmapFactory.decodeFile(caminhoFoto);
        Bitmap imagemReduzida = Bitmap.createScaledBitmap(imagem, 100, 100, true);
        campoFoto.setImageBitmap(imagemReduzida);
        */
    }

}


text:
import {async, inject, TestComponentBuilder, ComponentFixture} from '@angular/core/testing';
import {AuiNgRadioButtonGroupComponent} from './radio-button-group.component';

describe('RadioButtonGroup Component', () => {
    let items: any[] = [
        {id: 1, name: 'foo', color: 'blue'},
        {id: 2, name: 'bar'},
        {id: 3, name: 'baz'}
    ];
    let radioButtonGroup: ComponentFixture<AuiNgRadioButtonGroupComponent>;

    let changes = [];

    beforeEach(async(inject([TestComponentBuilder], (tcb: TestComponentBuilder) => {
        return tcb.createAsync(
            AuiNgRadioButtonGroupComponent).then((componentFixture: ComponentFixture<AuiNgRadioButtonGroupComponent>) => {
            radioButtonGroup = componentFixture;
            radioButtonGroup.componentInstance.items = items;
            radioButtonGroup.componentInstance.selection = items[0];
            radioButtonGroup.componentInstance.name = 'foobar';
            radioButtonGroup.componentInstance.title = 'My Options';
            radioButtonGroup.componentInstance.idProperty = 'id';
            radioButtonGroup.componentInstance.labelProperty = 'name';

            radioButtonGroup.detectChanges();
        });
    })));

    it('should have a title', () => {
        let title = radioButtonGroup.nativeElement.querySelector('legend');

        expect(title.innerText).toEqual('My Options');
    });

    it('should have a radio button for each option', () => {
        let radioButtons = radioButtonGroup.nativeElement.querySelectorAll('input.radio');

        expect(radioButtons.length).toEqual(items.length);
    });

    it('should check selection option', () => {
        let checkedButtons = radioButtonGroup.nativeElement.querySelectorAll('input.radio:checked');

        expect(checkedButtons.length).toEqual(1);
        expect(checkedButtons[0].parentElement.innerText).toEqual(' foo');
    });

    it('should change selection if radio button is clicked', (done) => {
        radioButtonGroup.componentInstance.onChange = function (item) {

            expect(item).toEqual(items[1]);
            done();
        };
        radioButtonGroup.detectChanges();

        let radioButtons = radioButtonGroup.nativeElement.querySelectorAll('input.radio');
        radioButtons[1].click();
    });

    it('should change selection if lable is clicked', (done) => {
        radioButtonGroup.componentInstance.onChange = function (item) {
            expect(item).toEqual(items[2]);
            done();
        };
        radioButtonGroup.detectChanges();

        let radioButtons = radioButtonGroup.nativeElement.querySelectorAll('.radio label');

        // create custom event, because click only works on buttons
        let event = document.createEvent('Event');
        event.initEvent('click', true, true);

        radioButtons[2].dispatchEvent(event);
    });

});


text:
$(document).ready(function () {
	$('.carousel').carousel({
		interval: 5000 //changes the speed
	});

    $(document).delegate('*[data-toggle="lightbox"]', 'click', function(event) {
        event.preventDefault();
        $(this).ekkoLightbox();
    });
});


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
  <string name="coordinates">Comhordanáidí</string>
  <string name="coordinateTraining">Cleachtadh comhordanáide</string>
  <string name="averageScoreAsWhiteX">Meánscór le bán: %s</string>
  <string name="averageScoreAsBlackX">Meánscór le dubh: %s</string>
  <string name="knowingTheChessBoard">Is scil fichille an-tábhachtach é eolas a bheith agat ar chomhordanáidí an chláir fichille:</string>
  <string name="mostChessCourses">Baineann an chuid is mó de chúrsaí agus cleachtaí fichille úsáid as an nodaireacht ailgéabrach go fairsing.</string>
  <string name="talkToYourChessFriends">Tá sé níos éascaigh labhairt le do chairde fichille, má dtuigeann an bheirt agaibh 'teanga na fichille'.</string>
  <string name="youCanAnalyseAGameMoreEffectively">Is féidir leat cluiche a anailísiú ar bhealach níos éifeachtaí más féidir leat comhordanáidí a aithint go tapa.</string>
  <string name="aSquareNameAppears">Tá comhordanáid le feiceáil ar an gclár agus ní mór duit cliceáil ar an gcearnóg chomhfhreagrach. Tá 30 soicind agat chun an oiread cearnóga agus is féidir a aithint i gceart!</string>
  <string name="startTraining">Tosaigh</string>
</resources>


text:
<?php

    require("../includes/config.php");
    $id = $_SESSION["id"];

    if ($_SERVER["REQUEST_METHOD"] == "GET")
    {
        $rows = CS50::query("SELECT * FROM portfolios WHERE user_id = ?", $id);
        render("sell_form.php", ["title" => "Sell", "positions" => $rows]);
    }
    else
    {
        $symbol = $_POST["symbol"];
        $share_amt = $_POST["share_amt"];

        // error if no symbol or number of shares to buy entered
        if ((empty($symbol)) || empty($share_amt))
        {
            apologize("Please specify stock and number of shares to sell.");
        }

        // validate only whole shares are submitted
        if (preg_match("/^\d+$/", $share_amt) == false)
        {
            apologize("Only whole shares can be sold.");
        }

        // validate is numeric amount
        if (!is_numeric($share_amt))
        {
            apologize("Please enter a valid amount.");
        }

        // confirm user owns sufficient shares for the sale
        $ownership = CS50::query("SELECT * FROM portfolios WHERE user_id = ? AND symbol = ?", $id, $symbol);
        if (empty($ownership))
        {
            apologize("You do not own any {$symbol} stock.");
        }
        else
        {
            $shares = $ownership[0]["shares"];
            $quote = lookup($symbol);
            if ($share_amt > $shares)
            {
                apologize("You do not own enough shares to make this sale.");
            }

            // if all shares of such stock are sold, remove stock entirely
            elseif ($share_amt == $shares)
            {
                CS50::query("DELETE FROM portfolios WHERE user_id = ? and symbol = ?", $id, $symbol);
            }

            // if only some shares sold, update holdings accordingly
            else
            {
                CS50::query("UPDATE portfolios SET shares = ? WHERE symbol = ? and user_id = ?", ($shares - $share_amt), $symbol, $id);
            }

            // update user's cash to account for transaction
            $proceeds = $quote["price"] * $share_amt;
            CS50::query("UPDATE users SET cash = cash + ? WHERE id = ?", $proceeds, $id);

            // record transaction history
            CS50::query("INSERT INTO history (user_id, transaction, symbol, shares, time, price) VALUES (?, 'SELL', ?, ?, CURRENT_TIMESTAMP(), ?)", $id, $symbol, $share_amt, $quote["price"]);

            redirect("/");
        }
    }

?>


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
null

#### Original name
Gloeocystidiellum luteocystidium var. brevisporum S.S. Rattan

### Remarks
null


text:
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

defined('MOODLE_INTERNAL') || die();

require_once("$CFG->libdir/filestorage/file_packer.php");

/**
 * Utility class - handles all packing/unpacking of .mbz files.
 *
 * @package core_files
 * @category files
 * @copyright 2013 The Open University
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
class mbz_packer extends file_packer {
    /**
     * Archive files and store the result in file storage.
     *
     * Any existing file at that location will be overwritten.
     *
     * @param array $files array from archive path => pathname or stored_file
     * @param int $contextid context ID
     * @param string $component component
     * @param string $filearea file area
     * @param int $itemid item ID
     * @param string $filepath file path
     * @param string $filename file name
     * @param int $userid user ID
     * @param bool $ignoreinvalidfiles true means ignore missing or invalid files, false means abort on any error
     * @param file_progress $progress Progress indicator callback or null if not required
     * @return stored_file|bool false if error stored_file instance if ok
     * @throws file_exception If file operations fail
     * @throws coding_exception If any archive paths do not meet the restrictions
     */
    public function archive_to_storage(array $files, $contextid,
            $component, $filearea, $itemid, $filepath, $filename,
            $userid = null, $ignoreinvalidfiles = true, file_progress $progress = null) {
        return $this->get_packer_for_archive_operation()->archive_to_storage($files,
                $contextid, $component, $filearea, $itemid, $filepath, $filename,
                $userid, $ignoreinvalidfiles, $progress);
    }

    /**
     * Archive files and store the result in an OS file.
     *
     * @param array $files array from archive path => pathname or stored_file
     * @param string $archivefile path to target zip file
     * @param bool $ignoreinvalidfiles true means ignore missing or invalid files, false means abort on any error
     * @param file_progress $progress Progress indicator callback or null if not required
     * @return bool true if file created, false if not
     * @throws coding_exception If any archive paths do not meet the restrictions
     */
    public function archive_to_pathname(array $files, $archivefile,
            $ignoreinvalidfiles=true, file_progress $progress = null) {
        return $this->get_packer_for_archive_operation()->archive_to_pathname($files,
                $archivefile, $ignoreinvalidfiles, $progress);
    }

    /**
     * Extract file to given file path (real OS filesystem), existing files are overwritten.
     *
     * @param stored_file|string $archivefile full pathname of zip file or stored_file instance
     * @param string $pathname target directory
     * @param array $onlyfiles only extract files present in the array
     * @param file_progress $progress Progress indicator callback or null if not required
     * @param bool $returnbool Whether to return a basic true/false indicating error state, or full per-file error
     * details.
     * @return array list of processed files (name=>true)
     * @throws moodle_exception If error
     */
    public function extract_to_pathname($archivefile, $pathname,
            array $onlyfiles = null, file_progress $progress = null, $returnbool = false) {
        return $this->get_packer_for_read_operation($archivefile)->extract_to_pathname(
                $archivefile, $pathname, $onlyfiles, $progress, $returnbool);
    }

    /**
     * Extract file to given file path (real OS filesystem), existing files are overwritten.
     *
     * @param string|stored_file $archivefile full pathname of zip file or stored_file instance
     * @param int $contextid context ID
     * @param string $component component
     * @param string $filearea file area
     * @param int $itemid item ID
     * @param string $pathbase file path
     * @param int $userid user ID
     * @param file_progress $progress Progress indicator callback or null if not required
     * @return array list of processed files (name=>true)
     * @throws moodle_exception If error
     */
    public function extract_to_storage($archivefile, $contextid,
            $component, $filearea, $itemid, $pathbase, $userid = null,
            file_progress $progress = null) {
        return $this->get_packer_for_read_operation($archivefile)->extract_to_storage(
                $archivefile, $contextid, $component, $filearea, $itemid, $pathbase,
                $userid, $progress);
    }

    /**
     * Returns array of info about all files in archive.
     *
     * @param string|stored_file $archivefile
     * @return array of file infos
     */
    public function list_files($archivefile) {
        return $this->get_packer_for_read_operation($archivefile)->list_files($archivefile);
    }

    /**
     * Selects appropriate packer for new archive depending on system option
     * and whether required extension is available.
     *
     * @return file_packer Suitable packer
     */
    protected function get_packer_for_archive_operation() {
        global $CFG;
        require_once($CFG->dirroot . '/lib/filestorage/tgz_packer.php');

        if (!empty($CFG->usezipbackups)) {
            // Allow forced use of zip backups.
            return get_file_packer('application/zip');
        } else {
            return get_file_packer('application/x-gzip');
        }
    }

    /**
     * Selects appropriate packer for existing archive depending on file contents.
     *
     * @param string|stored_file $archivefile full pathname of zip file or stored_file instance
     * @return file_packer Suitable packer
     */
    protected function get_packer_for_read_operation($archivefile) {
        global $CFG;
        require_once($CFG->dirroot . '/lib/filestorage/tgz_packer.php');

        if (tgz_packer::is_tgz_file($archivefile)) {
            return get_file_packer('application/x-gzip');
        } else {
            return get_file_packer('application/zip');
        }
    }
}


text:
This readme is under construction.

Please see: `/media/docs/tutorial` for more info.


text:
package cn.lankton.anyshape.demo;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

import cn.lankton.anyshape.AnyshapeImageView;

public class SecondActivity extends AppCompatActivity {

    int colors[] = {Color.BLUE, Color.WHITE, Color.YELLOW, Color.LTGRAY, Color.RED, Color.GREEN, Color.CYAN};
    View root;
    AnyshapeImageView iv_rings;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        root = findViewById(R.id.root);
        iv_rings = (AnyshapeImageView) findViewById(R.id.iv_rings);
        findViewById(R.id.btn_change).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int index = (int)(colors.length * Math.random());
                iv_rings.setBackColor(colors[index]);
            }
        });
    }
}


text:
<?php

namespace WPTest\Console;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\Question;
use Symfony\Component\Yaml\Yaml;
use WPTest\Util\Util;

/**
 * Resets all generated setup and example files
 */
class ResetCommand extends Command
{
    protected function configure()
    {
        $this->setName('reset')
            ->setDescription('Removes all generated setup and example files')
            ->setHelp(<<<EOF
The <info>%command.name%</info> removes all generated setup and example files:

  <info>php %command.full_name%</info>

EOF
            );
    }

    /**
     * @param InputInterface  $input
     * @param OutputInterface $output
     *
     * @return mixed
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $Util = new Util();
        $project_dir = $Util->getProjectDirectory();
        $output->writeln($project_dir);
        $helper = $this->getHelper('question');
        $question = new Question("Are you sure you want to remove ALL generated files created by wp-test init? [type Yes to confirm]: ", '');
        $confirm = strtolower($helper->ask($input, $output, $question));
        if ($confirm != 'yes') {
            $output->writeln('Exited without removing files');
            return 0;
        }
        $output->writeln('Deleting files:');
        $phpspec_config_file = "$project_dir/phpspec.yml";
        $advanced = false;
        if (file_exists($phpspec_config_file)) {
            $advanced = true;
            $phpspec_config = Yaml::parseFile($phpspec_config_file);
            $suites = (array) $phpspec_config['suites'];
            $suite = reset($suites);
            $path_unit_tests = $suite['spec_path'] . DIRECTORY_SEPARATOR . $suite['spec_prefix'];
            $this->deleteFile("$project_dir/$path_unit_tests/ExampleSpec.php", $output);
            $this->deleteFile("$project_dir/{$suite['spec_path']}/phpspec.php", $output);
            $this->deleteFile($phpspec_config_file, $output);
            @rmdir("$project_dir/$path_unit_tests");
        }
        $phpunit_config_file = "$project_dir/phpunit.xml";
        if (file_exists($phpunit_config_file)) {
            $phpunit_config = simplexml_load_file($phpunit_config_file);
            $phpunit_path = (string) $phpunit_config->xpath('//testsuite[@name=\'default\']/directory')[0];
            $phpunit_bootstrap_path = dirname($phpunit_config->xpath('/phpunit')[0]['bootstrap']);
            $this->deleteFile("$project_dir/$phpunit_path/ExampleTest.php", $output);
            $this->deleteFile("$project_dir/$phpunit_bootstrap_path/phpunit.php", $output);
            $this->deleteFile($phpunit_config_file, $output);
            @rmdir("$project_dir/$phpunit_path");
            @rmdir("$project_dir/$phpunit_bootstrap_path");
        }

        $this->deleteFile("$project_dir/phpunit-watcher.yml", $output);
        $this->deleteFile("$project_dir/.phpspec-watcher.yml", $output);
        $this->deleteFile("$project_dir/wp-tests-config.php", $output);

        $output->writeln('Removing additional dependencies:');
        $packages = $advanced ? ['phpspec/phpspec', 'fetzi/phpspec-watcher', 'cyruscollier/phpspec-php-mock'] : ['spatie/phpunit-watcher'];
        $packages[] = $Util::WP_CORE_PACKAGE;
        $command = sprintf('composer remove %s --dev', implode(' ', $packages));
        $output->write(`$command`);
        $output->write(`composer config --unset extra.wordpress-install-dir`);

        return 0;
    }

    /**
     * @param string $name
     * @param OutputInterface $output
     */
    protected function deleteFile(string $name, OutputInterface $output)
    {
        if (!file_exists($name)) {
            return;
        }
        unlink($name);
        $output->writeLn($name);
    }
}


text:
#ifndef FTPSERVER_H
#define FTPSERVER_H

#include <string>
#include <netinet/in.h>
#include <vector>
#include <mutex>
#include <fstream>
#include <signal.h>

 enum States
{
    READY_NEW_USER,
    CHALLENGE_PASSWORD,
    INVALID_LOGIN,
    UNKNOWN
};

/**
 * Contains data required for each connection
 */
struct Data
{
    int bufferSize;
    std::string password;
    States state;
    std::string login;
    std::vector<char> buffer;
    std::string address;
    std::string date_time;
};

class FTPServer
{
public:
    FTPServer(std::string const& address, unsigned int port, unsigned int maxClients, std::string logFile);
    ~FTPServer();
    void run();

private:

    static const char* responseCodes[];
    static const int defaultSize = 16;
    static sig_atomic_t stopFlag;

    /**
     * Receive data from socket
     * @param  asocket socket
     * @param  data    data
     * @return         1 if timeout occured, 2 - rev() error, otherwise 0
     */
    int receive(int asocket, Data &data);

    /**
     * Send FTP response code to socket based on actual state
     * @param asocket Client's socket
     * @param state   Actual state of client
     */
    void sendResponse(int asocket, States state);

    /**
     * Server start sending data to client and receiveing from client
     * @param asocket Client's socket
     * @param data    Reference to client's data
     */
    void startCommunication(int asocket,Data &data);

    /**
     * Received buffer is parsed to USER/LOGIN and actual state
     * @param data Reference to client's data
     */
    void parseCommand(Data &data);

    /**
     * Check if end of buffer contains \r\n
     * @param  data Reference to client's data
     * @return      true if contains \r\n otherwise false
     */
    bool isReadyToParse(Data &data);

    /**
     * Close client's socket and decrecrement counter of all connections(mutex used)
     * @param asocket Client's socket
     */
    void closeConnection(int asocket);

    /**
     * Increment counter of connections
     * @return true if actual connections counter is less than max allowed connections
     */
    bool incConnections();

    /**
     * Get actual time and save it to data.date_time
     */
    void saveTime(Data &data);

    /**
     * Log received client's data (mutex used)
     * @param data Reference to client's data
     */
    void log(Data &data);

    static void signalHandler(int signal);

    unsigned int _port, _maxClients, _connections;
    int _socket;
    std::string _address;
    struct sockaddr_storage _sin;
    struct addrinfo *results, *rp;
    std::ofstream _logFile;
    std::mutex mConnections;
    std::mutex mLog;

};
#endif // !FTPSERVER_H


text:
namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

private:
    Ui::MainWindow *ui;
    QGraphicsScene *scene;          //сцена
    Triangle *triangle;             //триугольник

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
};

#endif // MAINWINDOW_H


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >

<!-- 点击后的颜色 -->
<item android:state_pressed="true" android:color="#66ccff"/>

<!-- 默认 -->
<item android:color="#fff"/>

</selector>


text:
package org.javacc.jjtree;

public class JJTreeNode extends SimpleNode {

  private int myOrdinal;

  public JJTreeNode(int id) {
    super(id);
  }

  public JJTreeNode(JJTreeParser p, int i) {
    this(i);
  }

  public static Node jjtCreate(int id) {
    return new JJTreeNode(id);
  }

  public void jjtAddChild(Node n, int i) {
    super.jjtAddChild(n, i);
    ((JJTreeNode)n).setOrdinal(i);
  }

  public int getOrdinal()
  {
    return myOrdinal;
  }

  public void setOrdinal(int o)
  {
    myOrdinal = o;
  }

  /*****************************************************************
   *
   * The following is added manually to enhance all tree nodes with
   * attributes that store the first and last tokens corresponding to
   * each node, as well as to print the tokens back to the specified
   * output stream.
   *
   *****************************************************************/

  private Token first, last;

  public Token getFirstToken() { return first; }
  public void setFirstToken(Token t) { first = t; }
  public Token getLastToken() { return last;  }
  public void setLastToken(Token t) { last = t; }

  /* This method prints the tokens corresponding to this node
     recursively calling the print methods of its children.
     Overriding this print method in appropriate nodes gives the
     output the added stuff not in the input.  */

  public void print(IO io) {
    /* Some productions do not consume any tokens.  In that case their
       first and last tokens are a bit strange. */
    if (getLastToken().next == getFirstToken()) {
      return;
    }

    Token t1 = getFirstToken();
    Token t = new Token();
    t.next = t1;
    JJTreeNode n;
    for (int ord = 0; ord < jjtGetNumChildren(); ord++) {
      n = (JJTreeNode)jjtGetChild(ord);
      while (true) {
        t = t.next;
        if (t == n.getFirstToken()) break;
        print(t, io);
      }
      n.print(io);
      t = n.getLastToken();
    }
    while (t != getLastToken()) {
      t = t.next;
      print(t, io);
    }
  }

  String translateImage(Token t)
  {
    return t.image;
  }

  String whiteOut(Token t)
  {
    StringBuffer sb = new StringBuffer(t.image.length());

    for (int i = 0; i < t.image.length(); ++i) {
      char ch = t.image.charAt(i);
      if (ch != '\t' && ch != '\n' && ch != '\r' && ch != '\f') {
        sb.append(' ');
      } else {
        sb.append(ch);
      }
    }

    return sb.toString();
  }

  /* Indicates whether the token should be replaced by white space or
     replaced with the actual node variable. */
  private boolean whitingOut = false;

  protected void print(Token t, IO io) {
    Token tt = t.specialToken;
    if (tt != null) {
      while (tt.specialToken != null) tt = tt.specialToken;
      while (tt != null) {
        io.print(TokenUtils.addUnicodeEscapes(translateImage(tt)));
        tt = tt.next;
      }
    }

    /* If we're within a node scope we modify the source in the
       following ways:

       1) we rename all references to `jjtThis' to be references to
       the actual node variable.

       2) we replace all calls to `jjtree.currentNode()' with
       references to the node variable. */

    NodeScope s = NodeScope.getEnclosingNodeScope(this);
    if (s == null) {
      /* Not within a node scope so we don't need to modify the
         source. */
      io.print(TokenUtils.addUnicodeEscapes(translateImage(t)));
      return;
    }

    if (t.image.equals("jjtThis")) {
      io.print(s.getNodeVariable());
      return;
    } else if (t.image.equals("jjtree")) {
      if (t.next.image.equals(".")) {
        if (t.next.next.image.equals("currentNode")) {
          if (t.next.next.next.image.equals("(")) {
            if (t.next.next.next.next.image.equals(")")) {
              /* Found `jjtree.currentNode()' so go into white out
                 mode.  We'll stay in this mode until we find the
                 closing parenthesis. */
              whitingOut = true;
            }
          }
        }
      }
    }
    if (whitingOut) {
      if (t.image.equals("jjtree")) {
        io.print(s.getNodeVariable());
        io.print(" ");
      } else if (t.image.equals(")")) {
        io.print(" ");
        whitingOut = false;
      } else {
        for (int i = 0; i < t.image.length(); ++i) {
          io.print(" ");
        }
      }
      return;
    }

    io.print(TokenUtils.addUnicodeEscapes(translateImage(t)));
  }

  static void openJJTreeComment(IO io, String arg)
  {
    if (arg != null) {
      io.print("/*@bgen(jjtree) " + arg + " */");
    } else {
      io.print("/*@bgen(jjtree)*/");
    }
  }

  static void closeJJTreeComment(IO io)
  {
    io.print("/*@egen*/");
  }

  String getIndentation(JJTreeNode n)
  {
    return getIndentation(n, 0);
  }

  String getIndentation(JJTreeNode n, int offset)
  {
    String s = "";
    for (int i = offset + 1; i < n.getFirstToken().beginColumn; ++i) {
      s += " ";
    }
    return s;
  }

}


text:
"""
Convert a mesh file from one SfePy-supported format to another.

Examples::

  $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk
  $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s2.5
  $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s0.5,2,1
  $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s0.5,2,1 -c 0
  $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.mesh --remesh='q2/0 a1e-8 O9/7 V'
  $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new2.mesh --remesh='rq2/0 a1e-8 O9/7 V'
"""
from __future__ import absolute_import
import sys
import os.path as op
from six.moves import range
sys.path.append('.')

from argparse import ArgumentParser, RawDescriptionHelpFormatter
from sfepy.base.base import nm, output
from sfepy.base.ioutils import remove_files
from sfepy.discrete.fem import Mesh, FEDomain
from sfepy.discrete.fem.meshio import (output_mesh_formats, MeshIO,
                                       supported_cell_types)
from sfepy.discrete.fem.mesh import fix_double_nodes
from sfepy.mesh.mesh_tools import elems_q2t

helps = {
    'scale' : 'scale factor (float or comma-separated list for each axis)'
    ' [default: %(default)s]',
    'center' : 'center of the output mesh (0 for origin or'
    ' comma-separated list for each axis) applied after scaling'
    ' [default: %(default)s]',
    'refine' : 'uniform refinement level [default: %(default)s]',
    'format' : 'output mesh format (overrides filename_out extension)',
    'list' : 'list supported readable/writable output mesh formats',
    'merge' : 'remove duplicate vertices',
    'tri-tetra' : 'convert elements: quad->tri, hexa->tetra',
    '2d' : 'force a 2D mesh by removing the z coordinates - assumes a 3D mesh'
    ' in the xy plane',
    'save-per-mat': 'extract cells by material id and save them into'
    ' separate mesh files with a name based on filename_out and the id'
    ' numbers (preserves original mesh vertices)',

    'remesh' : """when given, remesh the given mesh using tetgen.
      The options can be the following, separated by spaces, in this order: 1.
      "r" causes remeshing of the mesh volume - if not present the mesh surface
      is extracted and used for the volume mesh generation. 2.
      "q[<float>/<float>]" (required) - the two numbers after "q" are a maximum
      radius-edge ratio bound and a minimum dihedral angle bound. 3. "a<float>"
      (optional) - the number imposes a maximum volume constraint on all
      tetrahedra. 4. O[<0-9>/<0-7>] - the two numbers correspond to a mesh
      optimization level and a choice of optimizing operations. 5. "V"
      (optional) - if present, mesh statistics are printed. Consult the tetgen
      documentation for details.""",
}

def _parse_val_or_vec(option, name, parser):
    if option is not None:
        try:
            try:
                option = float(option)
            except ValueError:
                option = [float(ii) for ii in option.split(',')]
            option = nm.array(option, dtype=nm.float64, ndmin=1)
        except:
            output('bad %s! (%s)' % (name, option))
            parser.print_help()
            sys.exit(1)

    return option

def main():
    parser = ArgumentParser(description=__doc__,
                            formatter_class=RawDescriptionHelpFormatter)
    parser.add_argument('-s', '--scale', metavar='scale',
                        action='store', dest='scale',
                        default=None, help=helps['scale'])
    parser.add_argument('-c', '--center', metavar='center',
                        action='store', dest='center',
                        default=None, help=helps['center'])
    parser.add_argument('-r', '--refine', metavar='level',
                        action='store', type=int, dest='refine',
                        default=0, help=helps['refine'])
    parser.add_argument('-f', '--format', metavar='format',
                        action='store', type=str, dest='format',
                        default=None, help=helps['format'])
    parser.add_argument('-l', '--list', action='store_true',
                        dest='list', help=helps['list'])
    parser.add_argument('-m', '--merge', action='store_true',
                        dest='merge', help=helps['merge'])
    parser.add_argument('-t', '--tri-tetra', action='store_true',
                        dest='tri_tetra', help=helps['tri-tetra'])
    parser.add_argument('-2', '--2d', action='store_true',
                        dest='force_2d', help=helps['2d'])
    parser.add_argument('--save-per-mat', action='store_true',
                        dest='save_per_mat', help=helps['save-per-mat'])
    parser.add_argument('--remesh', metavar='options',
                        action='store', dest='remesh',
                        default=None, help=helps['remesh'])
    parser.add_argument('filename_in')
    parser.add_argument('filename_out')
    options = parser.parse_args()

    if options.list:
        output('Supported readable mesh formats:')
        output('--------------------------------')
        output_mesh_formats('r')
        output('')
        output('Supported writable mesh formats:')
        output('--------------------------------')
        output_mesh_formats('w')
        sys.exit(0)

    scale = _parse_val_or_vec(options.scale, 'scale', parser)
    center = _parse_val_or_vec(options.center, 'center', parser)

    filename_in = options.filename_in
    filename_out = options.filename_out

    if options.remesh:
        import tempfile
        import shlex
        import subprocess

        dirname = tempfile.mkdtemp()

        is_surface = options.remesh.startswith('q')
        if is_surface:
            mesh = Mesh.from_file(filename_in)
            domain = FEDomain(mesh.name, mesh)
            region = domain.create_region('surf', 'vertices of surface',
                                          'facet')
            surf_mesh = Mesh.from_region(region, mesh,
                                         localize=True, is_surface=True)

            filename = op.join(dirname, 'surf.mesh')
            surf_mesh.write(filename, io='auto')

        else:
            import shutil

            shutil.copy(filename_in, dirname)
            filename = op.join(dirname, op.basename(filename_in))

        qopts = ''.join(options.remesh.split()) # Remove spaces.
        command = 'tetgen -BFENkACp%s %s' % (qopts, filename)
        args = shlex.split(command)
        subprocess.call(args)

        root, ext = op.splitext(filename)
        mesh = Mesh.from_file(root + '.1.vtk')

        remove_files(dirname)

    else:
        mesh = Mesh.from_file(filename_in)

    if options.force_2d:
        data = list(mesh._get_io_data())
        data[0] = data[0][:, :2]
        mesh = Mesh.from_data(mesh.name, *data)

    if scale is not None:
        if len(scale) == 1:
            tr = nm.eye(mesh.dim, dtype=nm.float64) * scale
        elif len(scale) == mesh.dim:
            tr = nm.diag(scale)
        else:
            raise ValueError('bad scale! (%s)' % scale)
        mesh.transform_coors(tr)

    if center is not None:
        cc = 0.5 * mesh.get_bounding_box().sum(0)
        shift = center - cc
        tr = nm.c_[nm.eye(mesh.dim, dtype=nm.float64), shift[:, None]]
        mesh.transform_coors(tr)

    if options.refine > 0:
        domain = FEDomain(mesh.name, mesh)
        output('initial mesh: %d nodes %d elements'
               % (domain.shape.n_nod, domain.shape.n_el))

        for ii in range(options.refine):
            output('refine %d...' % ii)
            domain = domain.refine()
            output('... %d nodes %d elements'
                   % (domain.shape.n_nod, domain.shape.n_el))

        mesh = domain.mesh

    if options.tri_tetra > 0:
        conns = None
        for k, new_desc in [('3_8', '3_4'), ('2_4', '2_3')]:
            if k in mesh.descs:
                conns = mesh.get_conn(k)
                break

        if conns is not None:
            nelo = conns.shape[0]
            output('initial mesh: %d elements' % nelo)

            new_conns = elems_q2t(conns)
            nn = new_conns.shape[0] // nelo
            new_cgroups = nm.repeat(mesh.cmesh.cell_groups, nn)

            output('new mesh: %d elements' % new_conns.shape[0])
            mesh = Mesh.from_data(mesh.name, mesh.coors,
                                  mesh.cmesh.vertex_groups,
                                  [new_conns], [new_cgroups], [new_desc])

    if options.merge:
        desc = mesh.descs[0]
        coor, ngroups, conns = fix_double_nodes(mesh.coors,
                                                mesh.cmesh.vertex_groups,
                                                mesh.get_conn(desc), 1e-9)
        mesh = Mesh.from_data(mesh.name + '_merged',
                              coor, ngroups,
                              [conns], [mesh.cmesh.cell_groups], [desc])

    if options.save_per_mat:
        desc = mesh.descs[0]
        conns, cgroups = mesh.get_conn(desc), mesh.cmesh.cell_groups
        coors, ngroups = mesh.coors, mesh.cmesh.vertex_groups
        mat_ids = nm.unique(cgroups)

        for mat_id in mat_ids:
            idxs = nm.where(cgroups == mat_id)[0]
            imesh = Mesh.from_data(mesh.name + '_matid_%d' % mat_id,
                                   coors, ngroups,
                                   [conns[idxs]], [cgroups[idxs]], [desc])

            fbase, fext = op.splitext(filename_out)
            ifilename_out = '%s_matid_%d%s' % (fbase, mat_id, fext)
            io = MeshIO.for_format(ifilename_out, format=options.format,
                                   writable=True)
            output('writing %s...' % ifilename_out)
            imesh.write(ifilename_out, io=io)
            output('...done')

    io = MeshIO.for_format(filename_out, format=options.format,
                           writable=True)

    cell_types = ', '.join(supported_cell_types[io.format])
    output('writing [%s] %s...' % (cell_types, filename_out))
    mesh.write(filename_out, io=io)
    output('...done')

if __name__ == '__main__':
    main()


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Drawing;

namespace DennyTalk
{
    public class DialogManager
    {
        public class FilePortRequestInfo
        {
            public bool IsAcknowledged { get; set; }
            public bool IsAccepted { get; set; }
            public Address Address { get; private set; }
            public int NumberOfFiles { get; private set; }
            public TelegramListener TelegramListener { get; private set; }
            public int FileReceivingPort { get; private set; }
            public FilePortRequestInfo(int nFiles, Address address, TelegramListener l, int fileReceivingPort)
            {
                NumberOfFiles = nFiles;
                Address = address;
                TelegramListener = l;
                FileReceivingPort = fileReceivingPort;
            }
        }

        //
        private Messenger messanger;
        private TelegramListener telegramListener;
        private ContactManager contactManager;
        private Account account;
        private History history;
        //
        private MainForm mainForm = new MainForm();
        private DialogForm dialogForm = new DialogForm();

        public event EventHandler CheckUpdates;

        private void InitializeContacts()
        {
            Contact[] contacts = contactManager.GetContacts();
            List<ContactEx> contactInfos = new List<ContactEx>();
            foreach (Contact cont in contacts)
            {
                contactInfos.Add((ContactEx)cont);
            }
            mainForm.ContactList.AddContacts(contactInfos);
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="controller"></param>
        public DialogManager(Messenger messanger)
        {
            this.messanger = messanger;
            telegramListener = this.messanger.TelegramListener;
            contactManager = this.messanger.ContactManager;
            account = this.messanger.Account;
            history = this.messanger.History;
            Initialize();
        }

        private void Initialize()
        {
            InitializeContactManager();

            InitializeTelegramListener();

            InitializeDialogs();

            InitializeContacts();

            MainForm.Avatar = messanger.Account.Avatar;
            MainForm.Nick = account.Nick;
            MainForm.StatusText = account.StatusText;
            MainForm.Status = account.Status;

            messanger.NewClient += new EventHandler<FileReceiverClientEventArgs>(messanger_NewClient);
        }

        private void InitializeDialogs()
        {
            MainForm.AddContactButtonClick += new EventHandler(MainForm_AddContactButtonClick);
            MainForm.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(MainForm_PropertyChanged);
            MainForm.ContactDoubleClick += new EventHandler<ContactInfoEventArgs>(MainForm_ContactDoubleClick);
            MainForm.ConfigButtonClick += new EventHandler(MainForm_ConfigButtonClick);
            MainForm.ContactList.ContactEditRequest += new EventHandler<ContactInfoEventArgs>(ContactList_ContactEditRequest);
            MainForm.ContactList.ContactRemoveRequest += new EventHandler<ContactInfoEventArgs>(ContactList_ContactRemoveRequest);
            MainForm.ContactList.ContactShowInfoRequest += new EventHandler<ContactInfoEventArgs>(ContactList_ContactShowInfoRequest);
            MainForm.CheckUpdates += new EventHandler(dialog_CheckUpdates);
            dialogForm.AccountAddress = account.Address;
            dialogForm.AccountAvatar = account.Avatar;
            dialogForm.AccountNick = account.Nick;
            dialogForm.MessageSend += new EventHandler<MessageSendEventArgs>(DialogForm_MessageSend);
            dialogForm.FormClosing += new FormClosingEventHandler(dialogForm_FormClosing);
            dialogForm.ContactAdd += new EventHandler<ContactInfoEventArgs>(dialogForm_ContactAdd);
            dialogForm.ContactSelected += new EventHandler<ContactInfoEventArgs>(dialogForm_ContactSelected);
            dialogForm.FilesSend += new EventHandler<FilesSendEventArgs>(dialogForm_FilesSend);
            DialogForm.Initialize();
        }

        private void InitializeContactManager()
        {
            contactManager.ContactAdded += new EventHandler<ContactEventArgs>(contactManager_ContactAdded);
            contactManager.ContactRemoved += new EventHandler<ContactEventArgs>(contactManager_ContactRemoved);
            contactManager.ContactChanged+=new EventHandler<ContactEventArgs>(contactManager_ContactChanged);
        }

        private void InitializeTelegramListener()
        {
            telegramListener.FilePortReceived += new EventHandler<FilePortReceivedEventArgs>(telegramListener_FilePortReceived);
            telegramListener.FilePortRequestReceived += new EventHandler<FilePortRequestReceivedEventArgs>(telegramListener_FilePortRequest);
            telegramListener.MessageReceived += new EventHandler<MessageReceivedEventArgs>(telegramListener_MessageReceived);
            telegramListener.UserInfoReceived += new EventHandler<UserInfoReveivedEventArgs>(telegramListener_UserInfoReceived);
            telegramListener.MessageDelivered += new EventHandler<MessageDeliveredEventArgs>(telegramListener_MessageDelivered);
            telegramListener.UserStatusReceived += new EventHandler<UserStatusReceivedEventArgs>(telegramListener_UserStatusReceived);
        }

        void messanger_NewClient(object sender, FileReceiverClientEventArgs e)
        {
            Message msg = FindMessage(e.Client.RequestId, MessageType.FilesRequest,
                (ContactEx)contactManager.GetContactByGuid(e.Client.ContactGuid));
            if (msg != null)
            {
                msg.SetTypeAndTag(MessageType.Files, e.Client);
                e.Client.Message = msg;
            }
        }

        /// <summary>
        /// Ïîëó÷åí îòâåò íà çàïðîñ ïîðòà äëÿ ïåðåäà÷è ôàéëîâ.
        /// </summary>
        void telegramListener_FilePortReceived(object sender, FilePortReceivedEventArgs e)
        {
			/*
            Message msg = FindMessage(e.RequestId, MessageType.FilesRequest, (ContactEx)contactManager.GetContactByAddress(e.Address));
            if (msg != null)
            {
				FilePortRequestInfo info = (FilePortRequestInfo)msg.Tag;
                if (info.IsAcknowledged && info.IsAccepted)
                {
                    StringBuilder b = new StringBuilder();
                    for (int i = 1; i <= info.NumberOfFiles; i++)
                        b.Append("\n" + i + ". ???");
                    msg.Text += b.ToString();
                }
                else
                    msg.Text += "\nTransfering canceled";
            }
			*/
        }

        /// <summary>
        /// Ïîëó÷åí çàïðîñ íà ïåðåäà÷ó ôàéëîâ.
        /// </summary>
        void telegramListener_FilePortRequest(object sender, FilePortRequestReceivedEventArgs e)
        {
            Message msg = new Message(DateTime.Now, "",
                MessageDirection.In, e.Address, MessageType.FilesRequest);
            msg.Tag = new FilePortRequestInfo(e.NumberOfFiles, e.Address, telegramListener, messanger.FileReceivingPort);
            msg.ID = e.RequestId;
            AddMessage(msg, (ContactEx)contactManager.GetContactByAddress(e.Address));
        }

        void contactManager_ContactChanged(object sender, ContactEventArgs e)
        {
            Address addr = e.Contact.Address;
            if (e.PropertyName == "Address")
                addr = (Address)e.OldValue;
            ContactEx cont = MainForm.ContactList.GetContactByAddress(addr);
            if (cont != null)
            {
                switch (e.PropertyName)
                {
                    case "Avatar":
                        cont.Avatar = e.Contact.Avatar;
                        break;
                    case "Address":
                        cont.Address = e.Contact.Address;
                        break;
                    case "Nick":
                        cont.Nick = e.Contact.Nick;
                        break;
                    case "Status":
                        cont.Status = e.Contact.Status;
                        break;
                    case "StatusText":
                        cont.StatusText = e.Contact.StatusText;
                        break;
                }
            }
        }

        void contactManager_ContactRemoved(object sender, ContactEventArgs e)
        {
            MainForm.ContactList.RemoveContactByAddress(e.Contact.Address);
        }

        void contactManager_ContactAdded(object sender, ContactEventArgs e)
        {
            MainForm.ContactList.AddContacts(new ContactEx[] { (ContactEx)e.Contact });
        }

        void telegramListener_UserStatusReceived(object sender, UserStatusReceivedEventArgs e)
        {
            ContactEx cont = MainForm.ContactList.GetContactByAddress(e.Address);
            if (cont != null)
            {
                cont.Status = e.Status;
                cont.StatusText = e.Text;
            }
        }

        void telegramListener_MessageDelivered(object sender, MessageDeliveredEventArgs e)
        {
            DialogUserControl dialog = DialogForm.GetDialog(e.Address);
            if (dialog != null)
            {
                dialog.SetMessageDelivered(e.ID);
            }
        }

        void telegramListener_UserInfoReceived(object sender, UserInfoReveivedEventArgs e)
        {
            DialogUserControl dialog = DialogForm.GetDialog(e.Address);
            if (dialog != null)
            {
                dialog.AccountAvatar = e.Avatar;
                dialog.AccountNick = e.Nick;
                dialog.AccountAddress = e.Address;
            }
        }

        void telegramListener_MessageReceived(object sender, MessageReceivedEventArgs e)
        {
            Message histMessage = new Message(DateTime.Now, e.Text, MessageDirection.In, e.Address, MessageType.Message);
            histMessage.ID = e.ID;
            if (!DialogForm.Visible)
            {
                MainForm.Invoke(new MethodInvoker(delegate()
                {
                    MainForm.SetContactImageAsNewMessage(histMessage, e.Address);
                }));
            }
            else
            {
                MainForm.Invoke(new MethodInvoker(delegate()
                {
                    DialogForm.SetDialogImageAsNewMessage(e.Address);
                    if (!WinFormsHelper.IsFocused(DialogForm))
                        MainForm.SetContactImageAsNewMessage(histMessage, e.Address);
                }));
            }
            DialogUserControl dialog = DialogForm.GetDialog(e.Address);
            if (dialog == null)
            {
                Contact contact = contactManager.GetContactByAddress(e.Address);
                if (contact != null)
                {
                    MainForm.Invoke(new MethodInvoker(delegate()
                    {
                        dialog = DialogForm.AddDialog((ContactEx)contact, new Message[] { histMessage });
                    }));
                }
                else
                {
                    ContactEx contactInfo = new ContactEx();
                    contactInfo.Address = e.Address;
                    contactInfo.Avatar = ImageHelper2.DefaultAvatar;

                    MainForm.Invoke(new MethodInvoker(delegate()
                    {
                        dialog = DialogForm.AddDialog(contactInfo, new Message[] { histMessage });
                    }));

                    telegramListener.RequestUserInfo(e.Address);
                }
            }
            dialog.Invoke(new MethodInvoker(delegate()
            {
                dialog.AddMessage(histMessage);
            }));
        }

        void dialogForm_FilesSend(object sender, FilesSendEventArgs e)
        {
            //StringBuilder b = new StringBuilder();
            //for (int i = 0; i < e.FileNames.Length; i++)
            //    b.AppendLine(string.Format("{0}. {1}", i + 1, System.IO.Path.GetFileName(e.FileNames[i])));
            Message msg = new Message(DateTime.Now, "",
			                          MessageDirection.Out, e.ReceiverContectInfo.Address, MessageType.Files);
            FileSenderConnection conn = messanger.SendFiles(e.ReceiverContectInfo, e.FileNames);
            msg.ID = conn.RequestId;
            msg.Tag = conn;
            conn.Message = msg;
            AddMessage(msg, e.ReceiverContectInfo);
        }

        void DialogForm_MessageSend(object sender, MessageSendEventArgs e)
        {
            TelegramSendResult result = telegramListener.SendMessage(e.Address, e.Text);
            e.ID = result.ID;
            Contact contact = contactManager.GetContactByAddress(e.Address);
            ContactEx contactInfo = new ContactEx();
            contactInfo.Address = e.Address;
            if (contact != null)
            {
                contactInfo.Nick = contact.Nick;
                contactInfo.Avatar = contact.Avatar;
            }
            Message msg = new Message(DateTime.Now, e.Text, MessageDirection.Out, e.Address, MessageType.Message);
            msg.ID = e.ID;
            AddMessage(msg, contactInfo);
        }

        void dialogForm_ContactSelected(object sender, ContactInfoEventArgs e)
        {
            MainForm.ResetContactImage(e.ContactInfo.Address);
            DialogForm.ResetPageImage(e.ContactInfo.Address);
        }

        void dialogForm_ContactAdd(object sender, ContactInfoEventArgs e)
        {
            if (contactManager.GetContactByAddress(e.ContactInfo.Address) == null)
            {
                contactManager.AddContact(e.ContactInfo);
                telegramListener.RequestUserInfo(e.ContactInfo.Address);
            }
        }

        void dialogForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason != CloseReason.ApplicationExitCall
                && e.CloseReason != CloseReason.FormOwnerClosing)
            {
                e.Cancel = true;
                DialogForm.CloseAllDialogs();
                DialogForm.Hide();
            }
        }

        void MainForm_ContactDoubleClick(object sender, ContactInfoEventArgs e)
        {
            DialogForm.Focus();
            if (!DialogForm.HasDialog(e.ContactInfo))
            {
                DialogForm.Show();
                DialogForm.AddDialog(e.ContactInfo, history.GetMessage(e.ContactInfo.Address));
            }
            else
            {
                DialogForm.Show();
                DialogForm.SelectDialog(e.ContactInfo);
            }
            ResetContact(e.ContactInfo.Address);
        }

        void MainForm_AddContactButtonClick(object sender, EventArgs e)
        {
            Contact contact = new ContactEx();
            AddChangeContactDialog dialog = new AddChangeContactDialog();
            if (dialog.ShowDialog(MainForm) == DialogResult.OK)
            {
                contact.Nick = dialog.Host != "" ? dialog.Host : "Unnamed";
                string host = dialog.Host;
                int port = dialog.Port;
                string guid = dialog.Guid;
                if (string.IsNullOrEmpty(host))
                {
                    host = messanger.ServerHost;
                    port = messanger.ServerPort;
                }
                contact.Address = new Address(host, port, guid);
                contact.Avatar = ImageHelper2.DefaultAvatar;
                if (contactManager.AddContact(contact))
                    messanger.TelegramListener.RequestUserInfo(contact.Address);
                else
                    MessageBox.Show("User with this address already exists in your contact list", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        void MainForm_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            switch (e.PropertyName)
            {
                case "Nick":
                    account.Nick = MainForm.Nick;
                    break;
                case "Avatar":
                    account.Avatar = MainForm.Avatar;
                    break;
                case "Status":
                    account.Status = MainForm.Status;
                    break;
                case "StatusText":
                    account.StatusText = MainForm.StatusText;
                    break;
            }
        }

        void MainForm_ConfigButtonClick(object sender, EventArgs e)
        {
            ConfigurationDialog dialog = new ConfigurationDialog();
            dialog.Port = account.Address.Port;
            dialog.Guid = account.Address.Guid;
            dialog.CheckUpdates += dialog_CheckUpdates;
            dialog.ServerHost = messanger.ServerHost;
            dialog.ServerPort = messanger.ServerPort;
            dialog.UpdateServerHost = messanger.UpdateServerHost;
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                account.Address = new Address("127.0.0.1", dialog.Port, dialog.Guid);
                messanger.ServerHost = dialog.ServerHost;
                messanger.ServerPort = dialog.ServerPort;
                messanger.UpdateServerHost = dialog.UpdateServerHost;

            }
            dialog.CheckUpdates -= dialog_CheckUpdates;
        }

        void ContactList_ContactShowInfoRequest(object sender, ContactInfoEventArgs e)
        {
            messanger.TelegramListener.RequestUserInfo(e.ContactInfo.Address);
        }

        void ContactList_ContactRemoveRequest(object sender, ContactInfoEventArgs e)
        {
            if (MessageBox.Show("Remove contact?", "Remove Contact", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                contactManager.RemoveContactByAddress(e.ContactInfo.Address);
            }
        }

        void ContactList_ContactEditRequest(object sender, ContactInfoEventArgs e)
        {
            Contact contact = contactManager.GetContactByAddress(e.ContactInfo.Address);
            if (contact == null)
            {
                MessageBox.Show("Contact not found", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            AddChangeContactDialog dialog = new AddChangeContactDialog();
            dialog.Action = AddChangeContactAction.Change;
            dialog.Guid = contact.Address.Guid;
            dialog.Host = contact.Address.Host;
            dialog.Port = contact.Address.Port;
            if (dialog.ShowDialog(MainForm) == DialogResult.OK)
            {
                contact.Nick = dialog.Host != "" ? dialog.Host :  "Unnamed";
                string host = dialog.Host;
                int port = dialog.Port;
                string guid = dialog.Guid;
                if (string.IsNullOrEmpty(host))
                {
                    host = messanger.ServerHost;
                    port = messanger.ServerPort;
                }
                else if (port == 0)
                {
                    port = 1000;
                }
                contact.Address = new Address(host, port, guid);
                e.ContactInfo.Address = new Address(host, port, guid);
                e.ContactInfo.Nick = contact.Nick;
            }
        }

        void dialog_CheckUpdates(object sender, EventArgs e)
        {
            if (CheckUpdates != null)
                CheckUpdates(sender, e);
        }

        protected Message FindMessage(int requestId, MessageType type, ContactEx contactInfo)
        {
            if (DialogForm.HasDialog(contactInfo.Address))
            {
                DialogUserControl dialog = null;
                MainForm.Invoke(new MethodInvoker(delegate()
                {
                    dialog = DialogForm.SelectDialog(contactInfo.Address);
                }));
                return dialog.FindMessage(requestId, type);
            }
            return null;
        }

        protected void AddMessage(Message msg, ContactEx contactInfo)
        {
            DialogUserControl dialog = null;
            if (!DialogForm.HasDialog(contactInfo.Address))
                MainForm.Invoke(new MethodInvoker(delegate()
                {
                    dialog = DialogForm.AddDialog(contactInfo, new Message[] { msg });
                }));
            else
                MainForm.Invoke(new MethodInvoker(delegate()
                {
                    dialog = DialogForm.SelectDialog(contactInfo.Address);
                }));
            if (dialog != null)
                dialog.AddMessage(msg);
        }

        void ResetContact(Address address)
        {
            MainForm.ResetContactImage(address);
            DialogForm.ResetPageImage(address);
        }

        /// <summary>
        ///
        /// </summary>
        public MainForm MainForm
        {
            get
            {
                return mainForm;
            }
        }

        /// <summary>
        ///
        /// </summary>
        public DialogForm DialogForm
        {
            get
            {
                return dialogForm;
            }
        }

        public void NewVersionAvaliable(Version newVersion)
        {
            MainForm.NewVersionAvaliable(newVersion);
        }
    }
}