text:
package ucar.nc2.ui.grib;

import thredds.featurecollection.FeatureCollectionConfig;
import thredds.inventory.MFile;
import ucar.nc2.grib.collection.GribCdmIndex;
import ucar.nc2.grib.collection.GribCollectionImmutable;
import ucar.nc2.grib.collection.GribCollectionImmutable.Record;
import ucar.nc2.grib.collection.PartitionCollectionImmutable;
import ucar.nc2.grib.coord.Coordinate;
import ucar.nc2.grib.coord.CoordinateRuntime;
import ucar.nc2.grib.coord.CoordinateTime;
import ucar.nc2.grib.coord.CoordinateTime2D;
import ucar.nc2.grib.coord.CoordinateTimeAbstract;
import ucar.nc2.grib.coord.CoordinateTimeIntv;
import ucar.nc2.grib.coord.CoordinateVert;
import ucar.nc2.grib.coord.SparseArray;
import ucar.nc2.grib.coord.TimeCoordIntvValue;
import ucar.nc2.grib.coord.VertCoordValue;
import ucar.nc2.time.*;
import ucar.nc2.ui.MFileTable;
import ucar.nc2.util.Counters;
import ucar.ui.widget.BAMutil;
import ucar.ui.widget.IndependentWindow;
import ucar.ui.widget.PopupMenu;
import ucar.ui.widget.TextHistoryPane;
import ucar.nc2.util.Indent;
import ucar.util.prefs.PreferencesExt;
import ucar.ui.prefs.BeanTable;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.*;
import java.util.List;

/** Show info in GRIB ncx index files. */
public class CdmIndexPanel extends JPanel {
  private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(CdmIndexPanel.class);

  private PreferencesExt prefs;
  private BeanTable<GroupBean> groupTable;
  private BeanTable<VarBean> varTable;
  private BeanTable<CoordBean> coordTable;
  private JSplitPane split, split2, split3;

  private TextHistoryPane infoTA, extraTA;
  private IndependentWindow infoWindow, extraWindow;
  private MFileTable fileTable;

  public CdmIndexPanel(PreferencesExt prefs, JPanel buttPanel) {
    this.prefs = prefs;

    if (buttPanel != null) {
      AbstractButton infoButton = BAMutil.makeButtcon("Information", "Show Info", false);
      infoButton.addActionListener(e -> {
        Formatter f = new Formatter();
        showInfo(f);
        infoTA.setText(f.toString());
        infoTA.gotoTop();
        infoWindow.show();
      });
      buttPanel.add(infoButton);

      AbstractButton filesButton = BAMutil.makeButtcon("nj22/Catalog", "Show Files", false);
      filesButton.addActionListener(e -> {
        if (gc != null)
          showFileTable(gc, null);
      });
      buttPanel.add(filesButton);

      AbstractButton rawButton = BAMutil.makeButtcon("TableAppearence", "Estimate memory use", false);
      rawButton.addActionListener(e -> {
        Formatter f = new Formatter();
        showMemoryEst(f);
        infoTA.setText(f.toString());
        infoTA.gotoTop();
        infoWindow.show();
      });
      buttPanel.add(rawButton);

      AbstractButton checkAllButton = BAMutil.makeButtcon("Select", "Check entire file", false);
      rawButton.addActionListener(e -> {
        Formatter f = new Formatter();
        checkAll(f);
        infoTA.setText(f.toString());
        infoTA.gotoTop();
        infoWindow.show();
      });
      buttPanel.add(checkAllButton);

    }

    PopupMenu varPopup;
    groupTable = new BeanTable<>(GroupBean.class, (PreferencesExt) prefs.node("GroupBean"), false, "GDS group",
        "GribCollectionImmutable.GroupHcs", null);
    groupTable.addListSelectionListener(e -> {
      GroupBean bean = groupTable.getSelectedBean();
      if (bean != null)
        setGroup(bean);
    });

    varPopup = new PopupMenu(groupTable.getJTable(), "Options");
    varPopup.addAction("Show Group Info", new AbstractAction() {
      public void actionPerformed(ActionEvent e) {
        GroupBean bean = groupTable.getSelectedBean();
        if (bean != null && bean.group != null) {
          Formatter f = new Formatter();
          bean.group.show(f);
          infoTA.setText(f.toString());
          infoTA.gotoTop();
          infoWindow.show();
        }
      }
    });
    varPopup.addAction("Show Files Used", new AbstractAction() {
      public void actionPerformed(ActionEvent e) {
        GroupBean bean = groupTable.getSelectedBean();
        if (bean != null && bean.group != null) {
          showFileTable(gc, bean.group);
        }
      }
    });

    varTable = new BeanTable<>(VarBean.class, (PreferencesExt) prefs.node("Grib2Bean"), false, "Variables in group",
        "GribCollectionImmutable.VariableIndex", null);

    varPopup = new PopupMenu(varTable.getJTable(), "Options");
    varPopup.addAction("Show Variable(s)", new AbstractAction() {
      public void actionPerformed(ActionEvent e) {
        List<VarBean> beans = varTable.getSelectedBeans();
        infoTA.clear();
        for (VarBean bean : beans) {
          infoTA.appendLine(bean.v.toStringFrom());
        }
        infoTA.gotoTop();
        infoWindow.show();
      }
    });
    varPopup.addAction("Show Sparse Array", new AbstractAction() {
      public void actionPerformed(ActionEvent e) {
        VarBean bean = varTable.getSelectedBean();
        if (bean != null) {
          Formatter f = new Formatter();
          bean.showSparseArray(f);
          infoTA.setText(f.toString());
          infoTA.gotoTop();
          infoWindow.show();
        }
      }
    });
    varPopup.addAction("Make Variable(s) GribConfig", new AbstractAction() {
      public void actionPerformed(ActionEvent e) {
        List<VarBean> beans = varTable.getSelectedBeans();
        infoTA.clear();
        Formatter f = new Formatter();
        for (VarBean bean : beans)
          bean.makeGribConfig(f);
        infoTA.appendLine(f.toString());
        infoTA.gotoTop();
        infoWindow.show();
      }
    });

    coordTable = new BeanTable<>(CoordBean.class, (PreferencesExt) prefs.node("CoordBean"), false,
        "Coordinates in group", "Coordinates", null);
    varPopup = new PopupMenu(coordTable.getJTable(), "Options");

    varPopup.addAction("Show", new AbstractAction() {
      public void actionPerformed(ActionEvent e) {
        CoordBean bean = coordTable.getSelectedBean();
        if (bean != null) {
          Formatter f = new Formatter();
          bean.coord.showCoords(f);
          infoTA.setText(f.toString());
          infoTA.gotoTop();
          infoWindow.show();
        }
      }
    });

    varPopup.addAction("ShowCompact", new AbstractAction() {
      public void actionPerformed(ActionEvent e) {
        CoordBean bean = coordTable.getSelectedBean();
        if (bean != null) {
          Formatter f = new Formatter();
          bean.coord.showInfo(f, new Indent(2));
          infoTA.setText(f.toString());
          infoTA.gotoTop();
          infoWindow.show();
        }
      }
    });

    varPopup.addAction("Test Time2D isOrthogonal", new AbstractAction() {
      public void actionPerformed(ActionEvent e) {
        CoordBean bean = coordTable.getSelectedBean();
        if (bean != null) {
          Formatter f = new Formatter();
          testOrthogonal(f, bean.coord);
          extraTA.setText(f.toString());
          extraTA.gotoTop();
          extraWindow.show();
        }
      }
    });

    varPopup.addAction("Test Time2D isRegular", new AbstractAction() {
      public void actionPerformed(ActionEvent e) {
        CoordBean bean = coordTable.getSelectedBean();
        if (bean != null) {
          Formatter f = new Formatter();
          testRegular(f, bean.coord);
          extraTA.setText(f.toString());
          extraTA.gotoTop();
          extraWindow.show();
        }
      }
    });

    varPopup.addAction("Show Resolution distribution", new AbstractAction() {
      public void actionPerformed(ActionEvent e) {
        CoordBean bean = coordTable.getSelectedBean();
        if (bean != null) {
          Formatter f = new Formatter();
          bean.showResolution(f);
          infoTA.setText(f.toString());
          infoTA.gotoTop();
          infoWindow.show();
        }
      }
    });

    varPopup.addAction("Compare", new AbstractAction() {
      public void actionPerformed(ActionEvent e) {
        List beans = coordTable.getSelectedBeans();
        if (beans.size() == 2) {
          Formatter f = new Formatter();
          CoordBean bean1 = (CoordBean) beans.get(0);
          CoordBean bean2 = (CoordBean) beans.get(1);
          if (bean1.coord.getType() == Coordinate.Type.time2D && bean2.coord.getType() == Coordinate.Type.time2D)
            compareCoords2D(f, (CoordinateTime2D) bean1.coord, (CoordinateTime2D) bean2.coord);
          else
            compareCoords(f, bean1.coord, bean2.coord);
          infoTA.setText(f.toString());
          infoTA.gotoTop();
          infoWindow.show();
        }
      }
    });

    varPopup.addAction("Try to Merge", new AbstractAction() {
      public void actionPerformed(ActionEvent e) {
        List<CoordBean> beans = coordTable.getSelectedBeans();
        if (beans.size() == 2) {
          Formatter f = new Formatter();
          CoordBean bean1 = beans.get(0);
          CoordBean bean2 = beans.get(1);
          if (bean1.coord.getType() == Coordinate.Type.time2D && bean2.coord.getType() == Coordinate.Type.time2D)
            mergeCoords2D(f, (CoordinateTime2D) bean1.coord, (CoordinateTime2D) bean2.coord);
          else
            f.format("CoordinateTime2D only");
          infoTA.setText(f.toString());
          infoTA.gotoTop();
          infoWindow.show();
        }
      }
    });

    // file popup window
    fileTable = new MFileTable((PreferencesExt) prefs.node("MFileTable"), true);
    fileTable.addPropertyChangeListener(
        evt -> firePropertyChange(evt.getPropertyName(), evt.getOldValue(), evt.getNewValue()));

    /////////////////////////////////////////
    // the info windows
    infoTA = new TextHistoryPane();
    infoWindow = new IndependentWindow("Information", BAMutil.getImage("nj22/NetcdfUI"), infoTA);
    infoWindow.setBounds((Rectangle) prefs.getBean("InfoWindowBounds", new Rectangle(300, 300, 500, 300)));

    extraTA = new TextHistoryPane();
    extraWindow = new IndependentWindow("Extra Information", BAMutil.getImage("nj22/NetcdfUI"), extraTA);
    extraWindow.setBounds((Rectangle) prefs.getBean("ExtraWindowBounds", new Rectangle(300, 300, 500, 300)));

    setLayout(new BorderLayout());

    split3 = new JSplitPane(JSplitPane.VERTICAL_SPLIT, false, groupTable, varTable);
    split3.setDividerLocation(prefs.getInt("splitPos3", 800));

    split2 = new JSplitPane(JSplitPane.VERTICAL_SPLIT, false, split3, coordTable);
    split2.setDividerLocation(prefs.getInt("splitPos2", 800));

    // split = new JSplitPane(JSplitPane.VERTICAL_SPLIT, false, split2, vertCoordTable);
    // split.setDividerLocation(prefs.getInt("splitPos", 500));

    add(split2, BorderLayout.CENTER);
  }

  public void save() {
    groupTable.saveState(false);
    varTable.saveState(false);
    coordTable.saveState(false);
    fileTable.save();
    prefs.putBeanObject("InfoWindowBounds", infoWindow.getBounds());
    prefs.putBeanObject("ExtraWindowBounds", extraWindow.getBounds());
    if (split != null)
      prefs.putInt("splitPos", split.getDividerLocation());
    if (split2 != null)
      prefs.putInt("splitPos2", split2.getDividerLocation());
    if (split3 != null)
      prefs.putInt("splitPos3", split3.getDividerLocation());
  }

  public void clear() {
    if (gc != null) {
      try {
        gc.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    gc = null;
    groupTable.clearBeans();
    varTable.clearBeans();
    coordTable.clearBeans();
  }

  public void showInfo(Formatter f) {
    if (gc == null)
      return;
    gc.showIndex(f);
    f.format("%n");

    f.format("Groups%n");
    List<GroupBean> groups = groupTable.getBeans();
    for (GroupBean bean : groups) {
      f.format("%-50s %d%n", bean.getGroupId(), bean.getGdsHash());
      bean.group.show(f);
    }

    f.format("%n");
    // showFiles(f);
  }

  private void showFileTable(GribCollectionImmutable gc, GribCollectionImmutable.GroupGC group) {
    File dir = gc.getDirectory();
    Collection<MFile> files = (group == null) ? gc.getFiles() : group.getFiles();
    fileTable.setFiles(dir, files);
  }

  private static class SortBySize implements Comparable<SortBySize> {
    Object obj;
    int size;

    private SortBySize(Object obj, int size) {
      this.obj = obj;
      this.size = size;
    }

    public int compareTo(SortBySize o) {
      return Integer.compare(size, o.size);
    }
  }

  private void checkAll(Formatter f) {
    if (gc == null)
      return;
    for (GribCollectionImmutable.Dataset ds : gc.getDatasets()) {
      f.format("Dataset %s%n", ds.getType());
      int bytesTotal = 0;
      int bytesSATotal = 0;
      int coordsAllTotal = 0;

      for (GribCollectionImmutable.GroupGC g : ds.getGroups()) {
        f.format(" Group %s%n", g.getDescription());

        int count = 0;
        for (GribCollectionImmutable.VariableIndex v : g.getVariables()) {
          VarBean bean = new VarBean(v, g);

          if (v instanceof PartitionCollectionImmutable.VariableIndexPartitioned) {
            if (count == 0)
              f.format(" total   VariablePartitioned%n");

            PartitionCollectionImmutable.VariableIndexPartitioned vip =
                (PartitionCollectionImmutable.VariableIndexPartitioned) v;
            int nparts = vip.getNparts();
            int memEstBytes = 368 + nparts * 4; // very rough
            bytesTotal += memEstBytes;
            f.format("%6d %-50s nparts=%6d%n", memEstBytes, bean.getName(), nparts);

          } else {
            if (count == 0)
              f.format(" total   SA  Variable%n");
            try {
              v.readRecords();
              SparseArray<Record> sa = v.getSparseArray();
              int ntracks = sa.getTotalSize();
              int nrecords = sa.getContent().size();
              int memEstForSA = 276 + nrecords * 40 + ntracks * 4;
              int memEstBytes = 280 + memEstForSA;
              f.format("%6d %6d %-50s nrecords=%6d%n", memEstBytes, memEstForSA, bean.getName(), nrecords);
              bytesTotal += memEstBytes;
              bytesSATotal += memEstForSA;

            } catch (IOException e) {
              e.printStackTrace();
            }
          }
          count++;
        }
      }
      int noSA = bytesTotal - bytesSATotal;
      f.format("%n total KBytes=%d kbSATotal=%d kbNoSA=%d%n", bytesTotal / 1000, bytesSATotal / 1000, noSA / 1000);
      f.format("%n");
    }
  }

  private void showMemoryEst(Formatter f) {
    if (gc == null)
      return;

    for (GribCollectionImmutable.Dataset ds : gc.getDatasets()) {
      f.format("Dataset %s%n", ds.getType());
      int bytesTotal = 0;
      int bytesSATotal = 0;
      int coordsAllTotal = 0;

      for (GribCollectionImmutable.GroupGC g : ds.getGroups()) {
        f.format(" Group %s%n", g.getDescription());

        List<SortBySize> sortList = new ArrayList<>(g.getCoordinates().size());
        for (Coordinate vc : g.getCoordinates())
          sortList.add(new SortBySize(vc, vc.estMemorySize()));
        Collections.sort(sortList);

        int coordsTotal = 0;
        f.format("  totalKB  type Coordinate%n");
        for (SortBySize ss : sortList) {
          Coordinate vc = (Coordinate) ss.obj;
          f.format("  %6d %-8s %-40s%n", vc.estMemorySize() / 1000, vc.getType(), vc.getName());
          bytesTotal += vc.estMemorySize();
          coordsTotal += vc.estMemorySize();
        }
        f.format(" %7d KBytes%n", coordsTotal / 1000);
        f.format("%n");
        coordsAllTotal += coordsTotal;

        int count = 0;
        for (GribCollectionImmutable.VariableIndex v : g.getVariables()) {
          VarBean bean = new VarBean(v, g);

          if (v instanceof PartitionCollectionImmutable.VariableIndexPartitioned) {
            if (count == 0)
              f.format(" total   VariablePartitioned%n");

            PartitionCollectionImmutable.VariableIndexPartitioned vip =
                (PartitionCollectionImmutable.VariableIndexPartitioned) v;
            int nparts = vip.getNparts();
            int memEstBytes = 368 + nparts * 4; // very rough
            bytesTotal += memEstBytes;
            f.format("%6d %-50s nparts=%6d%n", memEstBytes, bean.getName(), nparts);

          } else {
            if (count == 0)
              f.format(" total   SA  Variable%n");
            try {
              v.readRecords();
              SparseArray<GribCollectionImmutable.Record> sa = v.getSparseArray();
              int ntracks = sa.getTotalSize();
              int nrecords = sa.getContent().size();
              int memEstForSA = 276 + nrecords * 40 + ntracks * 4;
              int memEstBytes = 280 + memEstForSA;
              f.format("%6d %6d %-50s nrecords=%6d%n", memEstBytes, memEstForSA, bean.getName(), nrecords);
              bytesTotal += memEstBytes;
              bytesSATotal += memEstForSA;

            } catch (IOException e) {
              e.printStackTrace();
            }
          }
          count++;
        }
      }
      int noSA = bytesTotal - bytesSATotal;
      f.format("%n total KBytes=%d kbSATotal=%d kbNoSA=%d coordsAllTotal=%d%n", bytesTotal / 1000, bytesSATotal / 1000,
          noSA / 1000, coordsAllTotal / 1000);
      f.format("%n");
    }
  }

  private void compareCoords(Formatter f, Coordinate coord1, Coordinate coord2) {
    List<?> vals1 = coord1.getValues();
    List<?> vals2 = coord2.getValues();
    f.format("Coordinate %s%n", coord1.getName());
    for (Object val1 : vals1) {
      if (!vals2.contains(val1)) {
        f.format(" %s ", val1);
        if (val1 instanceof Long)
          f.format("(%s) ", CalendarDate.of((Long) val1));
        f.format("MISSING IN 2%n");
      }
    }
    f.format("%nCoordinate %s%n", coord2.getName());
    for (Object val2 : vals2) {
      if (!vals1.contains(val2)) {
        f.format(" %s ", val2);
        if (val2 instanceof Long)
          f.format("(%s) ", CalendarDate.of((Long) val2));
        f.format("MISSING IN 1%n");
      }
    }
  }

  private void compareCoords2D(Formatter f, CoordinateTime2D coord1, CoordinateTime2D coord2) {
    CoordinateRuntime runtimes1 = coord1.getRuntimeCoordinate();
    CoordinateRuntime runtimes2 = coord2.getRuntimeCoordinate();
    int n1 = coord1.getNruns();
    int n2 = coord2.getNruns();
    if (n1 != n2) {
      f.format("Coordinate 1 has %d runtimes, Coordinate 2 has %d runtimes, %n", n1, n2);
    }

    int min = Math.min(n1, n2);
    for (int idx = 0; idx < min; idx++) {
      CoordinateTimeAbstract time1 = coord1.getTimeCoordinate(idx);
      CoordinateTimeAbstract time2 = coord2.getTimeCoordinate(idx);
      f.format("Run %d %n", idx);
      if (!runtimes1.getValue(idx).equals(runtimes2.getValue(idx)))
        f.format("Runtime 1 %s != %s runtime 2%n", runtimes1.getValue(idx), runtimes2.getValue(idx));
      compareCoords(f, time1, time2);
    }
  }

  private void mergeCoords2D(Formatter f, CoordinateTime2D coord1, CoordinateTime2D coord2) {
    if (coord1.isTimeInterval() != coord2.isTimeInterval()) {
      f.format("Coordinate 1 isTimeInterval %s != Coordinate 2 isTimeInterval %s %n", coord1.isTimeInterval(),
          coord2.isTimeInterval());
      return;
    }

    CoordinateRuntime runtimes1 = coord1.getRuntimeCoordinate();
    CoordinateRuntime runtimes2 = coord2.getRuntimeCoordinate();
    int n1 = coord1.getNruns();
    int n2 = coord2.getNruns();
    if (n1 != n2) {
      f.format("Coordinate 1 has %d runtimes, Coordinate 2 has %d runtimes, %n", n1, n2);
    }

    int min = Math.min(n1, n2);
    for (int idx = 0; idx < min; idx++) {
      if (!runtimes1.getValue(idx).equals(runtimes2.getValue(idx)))
        f.format("Runtime 1 %s != %s runtime 2%n", runtimes1.getValue(idx), runtimes2.getValue(idx));
    }

    Set<Object> set1 = makeCoordSet(coord1);
    List<?> list1 = coord1.getOffsetsSorted();
    Set<Object> set2 = makeCoordSet(coord2);
    List<?> list2 = coord2.getOffsetsSorted();

    f.format("%nCoordinate %s%n", coord1.getName());
    for (Object val : list1)
      f.format(" %s,", val);
    f.format(" n=(%d)%n", list1.size());
    testMissing(f, list1, set2);

    f.format("%nCoordinate %s%n", coord2.getName());
    for (Object val : list2)
      f.format(" %s,", val);
    f.format(" (n=%d)%n", list2.size());
    testMissing(f, list2, set1);
  }

  private Set<Object> makeCoordSet(CoordinateTime2D time2D) {
    Set<Object> result = new HashSet<>(100);
    for (int runIdx = 0; runIdx < time2D.getNruns(); runIdx++) {
      Coordinate coord = time2D.getTimeCoordinate(runIdx);
      result.addAll(coord.getValues());
    }
    return result;
  }

  private void testMissing(Formatter f, List<?> test, Set<Object> against) {
    int countMissing = 0;
    for (Object val1 : test) {
      if (!against.contains(val1))
        f.format(" %d: %s MISSING%n", countMissing++, val1);
    }
    f.format("TOTAL MISSING %s%n", countMissing);
  }

  // orthogonal means that all the times can be made into a single time coordinate
  private boolean testOrthogonal(Formatter f, Coordinate c) {
    if (!(c instanceof CoordinateTime2D)) {
      f.format("testOrthogonal only on CoordinateTime2D%n");
      return false;
    }
    CoordinateTime2D time2D = (CoordinateTime2D) c;
    List<CoordinateTimeAbstract> coords = new ArrayList<>();
    for (int runIdx = 0; runIdx < time2D.getNruns(); runIdx++) {
      coords.add(time2D.getTimeCoordinate(runIdx));
    }
    return testOrthogonal(f, coords, true);
  }

  private boolean testOrthogonal(Formatter f, List<CoordinateTimeAbstract> times, boolean show) {
    int max = 0;
    Map<Object, Integer> allCoords = new HashMap<>(1000);
    for (CoordinateTimeAbstract coord : times) {
      max = Math.max(max, coord.getSize());
      for (Object val : coord.getValues()) {
        allCoords.merge(val, 1, (a, b) -> a + b);
      }
    }

    // is the set of all values the same as the component times?
    int totalMax = allCoords.size();
    boolean isOrthogonal = (totalMax == max);

    if (show) {
      f.format("isOrthogonal %s : allCoords.size = %d max of coords=%d%nAllCoords=%n", isOrthogonal, totalMax, max);
      List allList = new ArrayList<>(allCoords.keySet());
      Collections.sort(allList);
      for (Object coord : allList) {
        Integer count = allCoords.get(coord);
        f.format("  %4d %s%n", count, coord);
      }
    }

    return isOrthogonal;
  }

  // regular means that all the times for each offset from 0Z can be made into a single time coordinate (FMRC algo)
  private boolean testRegular(Formatter f, Coordinate c) {
    if (!(c instanceof CoordinateTime2D)) {
      f.format("testOrthogonal only on CoordinateTime2D%n");
      return false;
    }
    CoordinateTime2D time2D = (CoordinateTime2D) c;

    // group time coords by offset hour
    Map<Integer, List<CoordinateTimeAbstract>> hourMap = new HashMap<>();
    for (int runIdx = 0; runIdx < time2D.getNruns(); runIdx++) {
      CoordinateTimeAbstract coord = time2D.getTimeCoordinate(runIdx);
      CalendarDate runDate = coord.getRefDate();
      int hour = runDate.getHourOfDay();
      List<CoordinateTimeAbstract> hg = hourMap.computeIfAbsent(hour, k -> new ArrayList<>());
      hg.add(coord);
    }

    // see if each offset hour is orthogonal
    boolean ok = true;
    for (int hour : hourMap.keySet()) {
      List<CoordinateTimeAbstract> hg = hourMap.get(hour);
      boolean isOrthogonal = testOrthogonal(f, hg, false);
      f.format("Hour %d: isOrthogonal=%s%n", hour, isOrthogonal);
      ok &= isOrthogonal;
    }
    f.format("%nAll are orthogonal: %s%n", ok);
    if (ok)
      return true;

    for (int hour : hourMap.keySet()) {
      List<CoordinateTimeAbstract> hg = hourMap.get(hour);
      f.format("Hour %d: %n", hour);
      testOrthogonal(f, hg, true);
      f.format("%n");
    }
    return false;
  }

  private boolean testOrthogonal(Formatter f, List<CoordinateTimeAbstract> times) {
    int max = 0;
    Set<Object> allCoords = new HashSet<>(100);
    for (CoordinateTimeAbstract coord : times) {
      max = Math.max(max, coord.getSize());
      allCoords.addAll(coord.getValues());
    }

    // is the set of all values the same as the component times?
    int totalMax = allCoords.size();
    boolean isOrthogonal = (totalMax == max);
    f.format("isOrthogonal %s : allCoords.size = %d max of coords=%d%nAllCoords=%n", isOrthogonal, totalMax, max);
    for (Object coord : allCoords) {
      f.format("  %s%n", coord);
    }
    return isOrthogonal;
  }

  /*
   * private void compareFiles(Formatter f) throws IOException {
   * if (gc == null) return;
   * List<String> canon = new ArrayList<>(gc.getFilenames());
   * Collections.sort(canon);
   *
   * File idxFile = new File(gc.getIndexFilepathInCache());
   * File dir = idxFile.getParentFile();
   * File[] files = dir.listFiles(new FilenameFilter() {
   * public boolean accept(File dir, String name) {
   * return name.endsWith(".ncx");
   * }
   * });
   *
   * if (files == null) {
   * // File.listFiles() returns null instead of throwing an exception. Dumb.
   * throw new RuntimeException(String.format("Either an I/O error occurred, or \"%s\" is not a directory.", dir));
   * }
   *
   * int total = 0;
   * for (File file : files) {
   * RandomAccessFile raf = new RandomAccessFile(file.getPath(), "r");
   * GribCollectionImmutable cgc = Grib2CollectionBuilderFromIndex.readFromIndex(file.getName(), raf, null, false,
   * logger);
   * List<String> cfiles = new ArrayList<>(cgc.getFilenames());
   * Collections.sort(cfiles);
   * f.format("Compare files in %s to canonical files in %s%n", file.getPath(), idxFile.getPath());
   * compareSortedList(f, canon.iterator(), cfiles.iterator());
   * f.format("  Compared %d files to %d files%n%n", cfiles.size(), canon.size());
   * raf.close();
   * total += cfiles.size();
   * }
   * f.format("Total files = %d%n%n", total);
   * }
   */

  private void compareSortedList(Formatter f, Iterator<String> i1, Iterator<String> i2) {
    String s1 = null, s2 = null;
    boolean need1 = true, need2 = true;
    while (true) {
      if (need1)
        s1 = (i1.hasNext()) ? i1.next() : null;
      if (need2)
        s2 = (i2.hasNext()) ? i2.next() : null;

      need1 = true;
      need2 = true;

      if (s1 == null && s2 == null)
        break;
      if (s1 == null)
        f.format(" extra file = %s%n", s2);
      else if (s2 == null)
        f.format(" missing file = %s%n", s1);
      else {
        int pos = s1.lastIndexOf("/");
        String name1 = s1.substring(pos);
        name1 = name1.substring(1, name1.indexOf("gdas"));
        String name2 = s2.substring(pos);
        name2 = name2.substring(1, name2.indexOf("gdas"));
        int val = name1.compareTo(name2);
        if (val < 0) { // s1 < s2
          f.format(" missing file = %s%n", s1);
          need2 = false;
        } else if (val > 0) {
          f.format(" extra file = %s%n", s2);
          need1 = false;
        }
      }

    }
  }

  ///////////////////////////////////////////////
  Path indexFile;
  GribCollectionImmutable gc;
  Collection<MFile> gcFiles;
  FeatureCollectionConfig config = new FeatureCollectionConfig();

  public void setIndexFile(Path indexFile, FeatureCollectionConfig config) throws IOException {
    if (gc != null)
      gc.close();

    this.indexFile = indexFile;
    this.config = config;
    gc = GribCdmIndex.openCdmIndex(indexFile.toString(), config, false, logger);
    if (gc == null)
      throw new IOException("File not a grib collection index file");

    List<GroupBean> groups = new ArrayList<>();

    for (GribCollectionImmutable.Dataset ds : gc.getDatasets())
      for (GribCollectionImmutable.GroupGC g : ds.getGroups())
        groups.add(new GroupBean(g, ds.getType().toString()));

    if (!groups.isEmpty())
      setGroup(groups.get(0));
    else {
      varTable.clearBeans();
      coordTable.clearBeans();
    }

    groupTable.setBeans(groups);
    groupTable.setHeader(indexFile.toString());
    gcFiles = gc.getFiles();
  }

  private void setGroup(GroupBean bean) {
    bean.clear();
    List<VarBean> vars = new ArrayList<>();
    for (GribCollectionImmutable.VariableIndex v : bean.group.getVariables()) {
      VarBean vbean = new VarBean(v, bean.group);
      vars.add(vbean);
      bean.nrecords += vbean.getNrecords();
      bean.ndups += vbean.getNdups();
      bean.nmissing += vbean.getNmissing();
    }
    varTable.setBeans(vars);

    int count = 0;
    List<CoordBean> coords = new ArrayList<>();
    for (Coordinate vc : bean.group.getCoordinates())
      coords.add(new CoordBean(vc, count++));
    coordTable.setBeans(coords);
  }

  /*
   * private void showFiles(Formatter f) {
   * if (gc == null) return;
   * if (gc.getFiles() != null) {
   * List<MFile> fs = new ArrayList<>(gc.getFiles());
   * Map<MFile, Integer> map = new HashMap<>(fs.size() * 2);
   *
   * int count = 0;
   * f.format("In order:%n");
   * for (MFile file : fs) {
   * f.format("%5d %60s lastModified=%s%n", count, file.getName(), CalendarDateFormatter.toDateTimeString(new
   * Date(file.getLastModified())));
   * map.put(file, count);
   * count++;
   * }
   *
   * f.format("%nsorted:%n");
   * Collections.sort(fs);
   * int last = -1;
   * for (MFile file : fs) {
   * int num = map.get(file);
   * f.format("%s%5d %s%n", (num < last) ? "***" : "", num, file.getPath());
   * }
   * }
   *
   * if (gc instanceof PartitionCollection) {
   * PartitionCollection pc = (PartitionCollection) gc;
   * for (PartitionCollection.Partition part : pc.getPartitions())
   * f.format("%s%n", part);
   * }
   *
   * f.format("============%n%s%n", gc);
   * }
   */

  ////////////////////////////////////////////////////////////////////////////

  public class GroupBean {
    GribCollectionImmutable.GroupGC group;
    String type;
    int nrecords, nmissing, ndups;

    public GroupBean() {}

    public GroupBean(GribCollectionImmutable.GroupGC g, String type) {
      this.group = g;
      this.type = type;

      for (GribCollectionImmutable.VariableIndex vi : group.getVariables()) {
        nrecords += vi.getNrecords();
        ndups += vi.getNdups();
        nmissing += vi.getNmissing();
      }
    }

    void clear() {
      nmissing = 0;
      ndups = 0;
      nrecords = 0;
    }

    public String getGroupId() {
      return group.getId();
    }

    public int getGdsHash() {
      return group.getGdsHash().hashCode();
    }

    public int getNrecords() {
      return nrecords;
    }

    public String getType() {
      return type;
    }

    public int getNFiles() {
      int n = group.getNFiles();
      if (n == 0) {
        if (gc instanceof PartitionCollectionImmutable)
          n = ((PartitionCollectionImmutable) gc).getPartitionSize();
      }
      return n;
    }

    public int getNruntimes() {
      return group.getNruntimes();
    }

    public int getNCoords() {
      return group.getCoordinates().size();
    }

    public int getNVariables() {
      return group.getVariables().size();
    }

    public int getNmissing() {
      return nmissing;
    }

    public int getNdups() {
      return ndups;
    }
  }

  public class CoordBean implements Comparable<CoordBean> {
    Coordinate coord;
    int idx;
    double start, end, resol;
    Comparable resolMode;
    Counters counters;

    // no-arg constructor

    public CoordBean() {}

    public CoordBean(Coordinate coord, int idx) {
      this.coord = coord;
      this.idx = idx;
      counters = coord.calcDistributions();
      resolMode = counters.get("resol").getMode();

      if (coord instanceof CoordinateRuntime) {
        CoordinateRuntime runtime = (CoordinateRuntime) coord;
        List<Double> offsets = runtime.getOffsetsInTimeUnits();
        double offsetFromMaster = runtime.getOffsetInTimeUnits(gc.getMasterFirstDate());

        int n = offsets.size();
        start = offsets.get(0) + offsetFromMaster;
        end = offsets.get(n - 1) + offsetFromMaster;
        resol = (n > 1) ? (end - start) / (n - 1) : 0.0;

      } else if (coord instanceof CoordinateTime2D) {
        CoordinateTime2D time = (CoordinateTime2D) coord;
        List<?> offsets = time.getOffsetsSorted();
        int n = offsets.size();
        // double offsetFromMaster = time.getOffsetInTimeUnits(gc.getMasterFirstDate());

        if (time.isTimeInterval()) {
          start = ((TimeCoordIntvValue) offsets.get(0)).getBounds1(); // + offsetFromMaster;
          end = ((TimeCoordIntvValue) offsets.get(n - 1)).getBounds2(); // + offsetFromMaster;
          resol = (n > 1) ? (end - start) / (n - 1) : 0.0;

        } else {
          start = (Integer) offsets.get(0); // + offsetFromMaster;
          end = (Integer) offsets.get(n - 1); // + offsetFromMaster;
          resol = (n > 1) ? (end - start) / (n - 1) : 0.0;
        }

      } else if (coord instanceof CoordinateTime) {
        CoordinateTime time = (CoordinateTime) coord;
        List<Integer> offsets = time.getOffsetSorted();
        int n = offsets.size();
        double offsetFromMaster = time.getOffsetInTimeUnits(gc.getMasterFirstDate());
        start = offsets.get(0) + offsetFromMaster;
        end = offsets.get(n - 1) + offsetFromMaster;
        resol = (n > 1) ? (end - start) / (n - 1) : 0.0;

      } else if (coord instanceof CoordinateTimeIntv) {
        CoordinateTimeIntv time = (CoordinateTimeIntv) coord;
        List<TimeCoordIntvValue> offsets = time.getTimeIntervals();
        double offsetFromMaster = time.getOffsetInTimeUnits(gc.getMasterFirstDate());
        int n = offsets.size();
        start = offsets.get(0).getBounds1() + offsetFromMaster;
        end = offsets.get(n - 1).getBounds2() + offsetFromMaster;

      } else if (coord instanceof CoordinateVert) {
        CoordinateVert vert = (CoordinateVert) coord;
        List<VertCoordValue> offsets = vert.getLevelSorted();
        int n = offsets.size();
        if (vert.isLayer()) {
          start = offsets.get(0).getValue1();
          end = offsets.get(n - 1).getValue2();
          resol = (n > 1) ? (end - start) / (n - 1) : 0.0;
        } else {
          start = offsets.get(0).getValue1();
          end = offsets.get(n - 1).getValue1();
          resol = (n > 1) ? (end - start) / (n - 1) : 0.0;
        }
      }

    }

    private void showResolution(Formatter f) {
      counters.show(f);
    }

    public double getStart() {
      return start;
    }

    public double getEnd() {
      return end;
    }

    public double getResol() {
      return resol;
    }

    public String getResolMode() {
      return (resolMode == null) ? "null" : resolMode.toString();
    }

    public String getValues() {
      Formatter f = new Formatter();
      if (coord instanceof CoordinateRuntime) {
        CoordinateRuntime runtime = (CoordinateRuntime) coord;
        f.format("%s %s", runtime.getFirstDate(), runtime.getLastDate());

      } else if (coord instanceof CoordinateTime2D) {
        CoordinateTime2D coord2D = (CoordinateTime2D) coord;
        CalendarDateRange dr = coord2D.makeCalendarDateRange(null); // default calendar
        f.format("%s %s", dr.getStart(), dr.getEnd());

      } else {
        if (coord.getValues() == null)
          return "";
        for (Object val : coord.getValues())
          f.format("%s,", val);
      }
      return f.toString();
    }

    public String getType() {
      if (coord instanceof CoordinateTime2D) {
        CoordinateTime2D c2d = (CoordinateTime2D) coord;
        Formatter f = new Formatter();
        f.format("%s %s", coord.getType(), (c2d.isTimeInterval() ? "intv" : "offs"));
        if (c2d.isOrthogonal())
          f.format(" ort");
        if (c2d.isRegular())
          f.format(" reg");
        return f.toString();
      } else {
        return coord.getType().toString();
      }
    }

    public String getSize() {
      if (coord instanceof CoordinateTime2D) {
        CoordinateTime2D c2d = (CoordinateTime2D) coord;
        Formatter f = new Formatter();
        f.format("%d X %d (%d)", c2d.getRuntimeCoordinate().getSize(), c2d.getNtimes(), coord.getSize());
        return f.toString();
      } else {
        return Integer.toString(coord.getSize());
      }
    }

    public int getCode() {
      return coord.getCode();
    }

    public int getIndex() {
      return idx;
    }

    public String getUnit() {
      return coord.getUnit();
    }

    public String getRefDate() {
      if (coord instanceof CoordinateTimeAbstract)
        return ((CoordinateTimeAbstract) coord).getRefDate().toString();
      else if (coord instanceof CoordinateRuntime)
        return ((CoordinateRuntime) coord).getFirstDate().toString();
      else
        return "";
    }

    public String getName() {
      String intvName = null;
      if (coord instanceof CoordinateTimeIntv) {
        CoordinateTimeIntv timeiCoord = (CoordinateTimeIntv) coord;
        intvName = timeiCoord.getTimeIntervalName();
      }
      if (coord instanceof CoordinateTime2D) {
        CoordinateTime2D timeiCoord = (CoordinateTime2D) coord;
        intvName = timeiCoord.getTimeIntervalName();
      }

      return (intvName == null) ? coord.getName() : coord.getName() + " (" + intvName + ")";
    }

    @Override
    public int compareTo(CoordBean o) {
      return getType().compareTo(o.getType());
    }

    void showCoords(Formatter f) {
      coord.showCoords(f);
    }
  }

  ////////////////////////////////////////////////////////////////////////////////////

  public static class VarBean {
    GribCollectionImmutable.VariableIndex v;
    GribCollectionImmutable.GroupGC group;
    String name;

    public VarBean() {}

    public VarBean(GribCollectionImmutable.VariableIndex vindex, GribCollectionImmutable.GroupGC group) {
      this.v = vindex;
      this.group = group;
      this.name = vindex.makeVariableName();
    }

    public String getIndexes() {
      Formatter f = new Formatter();
      for (int idx : v.getCoordinateIndex())
        f.format("%d,", idx);
      return f.toString();
    }

    public String getIntvName() {
      return v.getIntvName();
    }

    public int getCdmHash() {
      return v.hashCode();
    }

    public String getGroupId() {
      return group.getId();
    }

    public String getVariableId() {
      return v.getDiscipline() + "-" + v.getCategory() + "-" + v.getParameter();
    }

    public String getName() {
      return name;
    }

    public int getNdups() {
      return v.getNdups();
    }

    public int getNrecords() {
      return v.getNrecords();
    }

    public int getNmissing() {
      int n = v.getSize();
      return n - v.getNrecords();
    }

    public int getSize() {
      return v.getSize();
    }

    public void makeGribConfig(Formatter f) {
      f.format("<variable id='%s'/>%n", getVariableId());
    }

    private void showSparseArray(Formatter f) {

      if (v instanceof PartitionCollectionImmutable.VariableIndexPartitioned) {
        PartitionCollectionImmutable.VariableIndexPartitioned vip =
            (PartitionCollectionImmutable.VariableIndexPartitioned) v;
        vip.show(f);
      } else {
        // make sure sparse array has been read in.
        try {
          v.readRecords();

          if (v.getSparseArray() != null) {
            SparseArray<GribCollectionImmutable.Record> sa = v.getSparseArray();
            sa.showInfo(f, null);
            f.format("%n");
            sa.showTracks(f);
            f.format("%n");
            sa.showContent(f);
          }
        } catch (IOException e) {
          logger.warn("Failed to showSparseArray for variable " + v, e);
        }
      }
    }

    /*
     * private void showRecords(Formatter f) {
     *
     * try {
     * GribCollectionImmutable.Record[] records = v.getRecords();
     * if (records.length == 0) {
     * f.format("this index has no records%n");
     * return;
     * }
     *
     * f.format("%s%n%n", v.toStringComplete());
     * f.format(" isTimeInterval=%s hasVert=%s%n", tcoord.isInterval(), (vcoord != null));
     * f.format(" Show records (file,pos)%n");
     *
     * if (tcoord.isInterval()) {
     * if (vcoord == null)
     * showRecords2Dintv(f, tcoord.getIntervals(), records);
     * else
     * showRecords2Dintv(f, vcoord, tcoord.getIntervals(), records);
     * } else {
     * if (vcoord == null)
     * showRecords(f, tcoord.getCoords(), records);
     * else
     * showRecords(f, vcoord, tcoord.getCoords(), records);
     * }
     * } catch (IOException ioe) {
     * ioe.printStackTrace();
     * }
     * }
     *
     * private void showRecords(Formatter f, List<Integer> values, GribCollectionImmutable.Record[] records) throws
     * IOException {
     * f.format(" time (down)%n");
     *
     * for (int timeIdx = 0; timeIdx < v.ntimes; timeIdx++) {
     * f.format("%10s = ", values.get(timeIdx));
     * int idx = GribCollectionImmutable.calcIndex(timeIdx, 0, 0, v.nens, v.nverts);
     * GribCollectionImmutable.Record r = records[idx];
     * if (r == null) f.format("null");
     * else f.format("(%d,%8d) ", r.fileno, r.pos);
     * f.format("%n");
     * }
     *
     * f.format("%n Show records in order%n");
     * int count = 0;
     * for (GribCollectionImmutable.Record r : records) {
     * if (r == null) f.format("null%n");
     * else f.format("%5d = (%d,%8d)%n", count, r.fileno, r.pos);
     * count++;
     * }
     * f.format("%n");
     *
     * }
     *
     * private void showRecords(Formatter f, VertCoord vcoord, List<Integer> values, GribCollectionImmutable.Record[]
     * records) throws IOException {
     * f.format(" time (down) vertLevel (across) %n");
     *
     * f.format("%12s ", " ");
     * List<VertCoord.Level> levels = vcoord.getCoords();
     * boolean isLayer = vcoord.isLayer();
     * for (int j = 0; j < levels.size(); j++)
     * f.format("%6s ", levels.get(j).toString(isLayer));
     * f.format("%n");
     *
     * for (int timeIdx = 0; timeIdx < v.ntimes; timeIdx++) {
     * f.format("%10s = ", values.get(timeIdx));
     * for (int vertIdx = 0; vertIdx < vcoord.getSize(); vertIdx++) {
     * int idx = GribCollectionImmutable.calcIndex(timeIdx, 0, vertIdx, v.nens, v.nverts);
     * GribCollectionImmutable.Record r = records[idx];
     * if (r == null) f.format("null");
     * else f.format("(%d,%8d) ", r.fileno, r.pos);
     * }
     * f.format("%n");
     * }
     *
     * f.format("%n Show records in order%n");
     * int count = 0;
     * for (GribCollectionImmutable.Record r : records) {
     * if (r == null) f.format("null%n");
     * else f.format("%5d = (%d,%8d)%n", count, r.fileno, r.pos);
     * count++;
     * }
     * f.format("%n");
     *
     * }
     *
     * void showRecords2Dintv(Formatter f, VertCoord vcoord, List<TimeCoordIntvValue> tinvs,
     * GribCollectionImmutable.Record[] records) throws IOException {
     * f.format(" timeIntv (down) vertLevel (across) %n");
     *
     * f.format("%12s ", " ");
     * List<VertCoord.Level> levels = vcoord.getCoords();
     * boolean isLayer = vcoord.isLayer();
     * for (VertCoord.Level level : levels)
     * f.format("%13s ", level.toString(isLayer));
     * f.format("%n");
     *
     * for (int timeIdx = 0; timeIdx < v.ntimes; timeIdx++) {
     * f.format("%10s = ", tinvs.get(timeIdx));
     * Formatter filenames = new Formatter();
     * for (int vertIdx = 0; vertIdx < vcoord.getSize(); vertIdx++) {
     * int idx = GribCollectionImmutable.calcIndex(timeIdx, 0, vertIdx, v.nens, v.nverts);
     * GribCollectionImmutable.Record r = records[idx];
     * //f.format("%3d %10d ", r.fileno, r.drsPos);
     * if (r == null || r.pos == 0)
     * f.format("(%4d,%6d) ", -1, -1);
     * else {
     * f.format("(%4d,%6d) ", r.fileno, r.pos);
     * filenames.format(" %s,", getFilename(r.fileno));
     * }
     * }
     * f.format(" == %s%n", filenames);
     * }
     * }
     *
     * private String getFilename(int fileno) {
     * MFile want = gcFiles.get(fileno);
     * File wantFile = new File(gc.getDirectory(), want.getPath());
     * return wantFile.getPath();
     * }
     *
     * void showRecords2Dintv(Formatter f, List<TimeCoordIntvValue> tinvs, GribCollectionImmutable.Record[] records)
     * throws IOException {
     * f.format(" timeIntv (down) %n");
     *
     * for (int timeIdx = 0; timeIdx < v.ntimes; timeIdx++) {
     * f.format("%10s = ", tinvs.get(timeIdx));
     * int idx = GribCollectionImmutable.calcIndex(timeIdx, 0, 0, v.nens, v.nverts);
     * GribCollectionImmutable.Record r = records[idx];
     * //f.format("%3d %10d ", r.fileno, r.drsPos);
     * f.format("%6d ", (r == null ? -1 : r.fileno));
     * f.format("%n");
     * }
     * }
     *
     * void sendFilesToGrib2Collection() {
     * try {
     * Set<Integer> filenos = new HashSet<>();
     * for (GribCollectionImmutable.Record r : v.getRecords()) {
     * if (r != null && r.pos > 0)
     * filenos.add(r.fileno);
     * }
     * Formatter f = new Formatter();
     *
     * f.format("list:");
     * Iterator<Integer> iter = filenos.iterator();
     * while (iter.hasNext()) {
     * f.format("%s;", getFilename(iter.next()));
     * }
     * firePropertyChange("openGrib2Collection", null, f.toString());
     *
     * } catch (IOException ioe) {
     * ioe.printStackTrace();
     * }
     *
     * }
     */

  }

  /*
   * private void showRecordsInPartition(Formatter f) {
   * try {
   * PartitionCollection.VariableIndexPartitioned vp = (PartitionCollection.VariableIndexPartitioned) v;
   * showPartitionInfo(vp, f);
   *
   * } catch (IOException ioe) {
   * ioe.printStackTrace();
   * }
   * }
   *
   * private void showPartitionInfo(PartitionCollection.VariableIndexPartitioned vP, Formatter f) throws IOException {
   *
   * PartitionCollection tp = (PartitionCollection) gc;
   * tp.setPartitionIndexReletive();
   *
   * TimeCoordUnion timeCoordP = (TimeCoordUnion) vP.getTimeCoord();
   * VertCoord vcoord = vP.getVertCoord();
   * EnsCoord ecoord = vP.getEnsCoord();
   * int ntimes = (timeCoordP == null) ? 0 : timeCoordP.getSize();
   * int nverts = (vcoord == null) ? 1 : vcoord.getSize();
   * int nens = (ecoord == null) ? 1 : ecoord.getSize();
   *
   * for (int timeIdx = 0; timeIdx < ntimes; timeIdx++) {
   *
   * TimeCoordUnion.Val val = timeCoordP.getVal(timeIdx);
   * int partno = val.getPartition();
   * GribCollectionImmutable.VariableIndex vindex = vP.getVindex(partno); // the variable in this partition
   * f.format("time = %d val = %s partition = %d%n", timeIdx, val, partno);
   *
   * for (int ensIdx = 0; ensIdx < nens; ensIdx++) {
   * if (nens > 1) f.format(" ens = %d%n", ensIdx);
   *
   * for (int levelIdx = 0; levelIdx <= nverts; levelIdx++) {
   * if (nverts > 1) f.format("  vert = %d%n", levelIdx);
   *
   * // where does this record go in the result ??
   * int resultIndex = GribCollectionImmutable.calcIndex(timeIdx, ensIdx, levelIdx, nens, nverts);
   *
   * // where does this record come from ??
   * int recordIndex = -1;
   *
   * int flag = vP.flag[partno]; // see if theres a mismatch with vert or ens coordinates
   * if (flag == 0) { // no problem
   * recordIndex = GribCollectionImmutable.calcIndex(val.getIndex(), ensIdx, levelIdx, vindex.nens, vindex.nverts);
   *
   * } else { // problem - must match coordinates
   * recordIndex = GribCollectionImmutable.calcIndex(val.getIndex(), ensIdx, levelIdx, flag, vindex.getEnsCoord(),
   * vindex.getVertCoord(),
   * vP.getEnsCoord(), vP.getVertCoord());
   * }
   *
   * f.format("   recordIndex=%d / %d, resultIndex=%d,  flag=%d%n", recordIndex, vindex.records.length, resultIndex,
   * flag);
   * if (flag == 0) f.format("   time=%d, ens=%d, level=%d, nens=%d, nverts=%d", val.getIndex(), ensIdx, levelIdx,
   * vindex.nens, vindex.nverts);
   * else f.format("   time=%d, ens=%d, level=%d, flag=%d, nens=%s, vert=%s ensp=%s, vertp=%s", val.getIndex(), ensIdx,
   * levelIdx, flag,
   * vindex.getEnsCoord(), vindex.getVertCoord(), vP.getEnsCoord(), vP.getVertCoord());
   *
   * }
   * }
   * }
   * }
   */
}


text:
import { Button, CheckCircleFillIcon, Flex, Text, Touchable } from "@artsy/palette-mobile"
import { last } from "lodash"
import { useEffect, useRef, useState } from "react"
import { ActivityIndicator } from "react-native"
import FileViewer from "react-native-file-viewer"
import RNFetchBlob, { FetchBlobResponse, StatefulPromise } from "rn-fetch-blob"
import { GlobalStore } from "app/store/GlobalStore"
import { getUrlExtension } from "shared/utils"
import { formatBytes } from "shared/utils/formatBytes"
import { FileTypeIcon } from "./FileTypeIcon"

export interface DocumentEntity {
  id: string
  url: string
  size: number
  title: string
}

interface DocumentGridItemProps {
  document: DocumentEntity
  onPress?: () => void
  selectedToAdd?: boolean
}

export const DocumentGridItem = ({ document, selectedToAdd, onPress }: DocumentGridItemProps) => {
  const [isDownloading, setIsDownloading] = useState(false)
  const formattedSize = formatBytes(document.size)
  const downloadTask = useRef<StatefulPromise<FetchBlobResponse> | null>(null)
  const fileExtension = last(document.url.split("."))
  const userAccessToken = GlobalStore.useAppState((state) => state.auth.userAccessToken)!
  const isSelectModeActive = GlobalStore.useAppState((state) => state.selectMode.isActive)

  const downloadFile = async (fileUrl: string, dest: string) => {
    try {
      setIsDownloading(true)
      const fetchInstance = RNFetchBlob.config({ path: dest })

      downloadTask.current = fetchInstance.fetch("GET", fileUrl, {
        "X-ACCESS-TOKEN": userAccessToken,
      })
      await downloadTask.current
    } catch (error) {
      // Trying to silently remove the file
      RNFetchBlob.fs.unlink(dest).catch(() => {})

      throw error
    } finally {
      downloadTask.current = null
      setIsDownloading(false)
    }
  }

  const openFile = async () => {
    try {
      const fileExt = getUrlExtension(document.url)
      const filename = `${document.id}.${fileExt}`
      const path = `${RNFetchBlob.fs.dirs.DocumentDir}/${filename}`
      const isFileExists = await RNFetchBlob.fs.exists(path)

      if (!isFileExists) {
        await downloadFile(document.url, path)
      }

      await FileViewer.open(path)
    } catch (error) {
      // Ignore error if user canceled the file download
      if ((error as Error)?.message === "canceled") {
        return
      }

      console.error(error)
    }
  }

  const cancelDownload = () => {
    if (downloadTask.current) {
      downloadTask.current.cancel((error) => {
        if (error) {
          console.error(error)
        }
      })
    }
  }

  // Cancel the file download if the component is unmounted
  useEffect(() => {
    return () => {
      cancelDownload()
    }
  }, [])

  return (
    <Touchable disabled={isDownloading} onPress={isSelectModeActive ? onPress : openFile}>
      <Flex mb={4} pl={2} opacity={selectedToAdd ? 0.4 : 1}>
        <Flex height={200} position="relative">
          <Flex flex={1} bg="black10" />
          <Flex
            position="absolute"
            width="100%"
            height="100%"
            justifyContent="center"
            alignItems="center"
          >
            <FileTypeIcon fileType={fileExtension} />
          </Flex>
          {isDownloading && (
            <Flex
              width="100%"
              height="100%"
              position="absolute"
              justifyContent="center"
              alignItems="center"
              bg="rgba(0, 0, 0, 0.5)"
            >
              <ActivityIndicator accessibilityLabel="Loading Indicator" />
              <Button size="small" mt={2} onPress={cancelDownload}>
                Cancel
              </Button>
            </Flex>
          )}
        </Flex>
        <Text italic variant="xs" color="onBackgroundMedium" mt={1}>
          {document.title}
        </Text>
        <Text variant="xs" color="onBackgroundMedium">
          {formattedSize}
        </Text>
      </Flex>
      {selectedToAdd && (
        <Flex position="absolute" top={1} right={1} alignItems="center" justifyContent="center">
          <CheckCircleFillIcon height={30} width={30} fill="blue100" />
        </Flex>
      )}
    </Touchable>
  )
}

redpajama_set_name: RedPajamaGithub


text:
package com.wincom.mstar.dao;

import java.util.List;
import com.wincom.mstar.AlarmPO;
import com.wincom.mstar.DevicePropertyPO;

import net.sf.json.JSONArray;

public interface MonitorServiceDAO {
	public List<BaseConfig> getConfig(int parentId);
	public List<BaseConfig> getSignal(int parentDeviceId);
	public DevicePropertyPO getDeviceProperty(int deviceId);
	public List<AlarmPO> getAllAlarm();
	public List<AlarmPO> getDeviceAlarm(int deviceId);
	public List<AlarmPO> getAllAlarm(int objId);
	public List<AlarmPO> getHisAlarm(int type,String name,String startTime,String endTime);
	public JSONArray getCapacityData(String IdLst,int type,JSONArray data);
	public void getCapacityRPData(int Id,int type,JSONArray data);
}


text:
/*
* Taken from:
* http://www.w3.org/TR/html5/video.html
*/

/**
* @namespace
* The track element allows authors to specify explicit external timed
* text tracks for media elements. It does not represent anything
* on its own.

* There must not be two track element children of the same media
* element whose kind attributes are in the same state, whose
* srclang attributes are both missing or have values that represent
* the same language, and whose label attributes are again both
* missing or both have the same value.
* @extends HTMLElement
* @BB60+
* @PB10
* @example
* <video src=\"brave.webm\">
*  <track kind=subtitles src=brave.en.vtt srclang=en label=\"English\">
*  <track kind=captions src=brave.en.vtt srclang=en label=\"English for the Hard of Hearing\">
*  <track kind=subtitles src=brave.fr.vtt srclang=fr label=\"Français\">
*  <track kind=subtitles src=brave.de.vtt srclang=de label=\"Deutsch\">
* </video>
*/
HTMLTrackElement = function() { };

/**
 * @field
 * @constructedBy document.createElement("track")
 * @description Creates an HTMLTrackElement
 * @example
 * var track = document.createElement("track");
 * @PB10
 * @BB60+
 */
HTMLTrackElement.documentConstructor = undefined;

/**
* kind is one of the following strings "subtitles", "captions",
* "descriptions", "chapters", "metadata"
* @type String
* @BB60+
* @PB10
*/
HTMLTrackElement.prototype.kind = { };

/**
* The src attribute gives the address of the text track data. The
* value must be a valid non-empty URL potentially surrounded by
* spaces. This attribute must be presen
* @type String
* @BB60+
* @PB10
*/
HTMLTrackElement.prototype.src = { };

/**
* The srclang attribute gives the language of the text track data.
* The value must be a valid BCP 47 language tag. This attribute must
* be present if the element's kind attribute is in the subtitles state.
* @type String
* @BB60+
* @PB10
*/
HTMLTrackElement.prototype.srclang = { };

/**
* The label attribute gives a user-readable title for the track. This
* title is used by user agents when listing subtitle, caption,
* and audio description tracks in their user interface

*
* The value of the label attribute, if the attribute is present,
* must not be the empty string.
* @type String
* @BB60+
* @PB10
*/
HTMLTrackElement.prototype.label = { };

/**
* The default attribute, if specified, indicates that the track is
* to be enabled if the user's preferences do not indicate that
* another track would be more appropriate. There must not be more
* than one track element with the same parent node with the default
* attribute specified.
* @type Boolean
* @BB60+
* @PB10
*/
HTMLTrackElement.prototype.default = { };

/**
* Returns the TextTrack object corresponding to the text track of
* the track element.
* @type TextTrack
* @readOnly
* @BB60+
* @PB10
*/
HTMLSourceElement.prototype.track = { };


text:
package com.adjust.sdk;

public interface ILogger {
    public void setLogLevel(LogLevel logLevel);

    public void setLogLevelString(String logLevelString);

    public void verbose(String message, Object... parameters);

    public void debug(String message, Object... parameters);

    public void info(String message, Object... parameters);

    public void warn(String message, Object... parameters);

    public void error(String message, Object... parameters);

    public void Assert(String message, Object... parameters);

}


text:
module SimpleCaptcha
  class Middleware
    include SimpleCaptcha::ImageHelpers

    DEFAULT_SEND_FILE_OPTIONS = {
      :type         => 'application/octet-stream'.freeze,
      :disposition  => 'attachment'.freeze,
    }.freeze

    def initialize(app, options={})
      @app = app
      self
    end

    def call(env) # :nodoc:
      if env["REQUEST_METHOD"] == "GET" && captcha_path?(env['PATH_INFO'])
        make_image(env)
      else
        @app.call(env)
      end
    end

    protected
      def make_image(env, headers = {}, status = 404)
        request = Rack::Request.new(env)
        code = request.params["code"]
        body = []

        if !code.blank? && Utils::simple_captcha_value(code)
          #status, headers, body = @app.call(env)
          #status = 200
          #body = generate_simple_captcha_image(code)
          #headers['Content-Type'] = 'image/jpeg'

          return send_file(generate_simple_captcha_image(code), :type => 'image/jpeg', :disposition => 'inline', :filename =>  'simple_captcha.jpg')
        end

        [status, headers, body]
      end

      def captcha_path?(request_path)
        request_path.include?('/simple_captcha')
      end

      def send_file(path, options = {})
        raise MissingFile, "Cannot read file #{path}" unless File.file?(path) and File.readable?(path)

        options[:filename] ||= File.basename(path) unless options[:url_based_filename]

        status = options[:status] || 200
        headers = {"Content-Disposition" => "#{options[:disposition]}; filename='#{options[:filename]}'", "Content-Type" => options[:type], 'Content-Transfer-Encoding' => 'binary', 'Cache-Control' => 'private'}
        response_body = File.open(path, "rb")

        [status, headers, response_body]
      end
  end
end


text:
import { spawn } from "child_process";
import * as simpleGit from "simple-git";
import * as yargs from "yargs";
import { logger } from "../utils";

export const publishCommand: yargs.CommandModule = {
    command: "publish",
    describe: "Publish the package to the npm registry and the central git repository.",
    handler: (options: Options) => {
        const rootDir = process.cwd();
        const npmPublishCommand = spawn("npm", ["publish"], {
            stdio: "inherit"
        });
        npmPublishCommand.on("exit", exitCode => {
            if (exitCode === 0) {
                logger.info("Published package to the npm registry.");
                simpleGit(rootDir)
                    .push("origin")
                    .pushTags("origin", () => {
                        logger.info("Pushed the package to the git repository.");
                        process.exit(0);
                    });
            } else {
                logger.error("Could not publish package!");
                process.exit(exitCode);
            }
        });
    }
};


text:
package org.jetbrains.idea.devkit;

import com.intellij.icons.AllIcons;
import com.intellij.ide.fileTemplates.FileTemplateDescriptor;
import com.intellij.ide.fileTemplates.FileTemplateGroupDescriptor;
import com.intellij.ide.fileTemplates.FileTemplateGroupDescriptorFactory;
import com.intellij.openapi.fileTypes.StdFileTypes;

public class DevKitFileTemplatesFactory implements FileTemplateGroupDescriptorFactory {

  public FileTemplateGroupDescriptor getFileTemplatesDescriptor() {
    FileTemplateGroupDescriptor descriptor = new FileTemplateGroupDescriptor(DevKitBundle.message("plugin.descriptor"),
                                                                             AllIcons.Nodes.Plugin);
    descriptor.addTemplate(new FileTemplateDescriptor("gradleBasedPlugin.xml", StdFileTypes.XML.getIcon()) {
      @Override
      public String getDisplayName() {
        return "plugin.xml in Gradle-based projects";
      }
    });
    descriptor.addTemplate(new FileTemplateDescriptor("plugin.xml", StdFileTypes.XML.getIcon()));
    descriptor.addTemplate(new FileTemplateDescriptor("ProjectServiceClass.java", StdFileTypes.JAVA.getIcon()));
    descriptor.addTemplate(new FileTemplateDescriptor("ProjectServiceInterface.java", StdFileTypes.JAVA.getIcon()));
    descriptor.addTemplate(new FileTemplateDescriptor("ProjectServiceImplementation.java", StdFileTypes.JAVA.getIcon()));
    descriptor.addTemplate(new FileTemplateDescriptor("ApplicationServiceClass.java", StdFileTypes.JAVA.getIcon()));
    descriptor.addTemplate(new FileTemplateDescriptor("ApplicationServiceInterface.java", StdFileTypes.JAVA.getIcon()));
    descriptor.addTemplate(new FileTemplateDescriptor("ApplicationServiceImplementation.java", StdFileTypes.JAVA.getIcon()));
    descriptor.addTemplate(new FileTemplateDescriptor("ModuleServiceClass.java", StdFileTypes.JAVA.getIcon()));
    descriptor.addTemplate(new FileTemplateDescriptor("ModuleServiceInterface.java", StdFileTypes.JAVA.getIcon()));
    descriptor.addTemplate(new FileTemplateDescriptor("ModuleServiceImplementation.java", StdFileTypes.JAVA.getIcon()));
    descriptor.addTemplate(new FileTemplateDescriptor("Action.java", StdFileTypes.JAVA.getIcon()));
    descriptor.addTemplate(new FileTemplateDescriptor("InspectionDescription.html", StdFileTypes.HTML.getIcon()));
    return descriptor;
  }

}


text:
"use strict";

var Composition = require("./Composition.js"),
    Condition = require("./Condition.js");

function React() {
    this.compositions = [];
}

React.prototype = {
    compositions: null,
    when: function (target) {
        var composition = new Composition();

        this.compositions.push(composition);

        return composition.api.when(target);
    },
    once: function (target) {
        var composition = new Composition();

        this.compositions.push(composition);

        return composition.api.once(target);
    }
};

function react() {
    return new React();
}

react.Composition = Composition;
react.Condition = Condition;

/**
 * Calls the given function with react as first argument and the given config (optionally). Plugins can be used
 * to hook into class methods by overriding them.
 *
 * @param {Function} plugin
 * @param {Object=} config
 * @returns {react}
 */
react.use = function (plugin, config) {
    plugin(this, config);

    return this;
};

module.exports = react;


text:
name: BioRhyme
date_added: 2018-10-15
category: Display
styles: 5
weights: [{ weight: 200, name: 'Extra-Light' },
          { weight: 300, name: 'Light' },
          { weight: 400, name: 'Regular' },
          { weight: 700, name: 'Bold' },
          { weight: 800, name: 'Extra-Bold' }]
latest_release: { version: 'v1.600', date: '9 Mar 2016' }
project_url: https://github.com/aoifemooney/makingbiorhyme
g_fonts_url: https://fonts.google.com/specimen/BioRhyme
creator: { name: 'Aoife Mooney', url: 'http://www.aoifemooney.org' }
description: BioRhyme takes inspiration from older slab serifs, but adds a friendly, playful personality. It works best at large sizes, both for headlines and short bursts of body copy. BioRhyme and its sister face BioRhyme Expanded take advantage of OpenType enhancements including alternative glyph forms, swashes and emoticons.
family_faces: [BioRhyme Expanded]
comparison_faces: [BioRhyme Expanded]
---

Figures

font-feature-settings: '----';

1/2 3/4

'frac'

A123

Superscripts: 'sups'

27 27
'ss03'

0 0
'zero'

Ordinals

font-feature-settings: 'ordn';

1a 1a

2o 2o

Special Characters
 Explore all characters

¶
&para;

§
&sect;

†
&dagger;

‡
&Dagger;

angry
angry: 'ss05'

neutral
neutral: 'ss05'

happy
happy: 'ss05'

sad
sad: 'ss05'

surprised
surprised: 'ss05'

afraid
afraid: 'ss05'

disgusted
disgusted: 'ss05'

angry
angry: 'ss06'

neutral
neutral: 'ss06'

happy
happy: 'ss06'

sad
sad: 'ss06'

surprised
surprised: 'ss06'

afraid
afraid: 'ss06'

disgusted
disgusted: 'ss06'

Alternate Glyph Forms

font-feature-settings: 'ss--';

A A
'ss07'

a a
'ss02'

G G
'ss04'

d d
'ss08'

f f
'ss01'

g g
'ss02'

k k
'ss03'

t t
'ss01'

u u
'ss08'

x x
'ss03'

z z
'ss04'

Swashes

font-feature-settings: 'swsh';

Q Q

R R

& &


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
Ark. Bot. 8(no. 4): 21 (1909)

#### Original name
Lichen islandicus Huds.

### Remarks
null


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Manipulator.cs" company="Helix 3D Toolkit">
//   http://helixtoolkit.codeplex.com, license: MIT
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace HelixToolkit.Wpf
{
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Media3D;

    /// <summary>
    ///   Provides an abstract base class for manipulators.
    /// </summary>
    public abstract class Manipulator : UIElement3D
    {
        /// <summary>
        /// Identifies the <see cref="Color"/> dependency property.
        /// </summary>
        public static readonly DependencyProperty ColorProperty = DependencyProperty.Register(
            "Color", typeof(Color), typeof(Manipulator), new UIPropertyMetadata((s, e) => ((Manipulator)s).ColorChanged()));

        /// <summary>
        /// Identifies the <see cref="Offset"/> dependency property.
        /// </summary>
        public static readonly DependencyProperty OffsetProperty = DependencyProperty.Register(
            "Offset",
            typeof(Vector3D),
            typeof(Manipulator),
            new FrameworkPropertyMetadata(
                new Vector3D(0, 0, 0), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, (s, e) => ((Manipulator)s).PositionChanged(e)));

        /// <summary>
        /// Identifies the <see cref="Position"/> dependency property.
        /// </summary>
        public static readonly DependencyProperty PositionProperty = DependencyProperty.Register(
            "Position",
            typeof(Point3D),
            typeof(Manipulator),
            new FrameworkPropertyMetadata(
                new Point3D(), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, (s, e) => ((Manipulator)s).PositionChanged(e)));

        /// <summary>
        /// Identifies the <see cref="TargetTransform"/> dependency property.
        /// </summary>
        public static readonly DependencyProperty TargetTransformProperty =
            DependencyProperty.Register(
                "TargetTransform",
                typeof(Transform3D),
                typeof(Manipulator),
                new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));

        /// <summary>
        /// Identifies the <see cref="Value"/> dependency property.
        /// </summary>
        public static readonly DependencyProperty ValueProperty = DependencyProperty.Register(
            "Value",
            typeof(double),
            typeof(Manipulator),
            new FrameworkPropertyMetadata(0.0, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, (s, e) => ((Manipulator)s).ValueChanged(e)));

        /// <summary>
        /// Identifies the <see cref="Material"/> dependency property.
        /// </summary>
        public static readonly DependencyProperty MaterialProperty =
            DependencyProperty.Register("Material", typeof(Material), typeof(Manipulator), new PropertyMetadata(null));

        /// <summary>
        /// Identifies the <see cref="BackMaterial"/> dependency property.
        /// </summary>
        public static readonly DependencyProperty BackMaterialProperty =
            DependencyProperty.Register("BackMaterial", typeof(Material), typeof(Manipulator), new PropertyMetadata(null));

        /// <summary>
        ///   Initializes a new instance of the <see cref="Manipulator" /> class.
        /// </summary>
        protected Manipulator()
        {
            this.Model = new GeometryModel3D();
            BindingOperations.SetBinding(this.Model, GeometryModel3D.MaterialProperty, new Binding("Material") { Source = this });
            BindingOperations.SetBinding(this.Model, GeometryModel3D.BackMaterialProperty, new Binding("BackMaterial") { Source = this });
            this.Visual3DModel = this.Model;
        }

        /// <summary>
        ///   Gets or sets the color of the manipulator.
        /// </summary>
        /// <value> The color. </value>
        public Color Color
        {
            get
            {
                return (Color)this.GetValue(ColorProperty);
            }

            set
            {
                this.SetValue(ColorProperty, value);
            }
        }

        /// <summary>
        /// Gets or sets the material of the manipulator.
        /// </summary>
        public Material Material
        {
            get { return (Material)this.GetValue(MaterialProperty); }
            set { this.SetValue(MaterialProperty, value); }
        }

        /// <summary>
        /// Gets or sets the back material of the manipulator.
        /// </summary>
        public Material BackMaterial
        {
            get { return (Material)this.GetValue(BackMaterialProperty); }
            set { this.SetValue(BackMaterialProperty, value); }
        }

        /// <summary>
        ///   Gets or sets the offset of the visual (this vector is added to the Position point).
        /// </summary>
        /// <value> The offset. </value>
        public Vector3D Offset
        {
            get
            {
                return (Vector3D)this.GetValue(OffsetProperty);
            }

            set
            {
                this.SetValue(OffsetProperty, value);
            }
        }

        /// <summary>
        ///   Gets or sets the position of the manipulator.
        /// </summary>
        /// <value> The position. </value>
        public Point3D Position
        {
            get
            {
                return (Point3D)this.GetValue(PositionProperty);
            }

            set
            {
                this.SetValue(PositionProperty, value);
            }
        }

        /// <summary>
        ///   Gets or sets the target transform.
        /// </summary>
        public Transform3D TargetTransform
        {
            get
            {
                return (Transform3D)this.GetValue(TargetTransformProperty);
            }

            set
            {
                this.SetValue(TargetTransformProperty, value);
            }
        }

        /// <summary>
        ///   Gets or sets the manipulator value.
        /// </summary>
        /// <value> The value. </value>
        public double Value
        {
            get
            {
                return (double)this.GetValue(ValueProperty);
            }

            set
            {
                this.SetValue(ValueProperty, value);
            }
        }

        /// <summary>
        ///   Gets or sets the camera.
        /// </summary>
        protected ProjectionCamera Camera { get; set; }

        /// <summary>
        ///   Gets or sets the hit plane normal.
        /// </summary>
        protected Vector3D HitPlaneNormal { get; set; }

        /// <summary>
        ///   Gets or sets the model.
        /// </summary>
        protected GeometryModel3D Model { get; set; }

        /// <summary>
        ///   Gets or sets the parent viewport.
        /// </summary>
        protected Viewport3D ParentViewport { get; set; }

        /// <summary>
        /// Binds this manipulator to a given Visual3D.
        /// </summary>
        /// <param name="source">
        /// Source Visual3D which receives the manipulator transforms.
        /// </param>
        public virtual void Bind(ModelVisual3D source)
        {
            BindingOperations.SetBinding(this, TargetTransformProperty, new Binding("Transform") { Source = source });
            BindingOperations.SetBinding(this, Visual3D.TransformProperty, new Binding("Transform") { Source = source });
        }

        /// <summary>
        ///   Releases the binding of this manipulator.
        /// </summary>
        public virtual void UnBind()
        {
            BindingOperations.ClearBinding(this, TargetTransformProperty);
            BindingOperations.ClearBinding(this, Visual3D.TransformProperty);
        }

        /// <summary>
        /// Called when a property related to the geometry is changed.
        /// </summary>
        /// <param name="d">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The <see cref="System.Windows.DependencyPropertyChangedEventArgs"/> instance containing the event data.
        /// </param>
        protected static void UpdateGeometry(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ((Manipulator)d).UpdateGeometry();
        }

        /// <summary>
        /// Projects the point on the hit plane.
        /// </summary>
        /// <param name="p">
        /// The p.
        /// </param>
        /// <param name="hitPlaneOrigin">
        /// The hit Plane Origin.
        /// </param>
        /// <param name="hitPlaneNormal">
        /// The hit plane normal (world coordinate system).
        /// </param>
        /// <returns>
        /// The point in world coordinates.
        /// </returns>
        protected virtual Point3D? GetHitPlanePoint(Point p, Point3D hitPlaneOrigin, Vector3D hitPlaneNormal)
        {
            return Viewport3DHelper.UnProject(this.ParentViewport, p, hitPlaneOrigin, hitPlaneNormal);
        }

        /// <summary>
        /// Updates the geometry.
        /// </summary>
        protected abstract void UpdateGeometry();

        /// <summary>
        /// Invoked when an unhandled <see cref="E:System.Windows.Input.Mouse.MouseDown" /> attached event reaches an element in its route that is derived from this class. Implement this method to add class handling for this event.
        /// </summary>
        /// <param name="e">The <see cref="T:System.Windows.Input.MouseButtonEventArgs" /> that contains the event data. This event data reports details about the mouse button that was pressed and the handled state.</param>
        protected override void OnMouseDown(MouseButtonEventArgs e)
        {
            base.OnMouseDown(e);
            this.ParentViewport = Visual3DHelper.GetViewport3D(this);
            this.Camera = this.ParentViewport.Camera as ProjectionCamera;
            var projectionCamera = this.Camera;
            if (projectionCamera != null)
            {
                this.HitPlaneNormal = projectionCamera.LookDirection;
            }

            this.CaptureMouse();
        }

        /// <summary>
        /// Invoked when an unhandled <see cref="E:System.Windows.Input.Mouse.MouseUp" /> routed event reaches an element in its route that is derived from this class. Implement this method to add class handling for this event.
        /// </summary>
        /// <param name="e">The <see cref="T:System.Windows.Input.MouseButtonEventArgs" /> that contains the event data. The event data reports that the mouse button was released.</param>
        protected override void OnMouseUp(MouseButtonEventArgs e)
        {
            base.OnMouseUp(e);
            this.ReleaseMouseCapture();
        }

        /// <summary>
        /// Handles changes in the Position property.
        /// </summary>
        /// <param name="e">The <see cref="DependencyPropertyChangedEventArgs"/> instance containing the event data.</param>
        protected virtual void PositionChanged(DependencyPropertyChangedEventArgs e)
        {
            this.Transform = new TranslateTransform3D(
                this.Position.X + this.Offset.X, this.Position.Y + this.Offset.Y, this.Position.Z + this.Offset.Z);
        }

        /// <summary>
        /// Handles changes in the Value property.
        /// </summary>
        /// <param name="e">The <see cref="DependencyPropertyChangedEventArgs"/> instance containing the event data.</param>
        protected virtual void ValueChanged(DependencyPropertyChangedEventArgs e)
        {
        }

        /// <summary>
        /// Transforms from world to local coordinates.
        /// </summary>
        /// <param name="worldPoint">
        /// The point (world coordinates).
        /// </param>
        /// <returns>
        /// Transformed vector (local coordinates).
        /// </returns>
        protected Point3D ToLocal(Point3D worldPoint)
        {
            var mat = Visual3DHelper.GetTransform(this);
            mat.Invert();
            var t = new MatrixTransform3D(mat);
            return t.Transform(worldPoint);
        }

        /// <summary>
        /// Transforms from local to world coordinates.
        /// </summary>
        /// <param name="point">
        /// The point (local coordinates).
        /// </param>
        /// <returns>
        /// Transformed point (world coordinates).
        /// </returns>
        protected Point3D ToWorld(Point3D point)
        {
            var mat = Visual3DHelper.GetTransform(this);
            var t = new MatrixTransform3D(mat);
            return t.Transform(point);
        }

        /// <summary>
        /// Transforms from local to world coordinates.
        /// </summary>
        /// <param name="vector">
        /// The vector (local coordinates).
        /// </param>
        /// <returns>
        /// Transformed vector (world coordinates).
        /// </returns>
        protected Vector3D ToWorld(Vector3D vector)
        {
            var mat = Visual3DHelper.GetTransform(this);
            var t = new MatrixTransform3D(mat);
            return t.Transform(vector);
        }

        /// <summary>
        ///   Handles changes in the Color property (this will override the materials).
        /// </summary>
        private void ColorChanged()
        {
            this.Material = MaterialHelper.CreateMaterial(this.Color);
            this.BackMaterial = this.Material;
        }
    }
}


text:
package com.pg.alert.utils;

import com.google.common.collect.Lists;
import org.dozer.DozerBeanMapper;

import java.util.Collection;
import java.util.List;

/**
 * @Author: XieHaijun
 * @Description:
 * @Date: Created in 10:41 2017/12/20
 * @Modified By
 */
public class BeanUtil {

    /**
     * 持有Dozer单例, 避免重复创建DozerMapper消耗资源.
     */
    private static DozerBeanMapper dozer = new DozerBeanMapper();

    /**
     * 基于Dozer转换对象的类型.
     */
    public static <T> T map(Object source, Class<T> destinationClass) {
        return dozer.map(source, destinationClass);
    }

    /**
     * 基于Dozer转换Collection中对象的类型.
     */
    public static <T> List<T> mapList(Collection sourceList, Class<T> destinationClass) {
        List<T> destinationList = Lists.newArrayList();
        for (Object sourceObject : sourceList) {
            T destinationObject = dozer.map(sourceObject, destinationClass);
            destinationList.add(destinationObject);
        }
        return destinationList;
    }

    /**
     * 基于Dozer将对象A的值拷贝到对象B中.
     */
    public static void copy(Object source, Object destinationObject) {
        dozer.map(source, destinationObject);
    }
}


text:
FROM mesosphere/mesos-slave:0.27.1-2.0.226.ubuntu1404
MAINTAINER Matt Parker <matthew.parker@l-3com.com>

# Setup env
USER root

# Define commonly used JAVA_HOME variable
ENV JAVA_HOME /usr/lib/jvm/java-7-openjdk-amd64

ENV HADOOP_PREFIX /usr/local/hadoop
ENV HADOOP_COMMON_HOME /usr/local/hadoop
ENV HADOOP_HDFS_HOME /usr/local/hadoop
ENV HADOOP_CONF_DIR /usr/local/hadoop/etc/hadoop

# download wget, java & hadoop and spark
RUN  apt-get -y update && \
 apt-get install -y openjdk-7-jdk wget && \
 wget -q -O - http://apache.mirrors.pair.com/hadoop/common/hadoop-2.7.1/hadoop-2.7.1.tar.gz | tar -xzf - -C /usr/local && \
 wget -q -O - http://d3kbcqa49mib13.cloudfront.net/spark-1.6.0-bin-hadoop2.6.tgz | tar -xzf - -C /usr/local && \
 ln -s /usr/local/hadoop-2.7.1 /usr/local/hadoop && \
 ln -s /usr/local/spark-1.6.0-bin-hadoop2.6 /usr/local/spark

# Copy the Site files up
WORKDIR /usr/local/hadoop
COPY core-site.xml.template etc/hadoop/core-site.xml.template
COPY hdfs-site.xml.template etc/hadoop/hdfs-site.xml.template

# Copy the bootstrap shell
COPY bootstrap.sh /bin/bootstrap.sh

# Location to store data
VOLUME ["/tmp/mesos"]

# Entry Point for our
ENV PATH $PATH:/usr/local/hadoop/bin
ENTRYPOINT ["/bin/bootstrap.sh"]
CMD ["mesos-slave"]


text:
'use strict';

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

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

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _lodash = require('lodash');

var _lodash2 = _interopRequireDefault(_lodash);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var Link = function (_React$Component) {
  _inherits(Link, _React$Component);

  function Link() {
    _classCallCheck(this, Link);

    var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(Link).call(this));

    _this.handleClick = _this.handleClick.bind(_this);
    return _this;
  }

  _createClass(Link, [{
    key: 'handleClick',
    value: function handleClick(e) {
      if (this.props.onClick) {
        this.props.onClick(e, this.props.callbackValue);
      }
    }
  }, {
    key: 'render',
    value: function render() {

      var a;
      if (_lodash2.default.isString(this.props.onClick)) {
        a = _react2.default.createElement(
          'a',
          { style: { textDecoration: 'none' }, href: this.props.onClick, target: this.props.newTab && '_blank' },
          this.props.children
        );
      } else {
        a = _react2.default.createElement(
          'a',
          { style: { textDecoration: 'none' }, onClick: this.handleClick },
          this.props.children
        );
      }

      return a;
    }
  }]);

  return Link;
}(_react2.default.Component);

// Link.propTypes =
//   onClick: React.PropTypes.oneOfType(
//     React.PropTypes.string,
//     React.PropTypes.func
//   );

Link.defaultProps = {
  newTab: false
};

exports.default = Link;


text:
@interface ZFTimerCollectionReusableView : UICollectionReusableView
@property (weak, nonatomic) IBOutlet UILabel *timerLabel;

- (void)updateTimer:(NSArray*)array;

@end
// 版权属于原作者
// http://code4app.com (cn) http://code4app.net (en)
// 发布代码于最专业的源码分享网站: Code4App.com


text:
PDKUtil
=============================================

Stores a pdk file to a barbican container.

Installation
------------

Pip is the preferred way to install pdkutil: ::

    pip install pdkutil

Command-line interface
----------------------

PDKUtil uses Keystone for identity management. Credentials and endpoints can
be provided via environment variables or command line parameters in the same
way supported by most OpenStack command line interface (CLI) tools, e.g.: ::

    export OS_AUTH_URL=http://example.com:5000/v2.0
    export OS_USERNAME=admin
    export OS_PASSWORD=password
    export OS_TENANT_NAME=admin

Store a pdk file
----------------

This command stores the specified pdk file to a container, returning
container's reference: ::

    pdkutil store <filename> <container-name>

Get container's information
---------------------------

This command retrieves container's information (container's name,
secrets references, etc) by its specified reference: ::

    pdkutil get <container-reference>


text:
/* ----------------------------------------------------------------------------
 * This file was automatically generated by SWIG (http://www.swig.org).
 * Version 3.0.7
 *
 * Do not make changes to this file unless you know what you are doing--modify
 * the SWIG interface file instead.
 * ----------------------------------------------------------------------------- */

package org.pjsip.pjsua2;

public class AccountMediaConfig extends PersistentObject {
  private transient long swigCPtr;

  protected AccountMediaConfig(long cPtr, boolean cMemoryOwn) {
    super(pjsua2JNI.AccountMediaConfig_SWIGUpcast(cPtr), cMemoryOwn);
    swigCPtr = cPtr;
  }

  protected static long getCPtr(AccountMediaConfig obj) {
    return (obj == null) ? 0 : obj.swigCPtr;
  }

  protected void finalize() {
    delete();
  }

  public synchronized void delete() {
    if (swigCPtr != 0) {
      if (swigCMemOwn) {
        swigCMemOwn = false;
        pjsua2JNI.delete_AccountMediaConfig(swigCPtr);
      }
      swigCPtr = 0;
    }
    super.delete();
  }

  public void setTransportConfig(TransportConfig value) {
    pjsua2JNI.AccountMediaConfig_transportConfig_set(swigCPtr, this, TransportConfig.getCPtr(value), value);
  }

  public TransportConfig getTransportConfig() {
    long cPtr = pjsua2JNI.AccountMediaConfig_transportConfig_get(swigCPtr, this);
    return (cPtr == 0) ? null : new TransportConfig(cPtr, false);
  }

  public void setLockCodecEnabled(boolean value) {
    pjsua2JNI.AccountMediaConfig_lockCodecEnabled_set(swigCPtr, this, value);
  }

  public boolean getLockCodecEnabled() {
    return pjsua2JNI.AccountMediaConfig_lockCodecEnabled_get(swigCPtr, this);
  }

  public void setStreamKaEnabled(boolean value) {
    pjsua2JNI.AccountMediaConfig_streamKaEnabled_set(swigCPtr, this, value);
  }

  public boolean getStreamKaEnabled() {
    return pjsua2JNI.AccountMediaConfig_streamKaEnabled_get(swigCPtr, this);
  }

  public void setSrtpUse(pjmedia_srtp_use value) {
    pjsua2JNI.AccountMediaConfig_srtpUse_set(swigCPtr, this, value.swigValue());
  }

  public pjmedia_srtp_use getSrtpUse() {
    return pjmedia_srtp_use.swigToEnum(pjsua2JNI.AccountMediaConfig_srtpUse_get(swigCPtr, this));
  }

  public void setSrtpSecureSignaling(int value) {
    pjsua2JNI.AccountMediaConfig_srtpSecureSignaling_set(swigCPtr, this, value);
  }

  public int getSrtpSecureSignaling() {
    return pjsua2JNI.AccountMediaConfig_srtpSecureSignaling_get(swigCPtr, this);
  }

  public void setIpv6Use(pjsua_ipv6_use value) {
    pjsua2JNI.AccountMediaConfig_ipv6Use_set(swigCPtr, this, value.swigValue());
  }

  public pjsua_ipv6_use getIpv6Use() {
    return pjsua_ipv6_use.swigToEnum(pjsua2JNI.AccountMediaConfig_ipv6Use_get(swigCPtr, this));
  }

  public void readObject(ContainerNode node) throws java.lang.Exception {
    pjsua2JNI.AccountMediaConfig_readObject(swigCPtr, this, ContainerNode.getCPtr(node), node);
  }

  public void writeObject(ContainerNode node) throws java.lang.Exception {
    pjsua2JNI.AccountMediaConfig_writeObject(swigCPtr, this, ContainerNode.getCPtr(node), node);
  }

  public AccountMediaConfig() {
    this(pjsua2JNI.new_AccountMediaConfig(), true);
  }

}


text:
import { Point, Feature, FeatureCollection, MultiPolygon, Polygon, Units} from '@turf/helpers'

/**
 * http://turfjs.org/docs/#concave
 */
export default function concave(
    points: FeatureCollection<Point>,
    maxEdge: number,
    options?: {
      units?: Units
    }
): Feature<Polygon | MultiPolygon>;


text:
(function () {
    var SEARCH_BOX_ID = "search-box";
    var NO_RESULTS_MESSAGE_ID = "not-found";
    var SEARCH_RESULTS_CONTAINER_ID = "search-results";
    var QUERY_VARIABLE_URL_STRING = "query";

    function getQueryVariable(queryParam) {
        var query = window.location.search.substring(1);
        var vars = query.split("&");
        for (var i = 0; i < vars.length; i++) {
            var pair = vars[i].split("=");
            var param = pair[0];
            var value = pair[1];

            if (param === queryParam) {
                return decodeURIComponent(value.replace(/\+/g, "%20"));
            }
        }
    }

    function getSearchTerm() {
      return getQueryVariable(QUERY_VARIABLE_URL_STRING);
    }

    function setSearchBoxValue(searchBoxValue) {
      document.getElementById(SEARCH_BOX_ID).setAttribute("value", searchBoxValue);
    }

    function showNoResultsMessage() {
      document.getElementById(NO_RESULTS_MESSAGE_ID).style.display = "block";
    }

    function setSearchResultsHTML(innerHTML) {
      var searchResults = document.getElementById(SEARCH_RESULTS_CONTAINER_ID);
      searchResults.innerHTML = innerHTML;
    }

    function createPostListingHTML(postItem) {
      var headingHTML = "
" + postItem.title + "
";
      var metaHTML = "
" + postItem.date + "
";
      var descriptionHTML = "
" + postItem.content.substring(0, 150) + "...
";
      return headingHTML + metaHTML + descriptionHTML;
    }

    function displaySearchResults(results, store) {
        if (results.length) {
            var postsListingHTML = "";
            for (var i = 0; i < results.length; i++) {
                var postItem = store[results[i].ref];
                postsListingHTML += createPostListingHTML(postItem);
            }
            setSearchResultsHTML(postsListingHTML);
        } else {
          showNoResultsMessage();
        }
    }

    function addPostToSearchIndex(lunrIndex, key, postJSON) {
      lunrIndex.add({
          "id": key,
          "title": postJSON.title,
          "author": postJSON.author,
          "category": postJSON.category,
          "content": postJSON.content
      });
    }

    function search(searchTerm) {
      setSearchBoxValue(searchTerm);

      var lunrIndex = lunr(function () {
          this.field("id");
          this.field("title", {
              boost: 10
          });
          this.field("author");
          this.field("category");
          this.field("content");
      });

      for (var key in window.store) {
        addPostToSearchIndex(lunrIndex, key, window.store[key])
      }

      var results = lunrIndex.search(searchTerm);
      displaySearchResults(results, window.store);
    }

    var searchTerm = getSearchTerm();
    if (searchTerm) {
      search(searchTerm);
    }
})();


text:
Template support
================

Enable the Templates Plugin
---------------------------

The bundle offers you the ability to manage extra templates. To use this
feature, you need to enable the ``templates`` plugins shipped with the bundle.
You can define iy globally in your configuration:

.. code-block:: yaml

    # app/config/config.yml
    ivory_ck_editor:
        default_config: my_config
        configs:
            my_config:
                extraPlugins: "templates"

Or you can define it in your widget:

.. code-block:: php

    $builder->add('field', 'ckeditor', array(
        'config' => array(
            'extraPlugins' => 'templates',
        ),
    ));

Configure your templates
------------------------

.. code-block:: yaml

    # app/config/config.yml
    ivory_ck_editor:
        default_config: my_config
        configs:
            my_config:
                extraPlugins: "templates"
                templates:    "my_templates"
        templates:
            my_templates:
                imagesPath: "/bundles/mybundle/templates/images"
                templates:
                    -
                        title:       "My Template"
                        image:       "image.jpg"
                        description: "My awesome template"
                        html:        "
Crazy template :)
"

Or you can define them in your widget:

.. code-block:: php

    $builder->add('field', 'ckeditor', array(
        'config' => array(
            'extraPlugins' => 'templates',
            'templates'    => 'my_template',
        ),
        'templates' => array(
            'my_template' => array(
                'imagesPath' => '/bundles/mybundle/templates/images',
                'templates'  => array(
                    array(
                        'title'       => 'My Template',
                        'image'       => 'images.jpg',
                        'description' => 'My awesome template',
                        'html'        => '
Crazy template :)
',
                    ),
                    // ...
                ),
            ),
        ),
    ));

Use a dedicated template
------------------------

If you prefer define your html in a dedicated Twig or PHP template, you can
replace the ``html`` node by the ``template`` one and provide the path of your
template. You can optionally provide template parameters with the
``template_parameters`` node.

.. code-block:: yaml

    # app/config/config.yml
    ivory_ck_editor:
        default_config: my_config
        configs:
            my_config:
                extraPlugins: "templates"
                templates:    "my_templates"
        templates:
            my_templates:
                imagesPath: "/bundles/mybundle/templates/images"
                templates:
                    -
                        title:       "My Template"
                        image:       "image.jpg"
                        description: "My awesome template"
                        template:    "AppBundle:CKEditor:template.html.twig"
                        template_parameters:
                            foo: bar

Or you can define them in your widget:

.. code-block:: php

    $builder->add('field', 'ckeditor', array(
        'config' => array(
            'extraPlugins' => 'templates',
            'templates'    => 'my_template',
        ),
        'templates' => array(
            'my_template' => array(
                'imagesPath' => '/bundles/mybundle/templates/images',
                'templates'  => array(
                    array(
                        'title'               => 'My Template',
                        'image'               => 'images.jpg',
                        'description'         => 'My awesome template',
                        'template'            => 'AppBundle:CKEditor:template.html.twig',
                        'template_parameters' => array('foo' => 'bar'),
                    ),
                    // ...
                ),
            ),
        ),
    ));


text:
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.Assertions;
using UnityEditor;
using System;
using CNTK;
namespace UnityCNTK
{
    [CustomEditor(typeof(_Model), true)]
    public class ModelnspectorPlus : Editor
    {
        private string path;
        private List<Variable> inputList = new List<Variable>();
        private List<Variable> outputList = new List<Variable>();
        private bool isValidPath = false;
        private TextAsset _model;
        public override void OnInspectorGUI()
        {
            _Model model = (_Model)target;
            DrawDefaultInspector();

            if (model.rawModel != null)
            {
                isValidPath = false;
                if (_model != model.rawModel)
                {
                    try
                    {
                        var function = Function.Load(model.rawModel.bytes, DeviceDescriptor.CPUDevice);
                        isValidPath = true;
                        inputList = function.Arguments.ToList();
                        outputList = function.Outputs.ToList();
                        _model = model.rawModel;
                    }
                    catch
                    {
                    }

                }
                else
                {
                    isValidPath = true;
                }
            }

            if (isValidPath)
            {
                EditorGUILayout.LabelField("Inputs");
                foreach (var input in inputList)
                {
                    EditorGUILayout.LabelField(input.AsString());
                }
                EditorGUILayout.LabelField("Outputs");
                foreach (var output in outputList)
                {
                    EditorGUILayout.LabelField(output.AsString());
                }
            }
            else
            {
                EditorGUILayout.LabelField("Invalid Model");
            }

        }
    }

}


text:
var str = 'If you dream it, you can do it.';
console.log(str.startsWith('If you'));         // true
console.log(str.startsWith('you can do'));     // false
console.log(str.startsWith('you can do', 17)); // true