repo
stringclasses
1k values
file_url
stringlengths
96
373
file_path
stringlengths
11
294
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
6 values
commit_sha
stringclasses
1k values
retrieved_at
stringdate
2026-01-04 14:45:56
2026-01-04 18:30:23
truncated
bool
2 classes
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data2d/tools/Data2DTableTools.java
released/MyBox/src/main/java/mara/mybox/data2d/tools/Data2DTableTools.java
package mara.mybox.data2d.tools; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.nio.charset.Charset; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.util.ArrayList; import java.util.List; import mara.mybox.data2d.Data2D; import mara.mybox.data2d.DataClipboard; import mara.mybox.data2d.DataFileCSV; import mara.mybox.data2d.DataFileExcel; import mara.mybox.data2d.DataFileText; import mara.mybox.data2d.DataTable; import mara.mybox.data2d.TmpTable; import mara.mybox.data2d.writer.Data2DWriter; import mara.mybox.data2d.writer.DataTableWriter; import mara.mybox.db.Database; import mara.mybox.db.DerbyBase; import mara.mybox.db.data.ColumnDefinition; import mara.mybox.db.data.Data2DColumn; import mara.mybox.db.data.Data2DRow; import mara.mybox.db.table.TableData2D; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.tools.CsvTools; import mara.mybox.tools.DoubleTools; import mara.mybox.tools.TextFileTools; import static mara.mybox.value.Languages.message; import org.apache.commons.csv.CSVPrinter; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellType; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; /** * @Author Mara * @CreateDate 2023-9-12 * @License Apache License Version 2.0 */ public class Data2DTableTools { public static DataTable makeTable(FxTask task, String tname, List<Data2DColumn> sourceColumns, List<String> keys, String idName) { try { if (sourceColumns == null || sourceColumns.isEmpty()) { return null; } if (tname == null || tname.isBlank()) { tname = TmpTable.tmpTableName(); } DataTable dataTable = new DataTable(); TableData2D tableData2D = dataTable.getTableData2D(); String tableName = DerbyBase.fixedIdentifier(tname); tableData2D.setTableName(tableName); List<Data2DColumn> tableColumns = new ArrayList<>(); List<String> validNames = new ArrayList<>(); if (keys == null || keys.isEmpty()) { if (idName == null) { idName = "id"; } Data2DColumn idcolumn = new Data2DColumn(idName, ColumnDefinition.ColumnType.Long); idcolumn.setAuto(true).setIsPrimaryKey(true).setNotNull(true).setEditable(false); tableColumns.add(idcolumn); tableData2D.addColumn(idcolumn); validNames.add(idName); } for (Data2DColumn sourceColumn : sourceColumns) { Data2DColumn dataColumn = sourceColumn.copy(); dataColumn.setAuto(false).setIsPrimaryKey(false); String sourceColumnName = sourceColumn.getColumnName(); String columeName = DerbyBase.fixedIdentifier(sourceColumnName); columeName = DerbyBase.checkIdentifier(validNames, columeName, true); dataColumn.setColumnName(columeName); if (keys != null && !keys.isEmpty()) { dataColumn.setIsPrimaryKey(keys.contains(sourceColumnName)); } tableColumns.add(dataColumn); tableData2D.addColumn(dataColumn); } dataTable.setColumns(tableColumns).setTask(task).setSheet(tableName); return dataTable; } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e); } return null; } } public static DataTable createTable(FxTask task, Connection conn, String targetName, List<Data2DColumn> sourceColumns, List<String> keys, String comments, String idName, boolean dropExisted) { try { if (conn == null || sourceColumns == null || sourceColumns.isEmpty()) { return null; } if (targetName == null || targetName.isBlank()) { targetName = TmpTable.tmpTableName(); } DataTable dataTable = new DataTable(); String tableName = DerbyBase.fixedIdentifier(targetName); if (DerbyBase.exist(conn, tableName) > 0) { if (!dropExisted) { return null; } dataTable.drop(conn, tableName); conn.commit(); } dataTable = makeTable(task, tableName, sourceColumns, keys, idName); if (dataTable == null) { return null; } TableData2D tableData2D = dataTable.getTableData2D(); tableData2D.setTableName(dataTable.getSheet()); String sql = tableData2D.createTableStatement(); if (task != null) { task.setInfo(sql); } if (conn.createStatement().executeUpdate(sql) < 0) { return null; } conn.commit(); dataTable.recordTable(conn, tableName, dataTable.getColumns(), comments); return dataTable; } catch (Exception e) { if (task != null) { task.setError(e.toString()); } MyBoxLog.error(e); return null; } } public static DataTable createTable(FxTask task, Connection conn, String targetName, List<Data2DColumn> columns) { return createTable(task, conn, targetName, columns, null, null, null, true); } public static boolean write(FxTask task, DataTable dataTable, Data2DWriter writer, ResultSet results, String rowNumberName, int dscale, ColumnDefinition.InvalidAs invalidAs) { try { if (writer == null || results == null) { return false; } List<Data2DColumn> db2Columns = new ArrayList<>(); List<String> fileRow = new ArrayList<>(); List<String> names = new ArrayList<>(); List<Data2DColumn> targetColumns = new ArrayList<>(); if (rowNumberName != null) { names.add(rowNumberName); targetColumns.add(0, new Data2DColumn(rowNumberName, ColumnDefinition.ColumnType.Long)); } ResultSetMetaData meta = results.getMetaData(); for (int col = 1; col <= meta.getColumnCount(); col++) { String name = meta.getColumnName(col); names.add(name); Data2DColumn dc = null; if (dataTable != null) { dc = dataTable.columnByName(name); if (dc != null) { dc = dc.copy(); } } if (dc == null) { dc = new Data2DColumn(name, ColumnDefinition.sqlColumnType(meta.getColumnType(col)), meta.isNullable(col) == ResultSetMetaData.columnNoNulls); } db2Columns.add(dc); targetColumns.add(dc); } writer.setColumns(targetColumns).setHeaderNames(names); if (!writer.openWriter()) { return false; } long count = 0; while (results.next() && task != null && !task.isCancelled()) { count++; if (rowNumberName != null) { fileRow.add("" + count); } for (Data2DColumn column : db2Columns) { Object v = column.value(results); String s = column.toString(v); if (column.needScale()) { s = DoubleTools.scaleString(s, invalidAs, dscale); } fileRow.add(s); } writer.writeRow(fileRow); fileRow.clear(); } writer.closeWriter(); return writer.isCompleted(); } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e); } return false; } } public static DataTable importTable(FxTask task, String targetName, List<Data2DColumn> cols, List<List<String>> pageRows, ColumnDefinition.InvalidAs invalidAs) { if (cols == null || pageRows == null || pageRows.isEmpty()) { return null; } DataTable dataTable = null; try (Connection conn = DerbyBase.getConnection()) { dataTable = createTable(task, conn, targetName, cols, null, null, null, false); if (dataTable == null) { return null; } TableData2D tableData2D = dataTable.getTableData2D(); Data2DRow data2DRow = tableData2D.newRow(); List<Data2DColumn> columns = dataTable.getColumns(); conn.setAutoCommit(false); int count = 0; for (List<String> row : pageRows) { for (int i = 0; i < columns.size(); i++) { Data2DColumn column = columns.get(i); data2DRow.setValue(column.getColumnName(), column.fromString(row.get(i + 1), invalidAs)); } tableData2D.insertData(conn, data2DRow); if (++count % Database.BatchSize == 0) { conn.commit(); if (task != null) { task.setInfo(message("Imported") + ": " + count); } } } if (count > 0) { dataTable.setRowsNumber(count); dataTable.getTableData2DDefinition().updateData(conn, dataTable); conn.commit(); if (task != null) { task.setInfo(message("Imported") + ": " + count); } } } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e); } } return dataTable; } public static long importTable(FxTask task, Connection conn, Data2D sourceData, DataTable targetTable, List<Integer> cols, boolean includeRowNumber, ColumnDefinition.InvalidAs invalidAs) { try { if (sourceData == null || conn == null || targetTable == null) { return -1; } List<Data2DColumn> srcColumns = sourceData.getColumns(); if (srcColumns == null || srcColumns.isEmpty()) { sourceData.loadColumns(conn); } if (srcColumns == null || srcColumns.isEmpty()) { return -2; } if (cols == null || cols.isEmpty()) { cols = new ArrayList<>(); for (int i = 0; i < srcColumns.size(); i++) { cols.add(i); } } List<Data2DColumn> targetColumns = sourceData.targetColumns(cols, includeRowNumber); DataTableWriter writer = new DataTableWriter(); writer.setTargetTable(targetTable) .setColumns(targetColumns) .setHeaderNames(Data2DColumnTools.toNames(targetColumns)) .setWriteHeader(false); return sourceData.copy(task, writer, cols, includeRowNumber, invalidAs); } catch (Exception e) { if (task != null) { task.setError(e.toString()); } MyBoxLog.error(e); return -5; } } public static long importTable(FxTask task, Connection conn, Data2D sourceData, DataTable dataTable) { return Data2DTableTools.importTable(task, conn, sourceData, dataTable, null, false, ColumnDefinition.InvalidAs.Empty); } public static DataFileText toText(FxTask task, DataTable dataTable) { if (task == null || dataTable == null || !dataTable.hasColumns()) { return null; } File txtFile = dataTable.tmpFile(dataTable.getName(), null, "txt"); DataFileCSV csvData = toCSV(task, dataTable, txtFile, false); if (csvData != null && txtFile != null && txtFile.exists()) { DataFileText targetData = new DataFileText(); targetData.setColumns(csvData.getColumns()) .setFile(txtFile) .setDataName(csvData.getName()) .setCharset(Charset.forName("UTF-8")) .setDelimiter(",") .setHasHeader(true) .setColsNumber(csvData.getColsNumber()) .setRowsNumber(csvData.getRowsNumber()); targetData.saveAttributes(); return targetData; } else { return null; } } public static String toString(FxTask task, DataTable dataTable) { if (task == null || dataTable == null || !dataTable.hasColumns()) { return null; } File txtFile = dataTable.tmpFile(dataTable.getName(), null, "txt"); DataFileCSV csvData = toCSV(task, dataTable, txtFile, false); if (csvData != null && txtFile != null && txtFile.exists()) { return TextFileTools.readTexts(task, txtFile); } else { return null; } } public static DataFileCSV toCSV(FxTask task, DataTable dataTable, File file, boolean save) { if (task == null || dataTable == null || !dataTable.hasColumns() || file == null) { return null; } TableData2D tableData2D = dataTable.getTableData2D(); List<Data2DColumn> dataColumns = dataTable.getColumns(); int tcolsNumber = dataColumns.size(); int trowsNumber = 0; String sql = tableData2D.queryAllStatement(); if (task != null) { task.setInfo(sql); } try (Connection conn = DerbyBase.getConnection(); PreparedStatement statement = conn.prepareStatement(sql); ResultSet results = statement.executeQuery(); CSVPrinter csvPrinter = new CSVPrinter( new FileWriter(file, Charset.forName("UTF-8")), CsvTools.csvFormat(",", true))) { csvPrinter.printRecord(dataTable.columnNames()); while (results.next() && task != null && !task.isCancelled()) { try { List<String> row = new ArrayList<>(); for (int col = 0; col < tcolsNumber; col++) { Data2DColumn column = dataColumns.get(col); Object v = column.value(results); row.add(column.toString(v)); } csvPrinter.printRecord(row); trowsNumber++; } catch (Exception e) { // skip bad lines MyBoxLog.error(e); } } } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e); } return null; } if (file != null && file.exists()) { DataFileCSV targetData = new DataFileCSV(); targetData.setColumns(dataTable.getColumns()).setDataName(dataTable.getName()).setFile(file).setCharset(Charset.forName("UTF-8")).setDelimiter(",").setHasHeader(true).setColsNumber(tcolsNumber).setRowsNumber(trowsNumber); if (save) { targetData.saveAttributes(); } return targetData; } else { return null; } } public static DataFileCSV toCSV(FxTask task, DataTable dataTable) { File csvFile = dataTable.tmpFile(dataTable.getName(), null, "csv"); return toCSV(task, dataTable, csvFile, true); } public static DataFileExcel toExcel(FxTask task, DataTable dataTable) { if (task == null || dataTable == null || !dataTable.hasColumns()) { return null; } File excelFile = dataTable.tmpFile(dataTable.getName(), null, "xlsx"); String targetSheetName = message("Sheet") + "1"; TableData2D tableData2D = dataTable.getTableData2D(); List<Data2DColumn> dataColumns = dataTable.getColumns(); int tcolsNumber = dataColumns.size(); int trowsNumber = 0; String sql = tableData2D.queryAllStatement(); if (task != null) { task.setInfo(sql); } try (Connection conn = DerbyBase.getConnection(); PreparedStatement statement = conn.prepareStatement(sql); ResultSet results = statement.executeQuery(); Workbook targetBook = new XSSFWorkbook()) { Sheet targetSheet = targetBook.createSheet(targetSheetName); Row targetRow = targetSheet.createRow(0); for (int col = 0; col < tcolsNumber; col++) { Cell targetCell = targetRow.createCell(col, CellType.STRING); targetCell.setCellValue(dataColumns.get(col).getColumnName()); } while (results.next() && task != null && !task.isCancelled()) { try { targetRow = targetSheet.createRow(++trowsNumber); for (int col = 0; col < tcolsNumber; col++) { Data2DColumn column = dataColumns.get(col); Object v = column.value(results); Cell targetCell = targetRow.createCell(col, CellType.STRING); targetCell.setCellValue(column.toString(v)); } } catch (Exception e) { // skip bad lines MyBoxLog.error(e); } } try (FileOutputStream fileOut = new FileOutputStream(excelFile)) { targetBook.write(fileOut); } targetBook.close(); } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e); } return null; } if (excelFile != null && excelFile.exists()) { DataFileExcel targetData = new DataFileExcel(); targetData.setColumns(dataTable.getColumns()).setFile(excelFile) .setSheet(targetSheetName).setDataName(dataTable.getName()) .setHasHeader(true).setColsNumber(tcolsNumber).setRowsNumber(trowsNumber); targetData.saveAttributes(); return targetData; } else { return null; } } public static DataClipboard toClip(FxTask task, DataTable dataTable) { if (task == null || dataTable == null || !dataTable.hasColumns()) { return null; } File clipFile = DataClipboard.newFile(); DataFileCSV csvData = toCSV(task, dataTable, clipFile, false); if (csvData != null && clipFile != null && clipFile.exists()) { return DataClipboard.create(task, csvData, dataTable.getName(), clipFile); } else { return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data2d/reader/DataFileExcelReader.java
released/MyBox/src/main/java/mara/mybox/data2d/reader/DataFileExcelReader.java
package mara.mybox.data2d.reader; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import mara.mybox.data2d.DataFileExcel; import static mara.mybox.data2d.DataFileExcel.CommentsMarker; import mara.mybox.tools.FileTools; import mara.mybox.tools.MicrosoftDocumentTools; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.WorkbookFactory; /** * @Author Mara * @CreateDate 2022-1-27 * @License Apache License Version 2.0 */ public class DataFileExcelReader extends Data2DReader { protected DataFileExcel readerExcel; protected Iterator<Row> iterator; public DataFileExcelReader(DataFileExcel data) { this.readerExcel = data; sourceData = data; } @Override public void scanFile() { if (!FileTools.hasData(sourceFile)) { return; } try (Workbook wb = WorkbookFactory.create(sourceFile)) { Sheet sourceSheet; String sheetName = sourceData.getSheet(); if (sheetName != null) { sourceSheet = wb.getSheet(sheetName); } else { sourceSheet = wb.getSheetAt(0); sheetName = sourceSheet.getSheetName(); } if (readerExcel != null) { int sheetsNumber = wb.getNumberOfSheets(); List<String> sheetNames = new ArrayList<>(); for (int i = 0; i < sheetsNumber; i++) { sheetNames.add(wb.getSheetName(i)); } readerExcel.setSheetNames(sheetNames); readerExcel.setSheet(sheetName); } iterator = sourceSheet.iterator(); operate.handleData(); wb.close(); } catch (Exception e) { showError(e.toString()); setFailed(); } } @Override public void readColumnNames() { if (iterator == null) { return; } while (iterator.hasNext() && !isStopped()) { readRecord(); if (sourceRow == null || sourceRow.isEmpty()) { continue; } makeHeader(); return; } } @Override public void readTotal() { if (iterator == null) { return; } sourceIndex = 0; skipHeader(); while (iterator.hasNext()) { if (isStopped()) { sourceIndex = 0; return; } readRecord(); if (sourceRow != null && !sourceRow.isEmpty()) { ++sourceIndex; } } } public void skipHeader() { if (!readerHasHeader || iterator == null) { return; } while (iterator.hasNext() && !isStopped()) { readRecord(); if (sourceRow == null || sourceRow.isEmpty()) { continue; } return; } } // sourceIndex is 1-base while pageStartIndex and pageEndIndex are 0-based @Override public void readPage() { if (iterator == null) { return; } skipHeader(); sourceIndex = 0; while (iterator.hasNext() && !isStopped()) { readRecord(); if (sourceRow == null || sourceRow.isEmpty()) { continue; } if (sourceIndex++ < pageStartIndex) { continue; } if (sourceIndex > pageEndIndex) { stop(); break; } makePageRow(); } } @Override public void readRows() { if (iterator == null) { return; } skipHeader(); sourceIndex = 0; long fileIndex = -1; long startIndex = sourceData.pagination.startRowOfCurrentPage; long endIndex = sourceData.pagination.endRowOfCurrentPage; while (iterator.hasNext() && !isStopped()) { try { readRecord(); if (sourceRow == null || sourceRow.isEmpty()) { continue; } fileIndex++; if (fileIndex < startIndex || fileIndex >= endIndex) { ++sourceIndex; handleRow(); } else if (fileIndex == startIndex) { scanPage(); } } catch (Exception e) { // skip bad lines // showError(e.toString()); // setFailed(); } } } public void readRecord() { try { sourceRow = null; if (isStopped() || iterator == null) { return; } Row readerFileRow = iterator.next(); if (readerFileRow == null) { return; } sourceRow = new ArrayList<>(); String firstValue = null; for (int cellIndex = readerFileRow.getFirstCellNum(); cellIndex < readerFileRow.getLastCellNum(); cellIndex++) { String v = MicrosoftDocumentTools.cellString(readerFileRow.getCell(cellIndex)); sourceRow.add(v); if (v != null && !v.isBlank()) { firstValue = v; } } if (firstValue != null && firstValue.startsWith(CommentsMarker)) { if (dataComments == null) { dataComments = firstValue; } else { dataComments += "\n" + firstValue; } sourceRow = null; } } catch (Exception e) { showError(e.toString()); } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data2d/reader/DataTableReader.java
released/MyBox/src/main/java/mara/mybox/data2d/reader/DataTableReader.java
package mara.mybox.data2d.reader; import java.sql.PreparedStatement; import java.sql.ResultSet; import mara.mybox.data2d.DataTable; import mara.mybox.data2d.tools.Data2DRowTools; import mara.mybox.db.data.Data2DRow; import mara.mybox.db.table.TableData2D; /** * @Author Mara * @CreateDate 2022-1-29 * @License Apache License Version 2.0 */ public class DataTableReader extends Data2DReader { protected DataTable readerTable; protected TableData2D readerTableData2D; public DataTableReader(DataTable data) { readerTable = data; readerTableData2D = readerTable.getTableData2D(); readerTableData2D.setTableName(readerTable.getSheet()); sourceData = data; } @Override public void readColumnNames() { try { names = readerTable.columnNames(); } catch (Exception e) { showError(e.toString()); } } @Override public void readTotal() { try { sourceIndex = readerTableData2D.size(conn()); } catch (Exception e) { showError(e.toString()); setFailed(); } } @Override public void readPage() { sourceIndex = readerTable.pagination.startRowOfCurrentPage; String sql = readerTable.pageQuery(); // showInfo(sql); try (PreparedStatement statement = conn().prepareStatement(sql); ResultSet results = statement.executeQuery()) { while (results.next()) { makeRecord(readerTableData2D.readData(results)); sourceIndex++; makePageRow(); } } catch (Exception e) { showError(e.toString()); setFailed(); } } @Override public void readRows() { sourceIndex = 0; long tableIndex = 0; long startIndex = sourceData.pagination.startRowOfCurrentPage; long endIndex = sourceData.pagination.endRowOfCurrentPage; String sql = "SELECT * FROM " + readerTable.getSheet(); // showInfo(sql); try (PreparedStatement statement = conn().prepareStatement(sql); ResultSet results = statement.executeQuery()) { while (results.next() && !isStopped()) { try { if (tableIndex < startIndex || tableIndex >= endIndex) { makeRecord(readerTableData2D.readData(results)); ++sourceIndex; handleRow(); } else if (tableIndex == startIndex) { scanPage(); } tableIndex++; } catch (Exception e) { // skip bad lines // showError(e.toString()); // setFailed(); } } } catch (Exception e) { showError(e.toString()); setFailed(); } } public void makeRecord(Data2DRow row) { try { sourceRow = Data2DRowTools.toStrings(row, readerTable.getColumns()); } catch (Exception e) { showError(e.toString()); setFailed(); } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data2d/reader/Data2DReader.java
released/MyBox/src/main/java/mara/mybox/data2d/reader/Data2DReader.java
package mara.mybox.data2d.reader; import java.io.File; import java.sql.Connection; import java.util.ArrayList; import java.util.List; import mara.mybox.data2d.Data2D; import mara.mybox.data2d.Data2D_Edit; import mara.mybox.data2d.DataFileCSV; import mara.mybox.data2d.DataFileExcel; import mara.mybox.data2d.DataFileText; import mara.mybox.data2d.DataMatrix; import mara.mybox.data2d.DataTable; import mara.mybox.data2d.operate.Data2DOperate; import mara.mybox.db.DerbyBase; import mara.mybox.fxml.FxTask; /** * @Author Mara * @CreateDate 2022-2-25 * @License Apache License Version 2.0 */ public abstract class Data2DReader { protected Data2D sourceData; protected File sourceFile; protected Data2DOperate operate; protected long sourceIndex; // 1-based protected long pageStartIndex, pageEndIndex; // 0-based protected String dataComments; protected List<String> sourceRow, names; protected List<List<String>> rows = new ArrayList<>(); protected Connection conn; protected boolean readerHasHeader; public abstract void readColumnNames(); public abstract void readTotal(); public abstract void readPage(); public abstract void readRows(); public static Data2DReader create(Data2D_Edit data) { if (data == null) { return null; } if (data instanceof DataFileExcel) { return new DataFileExcelReader((DataFileExcel) data); } else if (data instanceof DataFileCSV) { return new DataFileCSVReader((DataFileCSV) data); } else if (data instanceof DataFileText) { return new DataFileTextReader((DataFileText) data); } else if (data instanceof DataTable) { return new DataTableReader((DataTable) data); } else if (data instanceof DataMatrix) { return new DataFileTextReader((DataFileText) data); } return null; } public boolean start(boolean scanWholeFile) { if (sourceData == null || operate == null) { return false; } sourceFile = sourceData.getFile(); readerHasHeader = sourceData.isHasHeader(); sourceIndex = 0; // 1-based pageStartIndex = sourceData.getStartRowOfCurrentPage(); pageEndIndex = pageStartIndex + sourceData.getPageSize(); dataComments = null; names = new ArrayList<>(); rows = new ArrayList<>(); sourceRow = new ArrayList<>(); sourceData.startFilter(); if (sourceData.isTmpData()) { scanPage(); } else if (scanWholeFile || !sourceData.hasPage() || sourceData.isMutiplePages() || !sourceData.isDataLoaded()) { scanFile(); } else { scanPage(); } afterScanned(); return true; } public void scanFile() { operate.handleData(); } public void scanPage() { try { for (int r = 0; r < sourceData.tableRowsNumber(); r++) { if (isStopped()) { return; } sourceRow = sourceData.dataRow(r); if (sourceRow == null || sourceRow.isEmpty()) { continue; } ++sourceIndex; handleRow(); } } catch (Exception e) { // skip bad lines showError(e.toString()); // setFailed(); } } public void handleRow() { try { operate.handleRow(sourceRow, sourceIndex); } catch (Exception e) { showError(e.toString()); } } public void makeHeader() { try { if (sourceRow == null || sourceRow.isEmpty()) { readerHasHeader = false; } names = new ArrayList<>(); if (readerHasHeader) { for (int i = 0; i < sourceRow.size(); i++) { String name = sourceRow.get(i); if (name == null || name.isBlank()) { names.add(sourceData.colPrefix() + i); } else if (names.contains(name)) { int index = 2; while (names.contains(name + index)) { index++; } names.add(name + index); } else { names.add(name); } } } else { if (sourceRow != null) { for (int i = 1; i <= sourceRow.size(); i++) { names.add(sourceData.colPrefix() + i); } } } sourceData.setHasHeader(readerHasHeader); if (!sourceData.hasComments()) { sourceData.setComments(dataComments); } stop(); } catch (Exception e) { showError(e.toString()); } } public void makePageRow() { List<String> row = new ArrayList<>(); for (int i = 0; i < Math.min(sourceRow.size(), sourceData.columnsNumber()); i++) { row.add(sourceRow.get(i)); } for (int col = row.size(); col < sourceData.columnsNumber(); col++) { row.add(sourceData.defaultColValue()); } row.add(0, "" + sourceIndex); rows.add(row); } public void afterScanned() { try { sourceData.stopFilter(); if (operate == null && conn != null) { conn.commit(); conn.close(); conn = null; } } catch (Exception e) { showError(e.toString()); } } /* status */ public FxTask task() { if (operate != null) { return operate.getTask(); } else { return null; } } public Connection conn() { if (operate != null) { return operate.conn(); } else { return DerbyBase.getConnection(); } } public void showInfo(String info) { if (operate != null) { operate.showInfo(info); } } public void showError(String error) { if (operate != null) { operate.showError(error); } } public void stop() { if (operate != null) { operate.stop(); } } public void setFailed() { if (operate != null) { operate.setFailed(); } } public boolean isStopped() { return operate == null || operate.isStopped(); } /* get/set */ public Data2D getSourceData() { return sourceData; } public Data2DOperate getOperate() { return operate; } public void setOperate(Data2DOperate operate) { this.operate = operate; } public List<String> getNames() { return names; } public List<List<String>> getRows() { return rows; } public long getSourceIndex() { return sourceIndex; } public void setSourceIndex(long sourceIndex) { this.sourceIndex = sourceIndex; } public Data2DReader setReaderData(Data2D readerData) { this.sourceData = readerData; return this; } public Data2DReader setReaderHasHeader(boolean readerHasHeader) { this.readerHasHeader = readerHasHeader; return this; } public Data2DReader setNames(List<String> names) { this.names = names; return this; } public String getDataComments() { return dataComments; } public Data2DReader setDataComments(String dataComments) { this.dataComments = dataComments; return this; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data2d/reader/DataFileTextReader.java
released/MyBox/src/main/java/mara/mybox/data2d/reader/DataFileTextReader.java
package mara.mybox.data2d.reader; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.util.List; import mara.mybox.data2d.DataFileText; import mara.mybox.tools.FileTools; /** * @Author Mara * @CreateDate 2022-1-29 * @License Apache License Version 2.0 */ public class DataFileTextReader extends Data2DReader { protected DataFileText readerText; protected BufferedReader textReader; public DataFileTextReader() { } public DataFileTextReader(DataFileText data) { readerText = data; sourceData = data; } @Override public void scanFile() { File validFile = FileTools.removeBOM(task(), sourceFile); if (validFile == null || isStopped()) { return; } readerText.checkForLoad(); try (BufferedReader reader = new BufferedReader(new FileReader(validFile, readerText.getCharset()))) { textReader = reader; operate.handleData(); textReader = null; reader.close(); } catch (Exception e) { showError(e.toString()); setFailed(); } } protected List<String> readValidLine() { return readerText.readValidLine(textReader); } protected List<String> parseFileLine(String line) { return readerText.parseFileLine(line); } @Override public void readColumnNames() { try { String line, comments; while ((line = textReader.readLine()) != null && !isStopped()) { if (line == null || line.isBlank()) { continue; } if (line.startsWith(DataFileText.CommentsMarker)) { comments = line.substring(DataFileText.CommentsMarker.length(), line.length()); if (dataComments == null) { dataComments = comments; } else { dataComments += "\n" + comments; } continue; } sourceRow = parseFileLine(line); if (sourceRow == null || sourceRow.isEmpty()) { continue; } makeHeader(); return; } } catch (Exception e) { showError(e.toString()); } } @Override public void readTotal() { try { String line; sourceIndex = 0; skipHeader(); while ((line = textReader.readLine()) != null) { if (isStopped()) { sourceIndex = 0; return; } List<String> row = parseFileLine(line); if (row != null && !row.isEmpty()) { ++sourceIndex; } } } catch (Exception e) { showError(e.toString()); setFailed(); } } public void skipHeader() { try { if (!readerHasHeader || textReader == null) { return; } String line; while ((line = textReader.readLine()) != null && !isStopped()) { sourceRow = parseFileLine(line); if (sourceRow == null || sourceRow.isEmpty()) { continue; } return; } } catch (Exception e) { showError(e.toString()); setFailed(); } } // sourceIndex is 1-base while pageStartIndex and pageEndIndex are 0-based @Override public void readPage() { if (textReader == null) { return; } try { skipHeader(); sourceIndex = 0; String line; while ((line = textReader.readLine()) != null && !isStopped()) { sourceRow = parseFileLine(line); if (sourceRow == null || sourceRow.isEmpty()) { continue; } if (sourceIndex++ < pageStartIndex) { continue; } if (sourceIndex > pageEndIndex) { stop(); break; } makePageRow(); } } catch (Exception e) { showError(e.toString()); setFailed(); } } @Override public void readRows() { try { if (textReader == null) { return; } skipHeader(); sourceIndex = 0; long fileIndex = -1; long startIndex = sourceData.pagination.startRowOfCurrentPage; long endIndex = sourceData.pagination.endRowOfCurrentPage; String line; while ((line = textReader.readLine()) != null && !isStopped()) { sourceRow = parseFileLine(line); if (sourceRow == null || sourceRow.isEmpty()) { continue; } fileIndex++; if (fileIndex < startIndex || fileIndex >= endIndex) { ++sourceIndex; handleRow(); } else if (fileIndex == startIndex) { scanPage(); } } } catch (Exception e) { showError(e.toString()); setFailed(); } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data2d/reader/DataFileCSVReader.java
released/MyBox/src/main/java/mara/mybox/data2d/reader/DataFileCSVReader.java
package mara.mybox.data2d.reader; import java.io.File; import java.util.ArrayList; import java.util.Iterator; import mara.mybox.data2d.DataFileCSV; import mara.mybox.tools.FileTools; import org.apache.commons.csv.CSVParser; import org.apache.commons.csv.CSVRecord; /** * @Author Mara * @CreateDate 2022-1-29 * @License Apache License Version 2.0 */ public class DataFileCSVReader extends Data2DReader { protected DataFileCSV readerCSV; protected Iterator<CSVRecord> iterator; protected CSVParser csvParser; public DataFileCSVReader(DataFileCSV data) { readerCSV = data; sourceData = data; } @Override public void scanFile() { File validFile = FileTools.removeBOM(task(), sourceFile); if (validFile == null || isStopped()) { return; } readerCSV.checkForLoad(); try (CSVParser parser = CSVParser.parse(validFile, readerCSV.getCharset(), readerCSV.cvsFormat())) { csvParser = parser; iterator = parser.iterator(); operate.handleData(); csvParser = null; parser.close(); } catch (Exception e) { showError(e.toString()); setFailed(); } } @Override public void readColumnNames() { try { if (csvParser == null) { return; } sourceRow = null; dataComments = csvParser.getHeaderComment(); if (readerHasHeader) { try { sourceRow = new ArrayList<>(); sourceRow.addAll(csvParser.getHeaderNames()); } catch (Exception e) { showError(e.toString()); } } else { while (iterator.hasNext() && !isStopped()) { readFileRecord(); if (sourceRow != null && !sourceRow.isEmpty()) { break; } } } makeHeader(); } catch (Exception e) { showError(e.toString()); } } @Override public void readTotal() { try { sourceIndex = 0; if (iterator == null) { return; } while (iterator.hasNext()) { if (isStopped()) { sourceIndex = 0; return; } readFileRecord(); if (sourceRow != null && !sourceRow.isEmpty()) { ++sourceIndex; } } } catch (Exception e) { showError(e.toString()); setFailed(); } } // sourceIndex is 1-base while pageStartIndex and pageEndIndex are 0-based @Override public void readPage() { try { if (iterator == null) { return; } sourceIndex = 0; while (iterator.hasNext() && !isStopped()) { readFileRecord(); if (sourceRow == null || sourceRow.isEmpty()) { continue; } if (sourceIndex++ < pageStartIndex) { continue; } if (sourceIndex > pageEndIndex) { stop(); break; } makePageRow(); } } catch (Exception e) { showError(e.toString()); setFailed(); } } public void readFileRecord() { try { sourceRow = null; if (isStopped() || iterator == null) { return; } CSVRecord csvRecord = iterator.next(); if (csvRecord == null) { return; } sourceRow = new ArrayList<>(); for (String v : csvRecord) { sourceRow.add(v); } } catch (Exception e) { showError(e.toString()); } } @Override public void readRows() { try { if (iterator == null) { return; } sourceIndex = 0; long fileIndex = -1; long startIndex = sourceData.pagination.startRowOfCurrentPage; long endIndex = sourceData.pagination.endRowOfCurrentPage; while (iterator.hasNext() && !isStopped()) { try { readFileRecord(); if (sourceRow == null || sourceRow.isEmpty()) { continue; } fileIndex++; if (fileIndex < startIndex || fileIndex >= endIndex) { ++sourceIndex; handleRow(); } else if (fileIndex == startIndex) { scanPage(); } } catch (Exception e) { // skip bad lines // showError(e.toString()); // setFailed(); } } } catch (Exception e) { showError(e.toString()); setFailed(); } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DReadPage.java
released/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DReadPage.java
package mara.mybox.data2d.operate; import java.sql.Connection; import java.util.List; import mara.mybox.data2d.Data2D_Edit; /** * @Author Mara * @CreateDate 2022-2-25 * @License Apache License Version 2.0 */ public class Data2DReadPage extends Data2DOperate { public static Data2DReadPage create(Data2D_Edit data) { Data2DReadPage op = new Data2DReadPage(); return op.setSourceData(data) ? op : null; } @Override public boolean go() { return reader.start(true); } @Override public void handleData() { reader.readPage(); } public List<List<String>> getRows() { return reader.getRows(); } /* set */ public Data2DReadPage setConn(Connection conn) { this.conn = conn; closeConn = false; return this; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DReadDefinition.java
released/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DReadDefinition.java
package mara.mybox.data2d.operate; import mara.mybox.data2d.Data2D_Edit; /** * @Author Mara * @CreateDate 2022-2-25 * @License Apache License Version 2.0 */ public class Data2DReadDefinition extends Data2DOperate { public static Data2DReadDefinition create(Data2D_Edit data) { Data2DReadDefinition op = new Data2DReadDefinition(); return op.setSourceData(data) ? op : null; } @Override public void handleData() { } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DGroup.java
released/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DGroup.java
package mara.mybox.data2d.operate; import java.io.File; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import mara.mybox.data2d.Data2D_Edit; import mara.mybox.data2d.DataFileCSV; import mara.mybox.db.data.ColumnDefinition; import mara.mybox.db.data.Data2DColumn; import mara.mybox.dev.MyBoxLog; import mara.mybox.tools.CsvTools; import mara.mybox.tools.FileTmpTools; import mara.mybox.tools.FileTools; import static mara.mybox.value.Languages.message; import org.apache.commons.csv.CSVPrinter; /** * @Author Mara * @CreateDate 2022-2-25 * @License Apache License Version 2.0 */ public class Data2DGroup extends Data2DOperate { protected long splitSize, startIndex, currentSize; protected String prefix; protected List<Data2DColumn> targetColumns; protected List<String> names; protected File currentFile; protected List<DataFileCSV> files; protected CSVPrinter csvPrinter; public static Data2DGroup create(Data2D_Edit data) { Data2DGroup op = new Data2DGroup(); return op.setSourceData(data) ? op : null; } @Override public boolean checkParameters() { try { if (!super.checkParameters() || cols == null || cols.isEmpty() || splitSize <= 0) { return false; } startIndex = 1; currentSize = 0; prefix = sourceData.getName(); names = new ArrayList<>(); targetColumns = new ArrayList<>(); for (int c : cols) { Data2DColumn column = sourceData.column(c); names.add(column.getColumnName()); targetColumns.add(column.copy()); } if (includeRowNumber) { targetColumns.add(0, new Data2DColumn(message("SourceRowNumber"), ColumnDefinition.ColumnType.Long)); } files = new ArrayList<>(); return true; } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e); } return false; } } @Override public boolean handleRow() { try { targetRow = null; if (sourceRow == null) { return false; } targetRow = new ArrayList<>(); for (int col : cols) { if (col >= 0 && col < sourceRow.size()) { targetRow.add(sourceRow.get(col)); } else { targetRow.add(null); } } if (targetRow.isEmpty()) { return false; } if (currentFile == null) { currentFile = FileTmpTools.getTempFile(".csv"); csvPrinter = CsvTools.csvPrinter(currentFile); csvPrinter.printRecord(names); startIndex = sourceRowIndex; } if (includeRowNumber) { targetRow.add(0, sourceRowIndex + ""); } csvPrinter.printRecord(targetRow); currentSize++; if (currentSize % splitSize == 0) { closeFile(); } return true; } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e); } return false; } } public void closeFile() { try { if (csvPrinter == null) { return; } csvPrinter.flush(); csvPrinter.close(); csvPrinter = null; File file = sourceData.tmpFile(prefix + "_" + startIndex + "-" + sourceRowIndex, null, "csv"); if (FileTools.override(currentFile, file) && file.exists()) { DataFileCSV dataFileCSV = new DataFileCSV(); dataFileCSV.setTask(task); dataFileCSV.setColumns(targetColumns) .setFile(file) .setCharset(Charset.forName("UTF-8")) .setDelimiter(",") .setHasHeader(true) .setColsNumber(targetColumns.size()) .setRowsNumber(currentSize); dataFileCSV.saveAttributes(); dataFileCSV.stopTask(); files.add(dataFileCSV); } currentFile = null; currentSize = 0; } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e); } } } @Override public boolean end() { closeFile(); return super.end(); } /* set */ public Data2DGroup setSplitSize(int splitSize) { this.splitSize = splitSize; return this; } /* get */ public List<DataFileCSV> getFiles() { return files; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DReadColumnNames.java
released/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DReadColumnNames.java
package mara.mybox.data2d.operate; import java.util.List; import mara.mybox.data2d.Data2D_Edit; /** * @Author Mara * @CreateDate 2022-2-25 * @License Apache License Version 2.0 */ public class Data2DReadColumnNames extends Data2DOperate { public static Data2DReadColumnNames create(Data2D_Edit data) { Data2DReadColumnNames op = new Data2DReadColumnNames(); return op.setSourceData(data) ? op : null; } @Override public boolean checkParameters() { if (!super.checkParameters()) { return false; } sourceData.checkForLoad(); return true; } @Override public boolean go() { return reader.start(true); } @Override public void handleData() { reader.readColumnNames(); } public List<String> getNames() { return reader.getNames(); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DVerify.java
released/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DVerify.java
package mara.mybox.data2d.operate; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import mara.mybox.data2d.Data2D; import mara.mybox.data2d.Data2D_Edit; import mara.mybox.data2d.tools.Data2DColumnTools; import mara.mybox.data2d.writer.DataFileCSVWriter; import mara.mybox.db.data.ColumnDefinition; import mara.mybox.db.data.Data2DColumn; import mara.mybox.dev.MyBoxLog; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2022-2-25 * @License Apache License Version 2.0 */ public class Data2DVerify extends Data2DOperate { private DataFileCSVWriter writer; public static Data2DVerify create(Data2D_Edit data) { Data2DVerify op = new Data2DVerify(); return op.setSourceData(data) ? op : null; } @Override public boolean checkParameters() { File csvFile = sourceData.tmpFile(sourceData.getName(), "Verify", "csv"); writer = new DataFileCSVWriter(); writer.setPrintFile(csvFile); List<Data2DColumn> columns = columns(); writer.setColumns(columns) .setHeaderNames(Data2DColumnTools.toNames(columns)) .setWriteHeader(true); addWriter(writer); return super.checkParameters(); } @Override public void handleRow(List<String> row, long index) { sourceRow = row; sourceRowIndex = index; if (sourceRow == null) { return; } List<List<String>> invalids = verify(sourceData, sourceRowIndex, sourceRow); if (invalids != null) { for (List<String> invalid : invalids) { writer.writeRow(invalid); } } } @Override public boolean end() { try { if (writer == null || writer.getTargetRowIndex() <= 0) { writer.recordTargetData = false; } return super.end(); } catch (Exception e) { showError(e.toString()); return false; } } @Override public boolean openResults() { if (writer == null) { return false; } if (writer.getTargetRowIndex() <= 0) { controller.popInformation(message("RowsNumber") + ": " + sourceRowIndex + "\n" + message("AllValuesValid"), 5000); return true; } return super.openResults(); } /* static */ public static List<Data2DColumn> columns() { List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(message("Row"), ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(message("Column"), ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(message("Invalid"), ColumnDefinition.ColumnType.String)); return columns; } public static List<String> columnNames() { return Data2DColumnTools.toNames(columns()); } public static List<List<String>> verify(Data2D data, long rowIndex, List<String> row) { try { List< List<String>> invalids = new ArrayList<>(); int rowSize = row.size(); for (int c = 0; c < data.columnsNumber(); c++) { Data2DColumn column = data.column(c); if (column.isAuto()) { continue; } String value = c < rowSize ? row.get(c) : null; String item = null; if (column.isNotNull() && (value == null || value.isBlank())) { item = message("Null"); } else if (!column.validValue(value)) { item = message(column.getType().name()); } else if (!data.validValue(value)) { item = message("TextDataComments"); } if (item == null) { continue; } List<String> invalid = new ArrayList<>(); invalid.addAll(Arrays.asList((rowIndex + 1) + "", column.getColumnName(), item)); invalids.add(invalid); } return invalids; } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DOperate.java
released/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DOperate.java
package mara.mybox.data2d.operate; import java.io.File; import java.sql.Connection; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask; import javafx.application.Platform; import mara.mybox.controller.BaseController; import mara.mybox.controller.BaseLogsController; import mara.mybox.data2d.Data2D; import mara.mybox.data2d.Data2D_Edit; import mara.mybox.data2d.reader.Data2DReader; import mara.mybox.data2d.writer.Data2DWriter; import mara.mybox.db.DerbyBase; import mara.mybox.db.data.ColumnDefinition.InvalidAs; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2022-2-25 * @License Apache License Version 2.0 */ public abstract class Data2DOperate { protected BaseController controller; protected Data2DReader reader; protected List<Data2DWriter> writers; protected Data2D sourceData; protected File sourceFile, targetPath, targetFile; protected List<String> sourceRow, targetRow; protected FxTask task; protected List<Integer> cols, otherCols; protected int colsLen, scale = -1; protected boolean includeRowNumber, writeHeader, rowPassFilter, reachMaxFiltered; protected boolean stopped, needCheckTask, failed, closeConn; protected long sourceRowIndex; // 1-based protected long handledCount; protected InvalidAs invalidAs; protected Connection conn; protected List<File> printedFiles; public Data2DOperate() { closeConn = true; } public String info() { String s = getClass().toString() + "\n"; if (controller != null) { s += "controller: " + controller.getClass() + "\n"; } if (reader != null) { s += "reader: " + reader.getClass() + "\n"; } if (sourceData != null) { s += sourceData.info(); } return s; } /* reader */ public boolean setSourceData(Data2D_Edit data) { reader = Data2DReader.create(data); if (reader == null) { return false; } sourceData = reader.getSourceData(); sourceFile = sourceData.getFile(); task = sourceData.getTask(); reader.setOperate(this); return true; } /* writers */ public Data2DOperate addWriter(Data2DWriter writer) { if (writer == null) { return this; } if (writers == null) { writers = new ArrayList<>(); } writers.add(writer.setOperate(this)); return this; } public boolean openWriters() { if (writers == null) { return true; } for (Data2DWriter writer : writers) { assignPrintFile(writer); if (!writer.openWriter()) { failStop(null); end(); return false; } } return true; } public void assignPrintFile(Data2DWriter writer) { if (writer != null && targetFile != null) { writer.setPrintFile(targetFile); } } public Data2DOperate addPrintedFile(File file) { if (file == null || !file.exists()) { return this; } if (printedFiles == null) { printedFiles = new ArrayList<>(); } printedFiles.add(file); return this; } public boolean closeWriters() { if (writers == null) { return true; } for (Data2DWriter writer : writers) { writer.closeWriter(); } return true; } /* run */ public Data2DOperate start() { if (!checkParameters() || !go()) { failStop(null); } end(); return this; } public boolean checkParameters() { handledCount = 0; sourceRowIndex = 0; sourceRow = null; targetRow = null; stopped = false; failed = false; rowPassFilter = false; reachMaxFiltered = false; if (sourceData == null) { return false; } if (scale < 0) { scale = sourceData.getScale(); } if (task != null) { controller = task.getController(); } if (task == null) { controller = sourceData.getController(); } return openWriters(); } public boolean go() { return reader.start(false); } public void handleData() { reader.readRows(); } public void handleRow(List<String> row, long index) { sourceRow = row; sourceRowIndex = index; targetRow = null; rowPassFilter = sourceData.filterDataRow(sourceRow, sourceRowIndex); reachMaxFiltered = sourceData.filterReachMaxPassed(); if (reachMaxFiltered) { stopped = true; } else if (rowPassFilter) { if (handleRow()) { writeRow(); handledCount++; } } } public boolean handleRow() { return false; } public void writeRow() { if (writers == null || targetRow == null) { return; } for (Data2DWriter writer : writers) { writer.writeRow(targetRow); } } public boolean end() { try { closeWriters(); if (conn != null) { conn.commit(); if (closeConn) { conn.close(); } conn = null; } return true; } catch (Exception e) { showError(e.toString()); return false; } } public boolean openResults() { if (writers == null || writers.isEmpty()) { return false; } new Timer().schedule(new TimerTask() { @Override public void run() { Platform.runLater(() -> { for (Data2DWriter writer : writers) { if (writer.showResult()) { showInfo(writer.getFileSuffix() + " written."); } else { showInfo(writer.getFileSuffix() + " no data."); } } }); Platform.requestNextPulse(); } }, 200); return true; } /* status */ public Connection conn() { try { if (conn == null || conn.isClosed()) { conn = DerbyBase.getConnection(); } return conn; } catch (Exception e) { showError(e.toString()); setFailed(); return null; } } public FxTask getTask() { if (task == null && controller != null) { task = controller.getTask(); } return task; } public void showInfo(String info) { if (info == null || info.isBlank()) { return; } // MyBoxLog.console(info); if (controller != null) { if (controller instanceof BaseLogsController) { ((BaseLogsController) controller).updateLogs(info); } else if (task != null) { task.setInfo(info); } else { controller.popInformation(info); } } else if (task != null) { task.setInfo(info); } } public void showError(String error) { if (error == null || error.isBlank()) { return; } // MyBoxLog.console(error); if (controller != null) { if (controller instanceof BaseLogsController) { ((BaseLogsController) controller).showLogs(error); } else if (task != null) { task.setError(error); } else { controller.displayError(error); } } else if (task != null) { task.setError(error); } else { MyBoxLog.error(error); } } public void stop() { stopped = true; // showInfo(message("Stopped")); } public boolean isStopped() { return stopped; } public void setFailed() { failed = true; showInfo(message("Failed")); } public void failStop(String error) { fail(error); stop(); } public void fail(String error) { setFailed(); showError(error); } public boolean isFailed() { return failed; } /* set */ public Data2DOperate setTask(FxTask task) { this.task = task; return this; } public Data2DOperate setCols(List<Integer> cols) { this.cols = cols; if (cols == null) { colsLen = 0; } else { colsLen = cols.size(); } return this; } public Data2DOperate setOtherCols(List<Integer> otherCols) { this.otherCols = otherCols; return this; } public Data2DOperate setReader(Data2DReader reader) { this.reader = reader; return this; } public Data2DOperate setData2D(Data2D data2D) { this.sourceData = data2D; return this; } public boolean isWriteHeader() { return writeHeader; } public Data2DOperate setWriteHeader(boolean writeHeader) { this.writeHeader = writeHeader; return this; } public Data2DOperate setIncludeRowNumber(boolean includeRowNumber) { this.includeRowNumber = includeRowNumber; return this; } public Data2DOperate setSourceRow(List<String> sourceRow) { this.sourceRow = sourceRow; return this; } public Data2DOperate setRowIndex(long rowIndex) { this.sourceRowIndex = rowIndex; return this; } public Data2DOperate setScale(int scale) { this.scale = scale; return this; } public Data2DOperate setInvalidAs(InvalidAs invalidAs) { this.invalidAs = invalidAs; return this; } public List<Data2DWriter> getWriters() { return writers; } public Data2DOperate setWriters(List<Data2DWriter> writers) { this.writers = writers; return this; } public Data2DOperate setController(BaseController controller) { this.controller = controller; return this; } /* get */ public Data2DReader getReader() { return reader; } public Data2D getSourceData() { return sourceData; } public File getSourceFile() { return sourceFile; } public int getScale() { return scale; } public BaseController getController() { return controller; } public long getSourceRowIndex() { return reader.getSourceIndex(); } public long getHandledCount() { return handledCount; } public InvalidAs getInvalidAs() { return invalidAs; } public List<File> getPrintedFiles() { return printedFiles; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DSimpleLinearRegression.java
released/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DSimpleLinearRegression.java
package mara.mybox.data2d.operate; import mara.mybox.calculation.SimpleLinearRegression; import mara.mybox.data2d.Data2D_Edit; import mara.mybox.dev.MyBoxLog; import mara.mybox.tools.DoubleTools; /** * @Author Mara * @CreateDate 2022-2-25 * @License Apache License Version 2.0 */ public class Data2DSimpleLinearRegression extends Data2DOperate { protected SimpleLinearRegression simpleRegression; protected double x, y; public static Data2DSimpleLinearRegression create(Data2D_Edit data) { Data2DSimpleLinearRegression op = new Data2DSimpleLinearRegression(); return op.setSourceData(data) ? op : null; } @Override public boolean checkParameters() { return super.checkParameters() && cols != null && !cols.isEmpty() && simpleRegression != null; } @Override public boolean handleRow() { try { targetRow = null; if (sourceRow == null) { return false; } x = DoubleTools.toDouble(sourceRow.get(cols.get(0)), invalidAs); y = DoubleTools.toDouble(sourceRow.get(cols.get(1)), invalidAs); targetRow = simpleRegression.addData(sourceRowIndex, x, y); return true; } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e); } return false; } } /* set */ public Data2DSimpleLinearRegression setSimpleRegression(SimpleLinearRegression simpleRegression) { this.simpleRegression = simpleRegression; return this; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DReadColumns.java
released/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DReadColumns.java
package mara.mybox.data2d.operate; import java.util.ArrayList; import java.util.List; import mara.mybox.data2d.Data2D_Edit; /** * @Author Mara * @CreateDate 2022-2-25 * @License Apache License Version 2.0 */ public class Data2DReadColumns extends Data2DOperate { protected List<List<String>> rows; public static Data2DReadColumns create(Data2D_Edit data) { Data2DReadColumns op = new Data2DReadColumns(); return op.setSourceData(data) ? op : null; } @Override public boolean checkParameters() { if (!super.checkParameters() || cols == null || cols.isEmpty()) { return false; } rows = new ArrayList<>(); return true; } @Override public boolean handleRow() { try { if (sourceRow == null) { return false; } List<String> row = new ArrayList<>(); for (int col : cols) { if (col >= 0 && col < sourceRow.size()) { row.add(sourceRow.get(col)); } else { row.add(null); } } if (row.isEmpty()) { return false; } if (includeRowNumber) { row.add(0, sourceRowIndex + ""); } rows.add(row); return true; } catch (Exception e) { showError(e.toString()); return false; } } /* get */ public List<List<String>> getRows() { return rows; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DCopy.java
released/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DCopy.java
package mara.mybox.data2d.operate; import java.util.ArrayList; import mara.mybox.data2d.Data2D_Edit; /** * @Author Mara * @CreateDate 2022-2-25 * @License Apache License Version 2.0 */ public class Data2DCopy extends Data2DOperate { private String value; private int rowSize; public static Data2DCopy create(Data2D_Edit data) { Data2DCopy op = new Data2DCopy(); return op.setSourceData(data) ? op : null; } @Override public boolean checkParameters() { return super.checkParameters() && cols != null && !cols.isEmpty(); } @Override public boolean handleRow() { try { targetRow = null; if (sourceRow == null) { return false; } targetRow = new ArrayList<>(); rowSize = sourceRow.size(); for (int col : cols) { if (col >= 0 && col < rowSize) { value = sourceRow.get(col); } else { value = null; } targetRow.add(value); } if (targetRow.isEmpty()) { return false; } if (includeRowNumber) { targetRow.add(0, sourceRowIndex + ""); } return true; } catch (Exception e) { showError(e.toString()); return false; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DNormalize.java
released/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DNormalize.java
package mara.mybox.data2d.operate; import java.util.ArrayList; import mara.mybox.calculation.DoubleStatistic; import mara.mybox.calculation.Normalization; import mara.mybox.data2d.Data2D_Edit; import mara.mybox.tools.DoubleTools; import mara.mybox.value.AppValues; /** * @Author Mara * @CreateDate 2022-2-25 * @License Apache License Version 2.0 */ public class Data2DNormalize extends Data2DOperate { protected Type type; protected DoubleStatistic[] statisticData; protected DoubleStatistic statisticAll; protected double[] colValues; protected double from, to, tValue; protected Normalization.Algorithm a; public static enum Type { MinMaxColumns, SumColumns, ZscoreColumns, Rows, MinMaxAll, SumAll, ZscoreAll } public static Data2DNormalize create(Data2D_Edit data) { Data2DNormalize op = new Data2DNormalize(); return op.setSourceData(data) ? op : null; } @Override public boolean checkParameters() { if (!super.checkParameters() || cols == null || cols.isEmpty() || type == null || invalidAs == null) { return false; } switch (type) { case MinMaxColumns: case ZscoreColumns: if (statisticData == null) { return false; } if (cols == null || cols.isEmpty() || type == null || invalidAs == null) { return false; } break; case SumColumns: if (colValues == null) { return false; } break; case Rows: if (a == null) { return false; } break; case MinMaxAll: case ZscoreAll: if (statisticAll == null) { return false; } break; } return true; } @Override public boolean handleRow() { switch (type) { case MinMaxColumns: return handleNormalizeMinMaxColumns(); case SumColumns: return handleNormalizeSumColumns(); case ZscoreColumns: return handleNormalizeZscoreColumns(); case Rows: return handleNormalizeRows(a); case MinMaxAll: return handleNormalizeMinMaxAll(); case SumAll: return handleNormalizeSumAll(); case ZscoreAll: return handleNormalizeZscoreAll(); } return false; } public boolean handleNormalizeMinMaxColumns() { try { targetRow = null; if (sourceRow == null) { return false; } targetRow = new ArrayList<>(); if (includeRowNumber) { targetRow.add("" + sourceRowIndex); } for (int c = 0; c < colsLen; c++) { int i = cols.get(c); if (i < 0 || i >= sourceRow.size()) { targetRow.add(null); } else { String s = sourceRow.get(i); double v = DoubleTools.toDouble(s, invalidAs); if (DoubleTools.invalidDouble(v)) { targetRow.add(null); } else { v = from + statisticData[c].dTmp * (v - statisticData[c].minimum); targetRow.add(DoubleTools.scale(v, scale) + ""); } } } if (otherCols != null) { for (int c : otherCols) { if (c < 0 || c >= sourceRow.size()) { targetRow.add(null); } else { targetRow.add(sourceRow.get(c)); } } } return true; } catch (Exception e) { return false; } } public boolean handleNormalizeSumColumns() { try { targetRow = null; if (sourceRow == null) { return false; } targetRow = new ArrayList<>(); if (includeRowNumber) { targetRow.add("" + sourceRowIndex); } for (int c = 0; c < colsLen; c++) { int i = cols.get(c); if (i < 0 || i >= sourceRow.size()) { targetRow.add(null); } else { String s = sourceRow.get(i); double v = DoubleTools.toDouble(s, invalidAs); if (DoubleTools.invalidDouble(v)) { targetRow.add(null); } else { v = v * colValues[c]; targetRow.add(DoubleTools.scale(v, scale) + ""); } } } if (otherCols != null) { for (int c : otherCols) { if (c < 0 || c >= sourceRow.size()) { targetRow.add(null); } else { targetRow.add(sourceRow.get(c)); } } } return true; } catch (Exception e) { return false; } } public boolean handleNormalizeZscoreColumns() { try { targetRow = null; if (sourceRow == null) { return false; } targetRow = new ArrayList<>(); if (includeRowNumber) { targetRow.add("" + sourceRowIndex); } for (int c = 0; c < colsLen; c++) { int i = cols.get(c); if (i < 0 || i >= sourceRow.size()) { targetRow.add(null); } else { String s = sourceRow.get(i); double v = DoubleTools.toDouble(s, invalidAs); if (DoubleTools.invalidDouble(v)) { targetRow.add(null); } else { double k = statisticData[c].getPopulationStandardDeviation(); if (k == 0) { k = AppValues.TinyDouble; } v = (v - statisticData[c].mean) / k; targetRow.add(DoubleTools.scale(v, scale) + ""); } } } if (otherCols != null) { for (int c : otherCols) { if (c < 0 || c >= sourceRow.size()) { targetRow.add(null); } else { targetRow.add(sourceRow.get(c)); } } } return true; } catch (Exception e) { return false; } } public boolean handleNormalizeMinMaxAll() { try { targetRow = null; if (sourceRow == null) { return false; } targetRow = new ArrayList<>(); if (includeRowNumber) { targetRow.add("" + sourceRowIndex); } for (int c = 0; c < colsLen; c++) { int i = cols.get(c); if (i < 0 || i >= sourceRow.size()) { targetRow.add(null); } else { String s = sourceRow.get(i); double v = DoubleTools.toDouble(s, invalidAs); if (DoubleTools.invalidDouble(v)) { targetRow.add(null); } else { v = from + statisticAll.dTmp * (v - statisticAll.minimum); targetRow.add(DoubleTools.scale(v, scale) + ""); } } } if (otherCols != null) { for (int c : otherCols) { if (c < 0 || c >= sourceRow.size()) { targetRow.add(null); } else { targetRow.add(sourceRow.get(c)); } } } return true; } catch (Exception e) { return false; } } public boolean handleNormalizeSumAll() { try { targetRow = null; if (sourceRow == null) { return false; } targetRow = new ArrayList<>(); if (includeRowNumber) { targetRow.add("" + sourceRowIndex); } for (int c = 0; c < colsLen; c++) { int i = cols.get(c); if (i < 0 || i >= sourceRow.size()) { targetRow.add(null); } else { String s = sourceRow.get(i); double v = DoubleTools.toDouble(s, invalidAs); if (DoubleTools.invalidDouble(v)) { targetRow.add(null); } else { v = v * tValue; targetRow.add(DoubleTools.scale(v, scale) + ""); } } } if (otherCols != null) { for (int c : otherCols) { if (c < 0 || c >= sourceRow.size()) { targetRow.add(null); } else { targetRow.add(sourceRow.get(c)); } } } return true; } catch (Exception e) { return false; } } public boolean handleNormalizeZscoreAll() { try { targetRow = null; if (sourceRow == null) { return false; } targetRow = new ArrayList<>(); if (includeRowNumber) { targetRow.add("" + sourceRowIndex); } for (int c = 0; c < colsLen; c++) { int i = cols.get(c); if (i < 0 || i >= sourceRow.size()) { targetRow.add(null); } else { String s = sourceRow.get(i); double v = DoubleTools.toDouble(s, invalidAs); if (DoubleTools.invalidDouble(v)) { targetRow.add(null); } else { double k = statisticAll.getPopulationStandardDeviation(); if (k == 0) { k = AppValues.TinyDouble; } v = (v - statisticAll.mean) / k; targetRow.add(DoubleTools.scale(v, scale) + ""); } } } if (otherCols != null) { for (int c : otherCols) { if (c < 0 || c >= sourceRow.size()) { targetRow.add(null); } else { targetRow.add(sourceRow.get(c)); } } } return true; } catch (Exception e) { return false; } } public boolean handleNormalizeRows(Normalization.Algorithm a) { try { targetRow = null; if (sourceRow == null) { return false; } targetRow = new ArrayList<>(); if (includeRowNumber) { targetRow.add("" + sourceRowIndex); } String[] values = new String[colsLen]; for (int c = 0; c < colsLen; c++) { int i = cols.get(c); if (i < 0 || i >= sourceRow.size()) { values[c] = DoubleTools.value(invalidAs) + ""; } else { values[c] = sourceRow.get(i); } } values = Normalization.create() .setA(a).setFrom(from).setTo(to).setInvalidAs(invalidAs) .setSourceVector(values) .calculate(); if (values == null) { return false; } for (String s : values) { double d = DoubleTools.toDouble(s, invalidAs); if (DoubleTools.invalidDouble(d)) { targetRow.add(null); } else { targetRow.add(DoubleTools.scale(d, scale) + ""); } } if (otherCols != null) { for (int c : otherCols) { if (c < 0 || c >= sourceRow.size()) { targetRow.add(null); } else { targetRow.add(sourceRow.get(c)); } } } return true; } catch (Exception e) { return false; } } /* set */ public Data2DNormalize setType(Type type) { this.type = type; return this; } public Data2DNormalize setStatisticData(DoubleStatistic[] statisticData) { this.statisticData = statisticData; return this; } public Data2DNormalize setStatisticAll(DoubleStatistic statisticAll) { this.statisticAll = statisticAll; return this; } public Data2DNormalize setColValues(double[] colValues) { this.colValues = colValues; return this; } public Data2DNormalize setFrom(double from) { this.from = from; return this; } public Data2DNormalize setTo(double to) { this.to = to; return this; } public Data2DNormalize settValue(double tValue) { this.tValue = tValue; return this; } public Data2DNormalize setA(Normalization.Algorithm a) { this.a = a; return this; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DStatistic.java
released/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DStatistic.java
package mara.mybox.data2d.operate; import java.util.ArrayList; import java.util.List; import mara.mybox.calculation.DescriptiveStatistic; import mara.mybox.calculation.DescriptiveStatistic.StatisticType; import mara.mybox.calculation.DoubleStatistic; import mara.mybox.data2d.Data2D_Edit; import mara.mybox.dev.MyBoxLog; import mara.mybox.tools.DoubleTools; import org.apache.commons.math3.stat.descriptive.moment.Skewness; /** * @Author Mara * @CreateDate 2022-2-25 * @License Apache License Version 2.0 */ public class Data2DStatistic extends Data2DOperate { protected Type type; protected DoubleStatistic[] statisticData; protected DoubleStatistic statisticAll; protected DescriptiveStatistic statisticCalculation; protected double[] colValues; protected List<Skewness> skewnessList; protected Skewness skewnessAll; protected boolean sumAbs; public static enum Type { ColumnsPass1, ColumnsPass2, Rows, AllPass1, AllPass2 } public static Data2DStatistic create(Data2D_Edit data) { Data2DStatistic op = new Data2DStatistic(); return op.setSourceData(data) ? op : null; } @Override public boolean checkParameters() { if (!super.checkParameters() || cols == null || cols.isEmpty() || type == null || statisticCalculation == null) { return false; } switch (type) { case ColumnsPass1: if (statisticData == null) { return false; } colValues = new double[colsLen]; if (statisticCalculation.include(StatisticType.Skewness)) { skewnessList = new ArrayList<>(); for (int i = 0; i < cols.size(); i++) { skewnessList.add(new Skewness()); } } break; case ColumnsPass2: if (statisticData == null) { return false; } for (int i = 0; i < cols.size(); i++) { statisticData[i].dTmp = 0; } break; case AllPass1: if (statisticAll == null) { return false; } if (statisticCalculation.include(StatisticType.Skewness)) { skewnessAll = new Skewness(); } break; case AllPass2: if (statisticAll == null) { return false; } statisticAll.dTmp = 0; break; case Rows: break; default: return false; } return true; } @Override public boolean handleRow() { switch (type) { case ColumnsPass1: return handleStatisticColumnsPass1(); case ColumnsPass2: return handleStatisticColumnsPass2(); case AllPass1: return handleStatisticAllPass1(); case AllPass2: return handleStatisticAllPass2(); case Rows: return handleStatisticRows(); } return false; } public boolean handleStatisticColumnsPass1() { try { for (int i = 0; i < colsLen; i++) { int col = cols.get(i); if (col < 0 || col >= sourceRow.size()) { continue; } String s = sourceRow.get(col); double v = DoubleTools.toDouble(s, invalidAs); if (DoubleTools.invalidDouble(v)) { switch (invalidAs) { case Zero: v = 0; break; default: statisticData[i].invalidCount++; continue; } } statisticData[i].count++; if (sumAbs) { statisticData[i].sum += Math.abs(v); } else { statisticData[i].sum += v; } if (statisticCalculation.include(StatisticType.MaximumQ4) && v > statisticData[i].maximum) { statisticData[i].maximum = v; } if (statisticCalculation.include(StatisticType.MinimumQ0) && v < statisticData[i].minimum) { statisticData[i].minimum = v; } if (statisticCalculation.include(StatisticType.GeometricMean)) { statisticData[i].geometricMean = statisticData[i].geometricMean * v; } if (statisticCalculation.include(StatisticType.SumOfSquares)) { statisticData[i].sumSquares += v * v; } if (statisticCalculation.include(StatisticType.Skewness)) { skewnessList.get(i).increment(v); } } return true; } catch (Exception e) { return false; } } public boolean handleStatisticColumnsPass2() { try { for (int c = 0; c < colsLen; c++) { if (statisticData[c].count == 0) { continue; } int i = cols.get(c); if (i < 0 || i >= sourceRow.size()) { continue; } String s = sourceRow.get(i); double v = DoubleTools.toDouble(s, invalidAs); if (DoubleTools.invalidDouble(v)) { switch (invalidAs) { case Zero: v = 0; break; default: continue; } } v = v - statisticData[c].mean; statisticData[c].dTmp += v * v; } return true; } catch (Exception e) { return false; } } public boolean handleStatisticAllPass1() { try { for (int c = 0; c < colsLen; c++) { int i = cols.get(c); if (i < 0 || i >= sourceRow.size()) { continue; } String s = sourceRow.get(i); double v = DoubleTools.toDouble(s, invalidAs); if (DoubleTools.invalidDouble(v)) { switch (invalidAs) { case Zero: v = 0; break; default: statisticAll.invalidCount++; continue; } } statisticAll.count++; statisticAll.sum += v; if (statisticCalculation.include(StatisticType.MaximumQ4) && v > statisticAll.maximum) { statisticAll.maximum = v; } if (statisticCalculation.include(StatisticType.MinimumQ0) && v < statisticAll.minimum) { statisticAll.minimum = v; } if (statisticCalculation.include(StatisticType.GeometricMean)) { statisticAll.geometricMean = statisticAll.geometricMean * v; } if (statisticCalculation.include(StatisticType.SumOfSquares)) { statisticAll.sumSquares += v * v; } if (statisticCalculation.include(StatisticType.Skewness)) { skewnessAll.increment(v); } } return true; } catch (Exception e) { return false; } } public boolean handleStatisticAllPass2() { try { for (int c = 0; c < colsLen; c++) { if (statisticAll.count == 0) { continue; } int i = cols.get(c); if (i < 0 || i >= sourceRow.size()) { continue; } String s = sourceRow.get(i); double v = DoubleTools.toDouble(s, invalidAs); if (DoubleTools.invalidDouble(v)) { switch (invalidAs) { case Zero: v = 0; break; default: continue; } } v = v - statisticAll.mean; statisticAll.dTmp += v * v; } return true; } catch (Exception e) { return false; } } public boolean handleStatisticRows() { try { targetRow = null; if (sourceRow == null) { return false; } targetRow = new ArrayList<>(); int startIndex; if (statisticCalculation.getCategoryName() == null) { targetRow.add("" + sourceRowIndex); startIndex = 0; } else { targetRow.add(sourceRow.get(cols.get(0))); startIndex = 1; } String[] values = new String[colsLen - startIndex]; for (int c = startIndex; c < colsLen; c++) { int i = cols.get(c); if (i < 0 || i >= sourceRow.size()) { continue; } values[c - startIndex] = sourceRow.get(i); } DoubleStatistic statistic = new DoubleStatistic(values, statisticCalculation); targetRow.addAll(statistic.toStringList()); return true; } catch (Exception e) { return false; } } @Override public boolean end() { try { switch (type) { case ColumnsPass1: for (int c = 0; c < colsLen; c++) { if (statisticData[c].count > 0) { if (!DoubleTools.invalidDouble(statisticData[c].sum)) { statisticData[c].mean = statisticData[c].sum / statisticData[c].count; } else { statisticData[c].mean = Double.NaN; } if (statisticCalculation.include(StatisticType.GeometricMean)) { if (!DoubleTools.invalidDouble(statisticData[c].geometricMean)) { statisticData[c].geometricMean = Math.pow(statisticData[c].geometricMean, 1d / statisticData[c].count); } else { statisticData[c].geometricMean = Double.NaN; } } } else { statisticData[c].mean = Double.NaN; statisticData[c].geometricMean = Double.NaN; } if (statisticCalculation.include(StatisticType.Skewness)) { statisticData[c].skewness = skewnessList.get(c).getResult(); } if (statisticData[c].maximum == -Double.MAX_VALUE) { statisticData[c].maximum = Double.NaN; } if (statisticData[c].minimum == Double.MAX_VALUE) { statisticData[c].minimum = Double.NaN; } } break; case ColumnsPass2: for (int c = 0; c < colsLen; c++) { if (statisticData[c].count > 0 && !DoubleTools.invalidDouble(statisticData[c].dTmp)) { statisticData[c].populationVariance = statisticData[c].dTmp / statisticData[c].count; statisticData[c].sampleVariance = statisticData[c].dTmp / (statisticData[c].count - 1); if (statisticCalculation.include(StatisticType.PopulationStandardDeviation)) { statisticData[c].populationStandardDeviation = Math.sqrt(statisticData[c].populationVariance); } if (statisticCalculation.include(StatisticType.SampleStandardDeviation)) { statisticData[c].sampleStandardDeviation = Math.sqrt(statisticData[c].sampleVariance); } } else { statisticData[c].populationVariance = Double.NaN; statisticData[c].sampleVariance = Double.NaN; statisticData[c].populationStandardDeviation = Double.NaN; statisticData[c].sampleStandardDeviation = Double.NaN; } } break; case AllPass1: if (statisticAll.count > 0) { if (!DoubleTools.invalidDouble(statisticAll.sum)) { statisticAll.mean = statisticAll.sum / statisticAll.count; } else { statisticAll.mean = Double.NaN; } if (statisticCalculation.include(StatisticType.GeometricMean)) { if (!DoubleTools.invalidDouble(statisticAll.geometricMean)) { statisticAll.geometricMean = Math.pow(statisticAll.geometricMean, 1d / statisticAll.count); } else { statisticAll.geometricMean = Double.NaN; } } } else { statisticAll.mean = Double.NaN; statisticAll.geometricMean = Double.NaN; } if (statisticCalculation.include(StatisticType.Skewness)) { statisticAll.skewness = skewnessAll.getResult(); } if (statisticAll.maximum == -Double.MAX_VALUE) { statisticAll.maximum = Double.NaN; } if (statisticAll.minimum == Double.MAX_VALUE) { statisticAll.minimum = Double.NaN; } break; case AllPass2: if (statisticAll.count > 0 && !DoubleTools.invalidDouble(statisticAll.dTmp)) { statisticAll.populationVariance = statisticAll.dTmp / statisticAll.count; statisticAll.sampleVariance = statisticAll.dTmp / (statisticAll.count - 1); if (statisticCalculation.include(StatisticType.PopulationStandardDeviation)) { statisticAll.populationStandardDeviation = Math.sqrt(statisticAll.populationVariance); } if (statisticCalculation.include(StatisticType.SampleStandardDeviation)) { statisticAll.sampleStandardDeviation = Math.sqrt(statisticAll.sampleVariance); } } else { statisticAll.populationVariance = Double.NaN; statisticAll.sampleVariance = Double.NaN; statisticAll.populationStandardDeviation = Double.NaN; statisticAll.sampleStandardDeviation = Double.NaN; } break; } return super.end(); } catch (Exception e) { MyBoxLog.error(e); if (task != null) { task.setError(e.toString()); } return false; } } /* set */ public Data2DStatistic setType(Type type) { this.type = type; return this; } public Data2DStatistic setStatisticData(DoubleStatistic[] statisticData) { this.statisticData = statisticData; return this; } public Data2DStatistic setStatisticAll(DoubleStatistic statisticAll) { this.statisticAll = statisticAll; return this; } public Data2DStatistic setStatisticCalculation(DescriptiveStatistic statisticCalculation) { this.statisticCalculation = statisticCalculation; invalidAs = statisticCalculation.invalidAs; return this; } public Data2DStatistic setSumAbs(boolean sumAbs) { this.sumAbs = sumAbs; return this; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DSingleColumn.java
released/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DSingleColumn.java
package mara.mybox.data2d.operate; import java.sql.Connection; import mara.mybox.data2d.Data2D_Edit; import mara.mybox.data2d.DataTable; import mara.mybox.db.Database; import mara.mybox.db.data.ColumnDefinition.InvalidAs; import mara.mybox.db.data.Data2DColumn; import mara.mybox.db.data.Data2DRow; import mara.mybox.db.table.TableData2D; import mara.mybox.dev.MyBoxLog; /** * @Author Mara * @CreateDate 2022-2-25 * @License Apache License Version 2.0 */ public class Data2DSingleColumn extends Data2DOperate { protected DataTable writerTable; protected TableData2D writerTableData2D; protected long count; public static Data2DSingleColumn create(Data2D_Edit data) { Data2DSingleColumn op = new Data2DSingleColumn(); return op.setSourceData(data) ? op : null; } @Override public boolean checkParameters() { if (!super.checkParameters() || cols == null || cols.isEmpty() || conn == null || writerTable == null) { return false; } writerTableData2D = writerTable.getTableData2D(); count = 0; return true; } @Override public boolean handleRow() { try { if (sourceRow == null) { return false; } int len = sourceRow.size(); for (int col : cols) { if (col >= 0 && col < len) { Data2DRow data2DRow = writerTableData2D.newRow(); Data2DColumn targetColumn = writerTable.columnByName("data"); String value = sourceRow.get(col); if (targetColumn != null) { data2DRow.setValue("data", targetColumn.fromString(value, InvalidAs.Empty)); writerTableData2D.insertData(conn, data2DRow); if (++count % Database.BatchSize == 0) { conn.commit(); } } } } return true; } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e); } return false; } } /* set */ public Data2DSingleColumn setConn(Connection conn) { this.conn = conn; closeConn = false; return this; } public Data2DSingleColumn setWriterTable(DataTable writerTable) { this.writerTable = writerTable; return this; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DRange.java
released/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DRange.java
package mara.mybox.data2d.operate; import java.util.ArrayList; import mara.mybox.data2d.Data2D_Edit; /** * @Author Mara * @CreateDate 2022-2-25 * @License Apache License Version 2.0 */ public class Data2DRange extends Data2DOperate { protected long start, end; // 1-based, include end public static Data2DRange create(Data2D_Edit data) { Data2DRange op = new Data2DRange(); return op.setSourceData(data) ? op : null; } @Override public boolean checkParameters() { return super.checkParameters() && cols != null && !cols.isEmpty(); } @Override public boolean handleRow() { try { targetRow = null; if (sourceRow == null) { return false; } targetRow = new ArrayList<>(); for (int col : cols) { if (col >= 0 && col < sourceRow.size()) { targetRow.add(sourceRow.get(col)); } else { targetRow.add(null); } } if (targetRow.isEmpty() || sourceRowIndex < start) { return false; } if (sourceRowIndex > end) { stop(); return false; } if (includeRowNumber) { targetRow.add(0, sourceRowIndex + ""); } return true; } catch (Exception e) { showError(e.toString()); return false; } } /* set */ public Data2DRange setStart(long start) { this.start = start; return this; } public Data2DRange setEnd(long end) { this.end = end; return this; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DReadTotal.java
released/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DReadTotal.java
package mara.mybox.data2d.operate; import mara.mybox.data2d.Data2D_Edit; /** * @Author Mara * @CreateDate 2022-2-25 * @License Apache License Version 2.0 */ public class Data2DReadTotal extends Data2DOperate { public static Data2DReadTotal create(Data2D_Edit data) { Data2DReadTotal op = new Data2DReadTotal(); return op.setSourceData(data) ? op : null; } @Override public boolean go() { return reader.start(true); } @Override public void handleData() { reader.readTotal(); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DReadRows.java
released/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DReadRows.java
package mara.mybox.data2d.operate; import java.util.ArrayList; import java.util.List; import mara.mybox.data2d.Data2D_Edit; import mara.mybox.dev.MyBoxLog; /** * @Author Mara * @CreateDate 2022-2-25 * @License Apache License Version 2.0 */ public class Data2DReadRows extends Data2DOperate { protected List<List<String>> rows; protected long maxCount = -1; public static Data2DReadRows create(Data2D_Edit data) { Data2DReadRows op = new Data2DReadRows(); return op.setSourceData(data) ? op : null; } @Override public boolean checkParameters() { if (!super.checkParameters()) { return false; } rows = new ArrayList<>(); return true; } @Override public boolean handleRow() { try { if (sourceRow == null) { return false; } List<String> row = new ArrayList<>(); row.addAll(sourceRow); if (includeRowNumber) { row.add(0, sourceRowIndex + ""); } rows.add(row); if (maxCount > 0 && handledCount >= maxCount) { stopped = true; } return true; } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e); } return false; } } /* get */ public List<List<String>> getRows() { return rows; } public Data2DReadRows setMaxCount(long maxCount) { this.maxCount = maxCount; return this; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DFrequency.java
released/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DFrequency.java
package mara.mybox.data2d.operate; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.Iterator; import mara.mybox.data2d.Data2D_Edit; import mara.mybox.db.DerbyBase; import mara.mybox.dev.MyBoxLog; import mara.mybox.tools.DoubleTools; import mara.mybox.tools.NumberTools; import static mara.mybox.value.Languages.message; import org.apache.commons.math3.stat.Frequency; /** * @Author Mara * @CreateDate 2022-2-25 * @License Apache License Version 2.0 */ public class Data2DFrequency extends Data2DOperate { protected Frequency frequency; protected int colIndex; public static Data2DFrequency create(Data2D_Edit data) { Data2DFrequency op = new Data2DFrequency(); return op.setSourceData(data) ? op : null; } @Override public boolean checkParameters() { return super.checkParameters() && frequency != null && colIndex >= 0; } @Override public boolean go() { if (!sourceData.isTable() || sourceData.needFilter()) { return reader.start(false); } else { return goTable(); } } @Override public boolean handleRow() { try { frequency.addValue(sourceRow.get(colIndex)); return true; } catch (Exception e) { return false; } } @Override public boolean end() { try { targetRow = new ArrayList<>(); targetRow.add(message("All")); targetRow.add(frequency.getSumFreq() + ""); targetRow.add("100"); writeRow(); handledCount = 1; Iterator iterator = frequency.valuesIterator(); if (iterator != null) { while (iterator.hasNext()) { Object o = iterator.next(); targetRow.clear(); String value = o == null ? null : (String) o; targetRow.add(value); targetRow.add(frequency.getCount(value) + ""); targetRow.add(NumberTools.format(frequency.getPct(value) * 100, scale)); writeRow(); handledCount++; } } frequency.clear(); return super.end(); } catch (Exception e) { MyBoxLog.error(e); if (task != null) { task.setError(e.toString()); } return false; } } public boolean goTable() { try { int total = 0; conn = conn(); String sql = "SELECT count(*) AS mybox99_count FROM " + sourceData.getSheet(); if (task != null) { task.setInfo(sql); } try (PreparedStatement statement = conn.prepareStatement(sql); ResultSet results = statement.executeQuery()) { if (results.next()) { total = results.getInt("mybox99_count"); } } catch (Exception e) { } if (total == 0) { if (task != null) { task.setError(message("NoData")); } return false; } targetRow = new ArrayList<>(); targetRow.add(message("All")); targetRow.add(total + ""); targetRow.add("100"); writeRow(); handledCount = 0; String colName = sourceData.columnName(colIndex); sql = "SELECT " + colName + ", count(*) AS mybox99_count FROM " + sourceData.getSheet() + " GROUP BY " + colName + " ORDER BY mybox99_count DESC"; if (task != null) { task.setInfo(sql); } try (PreparedStatement statement = conn.prepareStatement(sql); ResultSet results = statement.executeQuery()) { String sname = DerbyBase.savedName(colName); while (results.next() && task != null && !task.isCancelled()) { targetRow = new ArrayList<>(); Object c = results.getObject(sname); targetRow.add(c != null ? c.toString() : null); int count = results.getInt("mybox99_count"); targetRow.add(count + ""); targetRow.add(DoubleTools.percentage(count, total, scale)); writeRow(); handledCount++; } } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e); } return false; } } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e); } return false; } return true; } /* set */ public Data2DFrequency setFrequency(Frequency frequency) { this.frequency = frequency; return this; } public Data2DFrequency setColIndex(int colIndex) { this.colIndex = colIndex; return this; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DSaveAs.java
released/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DSaveAs.java
package mara.mybox.data2d.operate; import mara.mybox.data2d.Data2D_Edit; import mara.mybox.data2d.writer.Data2DWriter; /** * @Author Mara * @CreateDate 2022-2-25 * @License Apache License Version 2.0 */ public class Data2DSaveAs extends Data2DOperate { public static Data2DSaveAs writeTo(Data2D_Edit data, Data2DWriter writer) { if (data == null || writer == null) { return null; } Data2DSaveAs operate = new Data2DSaveAs(); if (!operate.setSourceData(data)) { return null; } operate.addWriter(writer); return operate; } @Override public boolean handleRow() { try { targetRow = null; if (sourceRow == null) { return false; } targetRow = sourceRow; return true; } catch (Exception e) { showError(e.toString()); return false; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DSplit.java
released/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DSplit.java
package mara.mybox.data2d.operate; import java.io.File; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import mara.mybox.data2d.Data2D_Edit; import mara.mybox.data2d.DataFileCSV; import mara.mybox.db.data.ColumnDefinition; import mara.mybox.db.data.Data2DColumn; import mara.mybox.dev.MyBoxLog; import mara.mybox.tools.CsvTools; import mara.mybox.tools.FileTmpTools; import mara.mybox.tools.FileTools; import static mara.mybox.value.Languages.message; import org.apache.commons.csv.CSVPrinter; /** * @Author Mara * @CreateDate 2022-2-25 * @License Apache License Version 2.0 */ public class Data2DSplit extends Data2DOperate { protected long splitSize, startIndex, currentSize; protected String prefix; protected List<Data2DColumn> targetColumns; protected List<String> names; protected File currentFile; protected List<DataFileCSV> files; protected CSVPrinter csvPrinter; public static Data2DSplit create(Data2D_Edit data) { Data2DSplit op = new Data2DSplit(); return op.setSourceData(data) ? op : null; } @Override public boolean checkParameters() { try { if (!super.checkParameters() || cols == null || cols.isEmpty() || splitSize <= 0) { return false; } startIndex = 1; currentSize = 0; prefix = sourceData.getName(); names = new ArrayList<>(); targetColumns = new ArrayList<>(); for (int c : cols) { Data2DColumn column = sourceData.column(c); names.add(column.getColumnName()); targetColumns.add(column.copy()); } if (includeRowNumber) { targetColumns.add(0, new Data2DColumn(message("SourceRowNumber"), ColumnDefinition.ColumnType.Long)); } files = new ArrayList<>(); return true; } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e); } return false; } } @Override public boolean handleRow() { try { if (sourceRow == null) { return false; } List<String> row = new ArrayList<>(); for (int col : cols) { if (col >= 0 && col < sourceRow.size()) { row.add(sourceRow.get(col)); } else { row.add(null); } } if (row.isEmpty()) { return false; } if (currentFile == null) { currentFile = FileTmpTools.getTempFile(".csv"); csvPrinter = CsvTools.csvPrinter(currentFile); csvPrinter.printRecord(names); startIndex = sourceRowIndex; } if (includeRowNumber) { row.add(0, sourceRowIndex + ""); } csvPrinter.printRecord(row); currentSize++; if (currentSize % splitSize == 0) { closeFile(); } return true; } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e); } return false; } } public void closeFile() { try { if (csvPrinter == null) { return; } csvPrinter.flush(); csvPrinter.close(); csvPrinter = null; File file = sourceData.tmpFile(prefix + "_" + startIndex + "-" + sourceRowIndex, null, "csv"); if (FileTools.override(currentFile, file) && file.exists()) { DataFileCSV dataFileCSV = new DataFileCSV(); dataFileCSV.setTask(task); dataFileCSV.setColumns(targetColumns) .setFile(file) .setCharset(Charset.forName("UTF-8")) .setDelimiter(",") .setHasHeader(true) .setColsNumber(targetColumns.size()) .setRowsNumber(currentSize); dataFileCSV.saveAttributes(); dataFileCSV.stopTask(); files.add(dataFileCSV); } currentFile = null; currentSize = 0; } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e); } } } @Override public boolean end() { closeFile(); return super.end(); } /* set */ public Data2DSplit setSplitSize(int splitSize) { this.splitSize = splitSize; return this; } /* get */ public List<DataFileCSV> getFiles() { return files; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DRowExpression.java
released/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DRowExpression.java
package mara.mybox.data2d.operate; import java.util.ArrayList; import mara.mybox.data2d.Data2D_Edit; /** * @Author Mara * @CreateDate 2022-2-25 * @License Apache License Version 2.0 */ public class Data2DRowExpression extends Data2DOperate { protected String script, name; public static Data2DRowExpression create(Data2D_Edit data) { Data2DRowExpression op = new Data2DRowExpression(); return op.setSourceData(data) ? op : null; } @Override public boolean checkParameters() { return super.checkParameters() && cols != null && !cols.isEmpty() && script != null && name != null; } @Override public boolean handleRow() { try { targetRow = null; if (sourceRow == null) { return false; } targetRow = new ArrayList<>(); int rowSize = sourceRow.size(); for (int col : cols) { if (col >= 0 && col < rowSize) { targetRow.add(sourceRow.get(col)); } else { targetRow.add(null); } } if (targetRow.isEmpty()) { return false; } if (includeRowNumber) { targetRow.add(0, sourceRowIndex + ""); } if (sourceData.calculateDataRowExpression(script, sourceRow, sourceRowIndex)) { targetRow.add(sourceData.expressionResult()); return true; } else { stop(); return false; } } catch (Exception e) { showError(e.toString()); return false; } } /* set */ public Data2DRowExpression setScript(String script) { this.script = script; return this; } public Data2DRowExpression setName(String name) { this.name = name; return this; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DExport.java
released/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DExport.java
package mara.mybox.data2d.operate; import java.io.File; import java.util.ArrayList; import java.util.List; import mara.mybox.controller.ControlTargetFile; import mara.mybox.data2d.Data2D_Attributes.TargetType; import mara.mybox.data2d.Data2D_Edit; import mara.mybox.data2d.tools.Data2DColumnTools; import mara.mybox.data2d.writer.Data2DWriter; import mara.mybox.db.data.ColumnDefinition; import mara.mybox.db.data.Data2DColumn; import mara.mybox.tools.FileNameTools; import mara.mybox.value.AppPaths; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2022-2-25 * @License Apache License Version 2.0 */ public class Data2DExport extends Data2DOperate { protected ControlTargetFile pathController; protected List<Data2DColumn> columns; protected List<String> columnNames; protected TargetType format; protected String indent = " ", dataName, filePrefix; protected int maxLines, fileIndex, fileRowIndex; public Data2DExport() { resetExport(); } public static Data2DExport create(Data2D_Edit data) { Data2DExport op = new Data2DExport(); return op.setSourceData(data) ? op : null; } final public void resetExport() { maxLines = -1; format = null; columns = null; columnNames = null; filePrefix = null; fileIndex = 1; fileRowIndex = 0; } @Override public boolean checkParameters() { return cols != null && !cols.isEmpty() && writers != null && !writers.isEmpty() && super.checkParameters(); } @Override public void assignPrintFile(Data2DWriter writer) { if (writer == null) { return; } if (targetFile != null) { writer.setPrintFile(targetFile); } else if (pathController != null) { String name = filePrefix + (maxLines > 0 ? fileIndex : ""); writer.setPrintFile(pathController.makeTargetFile(name, "." + writer.getFileSuffix(), targetPath)); } } public void checkFileSplit() { if (maxLines > 0 && fileRowIndex >= maxLines) { closeWriters(); fileIndex++; fileRowIndex = 0; openWriters(); } } @Override public boolean handleRow() { try { targetRow = null; if (sourceRow == null) { return false; } checkFileSplit(); targetRow = new ArrayList<>(); for (int col : cols) { if (col >= 0 && col < sourceRow.size()) { String value = sourceRow.get(col); targetRow.add(value); } else { targetRow.add(null); } } if (targetRow.isEmpty()) { return false; } fileRowIndex++; if (includeRowNumber) { targetRow.add(0, sourceRowIndex + ""); } return true; } catch (Exception e) { showError(e.toString()); return false; } } /* control by external method */ public boolean initExport(ControlTargetFile controller, List<String> cols, String prefix) { pathController = controller; columnNames = cols; columns = Data2DColumnTools.toColumns(columnNames); return initExport(prefix); } public boolean initExport(String prefix) { targetFile = null; if (pathController == null || writers == null || writers.isEmpty() || columns == null || columns.isEmpty()) { return false; } filePrefix = prefix != null ? prefix : "mexport"; File file = pathController.pickFile(); if (file == null) { targetPath = new File(AppPaths.getGeneratedPath() + File.separator); } else if (file.isDirectory()) { targetPath = file; } else { targetPath = file.getParentFile(); } if (!pathController.isIsDirectory()) { if (file != null) { if (!file.exists()) { targetFile = file; } else { filePrefix = FileNameTools.prefix(file.getName()); } } } if (includeRowNumber) { if (columns != null) { columns.add(0, new Data2DColumn(message("RowNumber"), ColumnDefinition.ColumnType.Long)); } if (columnNames != null) { columnNames.add(0, message("RowNumber")); } } for (Data2DWriter writer : writers) { writer.setColumns(columns).setHeaderNames(columnNames); } sourceRowIndex = 0; fileIndex = 1; fileRowIndex = 0; return true; } public void writeRow(List<String> inRow) { try { if (inRow == null) { return; } checkFileSplit(); targetRow = new ArrayList<>(); for (int i = 0; i < inRow.size(); i++) { String v = inRow.get(i); targetRow.add(v); } fileRowIndex++; sourceRowIndex++; if (includeRowNumber) { targetRow.add(0, sourceRowIndex + ""); } writeRow(); } catch (Exception e) { showError(e.toString()); } } /* set / get */ public Data2DExport setPathController(ControlTargetFile pathController) { this.pathController = pathController; return this; } public List<String> getColumnNames() { return columnNames; } public Data2DExport setColumnNames(List<String> columnNames) { this.columnNames = columnNames; return this; } public List<Data2DColumn> getColumns() { return columns; } public Data2DExport setColumns(List<Data2DColumn> columns) { this.columns = columns; return this; } public String getIndent() { return indent; } public Data2DExport setIndent(String indent) { this.indent = indent; return this; } public String getFilePrefix() { return filePrefix; } public Data2DExport setFilePrefix(String filePrefix) { this.filePrefix = filePrefix; return this; } public int getMaxLines() { return maxLines; } public Data2DExport setMaxLines(int maxLines) { this.maxLines = maxLines; return this; } public File getTargetPath() { return targetPath; } public Data2DExport setTargetPath(File targetPath) { this.targetPath = targetPath; return this; } public File getTargetFile() { return targetFile; } public Data2DExport setTargetFile(File targetFile) { this.targetFile = targetFile; return this; } public String getDataName() { return dataName; } public Data2DExport setDataName(String dataName) { this.dataName = dataName; return this; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DPrecentage.java
released/MyBox/src/main/java/mara/mybox/data2d/operate/Data2DPrecentage.java
package mara.mybox.data2d.operate; import java.util.ArrayList; import java.util.List; import mara.mybox.data2d.Data2D_Edit; import mara.mybox.dev.MyBoxLog; import mara.mybox.tools.DoubleTools; /** * @Author Mara * @CreateDate 2022-2-25 * @License Apache License Version 2.0 */ public class Data2DPrecentage extends Data2DOperate { protected Type type; protected double[] colValues; protected double tValue; protected String toNegative; protected List<String> firstRow; public static enum Type { ColumnsPass1, ColumnsPass2, Rows, AllPass1, AllPass2 } public static Data2DPrecentage create(Data2D_Edit data) { Data2DPrecentage op = new Data2DPrecentage(); return op.setSourceData(data) ? op : null; } @Override public boolean checkParameters() { if (!super.checkParameters() || cols == null || cols.isEmpty() || type == null) { return false; } switch (type) { case ColumnsPass1: colValues = new double[colsLen]; break; case ColumnsPass2: if (colValues == null) { return false; } break; case AllPass1: tValue = 0d; break; case AllPass2: break; case Rows: break; default: return false; } return true; } @Override public boolean openWriters() { if (!super.openWriters()) { return false; } if (firstRow != null) { targetRow = firstRow; writeRow(); } return true; } @Override public boolean handleRow() { switch (type) { case ColumnsPass1: return handlePercentageColumnsPass1(); case ColumnsPass2: return handlePercentageColumnsPass2(); case AllPass1: return handlePercentageAllPass1(); case AllPass2: return handlePercentageAllPass2(); case Rows: return handlePercentageRows(); } return false; } public boolean handlePercentageColumnsPass1() { try { if (sourceRow == null) { return false; } for (int c = 0; c < colsLen; c++) { int i = cols.get(c); if (i < 0 || i >= sourceRow.size()) { continue; } double d = DoubleTools.toDouble(sourceRow.get(i), invalidAs); if (DoubleTools.invalidDouble(d)) { } else if (d < 0) { if ("abs".equals(toNegative)) { colValues[c] += Math.abs(d); } } else if (d > 0) { colValues[c] += d; } } return true; } catch (Exception e) { return false; } } public boolean handlePercentageColumnsPass2() { try { targetRow = null; if (sourceRow == null) { return false; } targetRow = new ArrayList<>(); targetRow.add("" + sourceRowIndex); for (int c = 0; c < colsLen; c++) { int i = cols.get(c); double d; if (i >= 0 && i < sourceRow.size()) { d = DoubleTools.toDouble(sourceRow.get(i), invalidAs); } else { d = DoubleTools.value(invalidAs); } double s = colValues[c]; if (DoubleTools.invalidDouble(d) || s == 0) { targetRow.add(Double.NaN + ""); } else { if (d < 0) { if ("skip".equals(toNegative)) { targetRow.add(Double.NaN + ""); continue; } else if ("abs".equals(toNegative)) { d = Math.abs(d); } else { d = 0; } } targetRow.add(DoubleTools.percentage(d, s, scale)); } } if (otherCols != null) { for (int c : otherCols) { if (c < 0 || c >= sourceRow.size()) { targetRow.add(null); } else { targetRow.add(sourceRow.get(c)); } } } return true; } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e); } return false; } } public boolean handlePercentageAllPass1() { try { if (sourceRow == null) { return false; } for (int c = 0; c < colsLen; c++) { int i = cols.get(c); if (i < 0 || i >= sourceRow.size()) { continue; } double d = DoubleTools.toDouble(sourceRow.get(i), invalidAs); if (DoubleTools.invalidDouble(d)) { } else if (d < 0) { if ("abs".equals(toNegative)) { tValue += Math.abs(d); } } else if (d > 0) { tValue += d; } } return true; } catch (Exception e) { return false; } } public boolean handlePercentageAllPass2() { try { targetRow = null; if (sourceRow == null) { return false; } targetRow = new ArrayList<>(); targetRow.add("" + sourceRowIndex); for (int c = 0; c < colsLen; c++) { int i = cols.get(c); double d; if (i >= 0 && i < sourceRow.size()) { d = DoubleTools.toDouble(sourceRow.get(i), invalidAs); } else { d = DoubleTools.value(invalidAs); } if (DoubleTools.invalidDouble(d) || tValue == 0) { targetRow.add(Double.NaN + ""); } else { if (d < 0) { if ("skip".equals(toNegative)) { targetRow.add(Double.NaN + ""); continue; } else if ("abs".equals(toNegative)) { d = Math.abs(d); } else { d = 0; } } targetRow.add(DoubleTools.percentage(d, tValue, scale)); } } if (otherCols != null) { for (int c : otherCols) { if (c < 0 || c >= sourceRow.size()) { targetRow.add(null); } else { targetRow.add(sourceRow.get(c)); } } } return true; } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e); } return false; } } public boolean handlePercentageRows() { try { targetRow = null; if (sourceRow == null) { return false; } targetRow = new ArrayList<>(); targetRow.add("" + sourceRowIndex); double sum = 0; for (int c = 0; c < colsLen; c++) { int i = cols.get(c); if (i >= 0 && i < sourceRow.size()) { double d = DoubleTools.toDouble(sourceRow.get(i), invalidAs); if (DoubleTools.invalidDouble(d)) { } else if (d < 0) { if ("abs".equals(toNegative)) { sum += Math.abs(d); } } else if (d > 0) { sum += d; } } } targetRow.add(DoubleTools.scale(sum, scale) + ""); for (int c = 0; c < colsLen; c++) { int i = cols.get(c); double d = 0; if (i >= 0 && i < sourceRow.size()) { d = DoubleTools.toDouble(sourceRow.get(i), invalidAs); } if (DoubleTools.invalidDouble(d) || sum == 0) { targetRow.add(Double.NaN + ""); } else { if (d < 0) { if ("skip".equals(toNegative)) { targetRow.add(Double.NaN + ""); continue; } else if ("abs".equals(toNegative)) { d = Math.abs(d); } else { d = 0; } } targetRow.add(DoubleTools.percentage(d, sum, scale)); } } if (otherCols != null) { for (int c : otherCols) { if (c < 0 || c >= sourceRow.size()) { targetRow.add(null); } else { targetRow.add(sourceRow.get(c)); } } } return true; } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e); } return false; } } /* set */ public Data2DPrecentage setType(Type type) { this.type = type; return this; } public Data2DPrecentage setColValues(double[] colValues) { this.colValues = colValues; return this; } public Data2DPrecentage settValue(double tValue) { this.tValue = tValue; return this; } public Data2DPrecentage setToNegative(String toNegative) { this.toNegative = toNegative; return this; } public Data2DPrecentage setFirstRow(List<String> firstRow) { this.firstRow = firstRow; return this; } /* get */ public double[] getColValues() { return colValues; } public double gettValue() { return tValue; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data2d/modify/DataTableModify.java
released/MyBox/src/main/java/mara/mybox/data2d/modify/DataTableModify.java
package mara.mybox.data2d.modify; import java.sql.PreparedStatement; import java.sql.ResultSet; import mara.mybox.data2d.DataTable; import mara.mybox.db.data.Data2DRow; import mara.mybox.db.table.TableData2D; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2022-8-16 * @License Apache License Version 2.0 */ public abstract class DataTableModify extends Data2DModify { protected DataTable sourceTable; protected TableData2D tableData2D; protected String tableName; protected Data2DRow sourceTableRow; protected PreparedStatement update; public boolean setSourceTable(DataTable data) { if (!setSourceData(data)) { return false; } sourceTable = data; tableName = sourceTable.getSheet(); tableData2D = sourceTable.getTableData2D(); tableData2D.setTableName(tableName); return true; } public boolean updateTable() { try { if (stopped || sourceTable == null || conn == null) { return false; } String sql = "SELECT count(*) FROM " + tableName; showInfo(sql); try (ResultSet query = conn.prepareStatement(sql).executeQuery()) { if (query.next()) { rowsNumber = query.getLong(1); } } sourceData.setRowsNumber(rowsNumber); if (stopped) { return false; } sourceData.saveAttributes(conn); showInfo(message("DataTable") + ": " + tableName + " " + message("RowsNumber") + ": " + rowsNumber); return true; } catch (Exception e) { showError(e.toString()); return false; } } @Override public boolean end() { return true; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data2d/modify/DataTableSetValue.java
released/MyBox/src/main/java/mara/mybox/data2d/modify/DataTableSetValue.java
package mara.mybox.data2d.modify; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import mara.mybox.data.SetValue; import mara.mybox.data2d.DataTable; import mara.mybox.data2d.tools.Data2DRowTools; import mara.mybox.db.Database; import mara.mybox.db.DerbyBase; import mara.mybox.db.data.Data2DRow; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2022-1-29 * @License Apache License Version 2.0 */ public class DataTableSetValue extends DataTableModify { public DataTableSetValue(DataTable data, SetValue value) { if (!setSourceTable(data)) { return; } initSetValue(value); sourceTable = data; } @Override public boolean go() { handledCount = 0; String sql = "SELECT * FROM " + tableName; showInfo(sql); try (Connection dconn = DerbyBase.getConnection(); PreparedStatement query = dconn.prepareStatement(sql); ResultSet results = query.executeQuery(); PreparedStatement dUpdate = dconn.prepareStatement(tableData2D.updateStatement())) { conn = dconn; conn.setAutoCommit(false); update = dUpdate; while (results.next() && !stopped && !reachMaxFiltered) { sourceTableRow = tableData2D.readData(results); sourceRow = Data2DRowTools.toStrings(sourceTableRow, columns); sourceRowIndex++; setValue(sourceRow, sourceRowIndex); } if (!stopped) { update.executeBatch(); conn.commit(); updateTable(); } showInfo(message("Updated") + ": " + handledCount); conn.close(); conn = null; return true; } catch (Exception e) { failStop(e.toString()); return false; } } @Override public void writeRow() { try { if (stopped || !rowChanged || targetRow == null || targetRow.isEmpty()) { return; } Data2DRow data2DRow = tableData2D.newRow(); for (int i = 0; i < columnsNumber; ++i) { column = columns.get(i); columnName = column.getColumnName(); data2DRow.setValue(columnName, column.fromString(targetRow.get(i), invalidAs)); } if (tableData2D.setUpdateStatement(conn, update, data2DRow)) { update.addBatch(); if (handledCount % Database.BatchSize == 0) { update.executeBatch(); conn.commit(); showInfo(message("Updated") + ": " + handledCount); } } } catch (Exception e) { showError(e.toString()); } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data2d/modify/DataTableClear.java
released/MyBox/src/main/java/mara/mybox/data2d/modify/DataTableClear.java
package mara.mybox.data2d.modify; import java.sql.Connection; import mara.mybox.data2d.DataTable; import mara.mybox.db.DerbyBase; /** * @Author Mara * @CreateDate 2022-1-29 * @License Apache License Version 2.0 */ public class DataTableClear extends DataTableModify { public DataTableClear(DataTable data) { setSourceTable(data); } @Override public boolean go() { try (Connection dconn = DerbyBase.getConnection()) { conn = dconn; String sql = "DELETE FROM " + tableName; showInfo(sql); handledCount = tableData2D.clearData(conn); if (handledCount < 0) { return false; } return updateTable(); } catch (Exception e) { showError(e.toString()); return false; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data2d/modify/Data2DSaveAttributes.java
released/MyBox/src/main/java/mara/mybox/data2d/modify/Data2DSaveAttributes.java
package mara.mybox.data2d.modify; import java.util.ArrayList; import java.util.List; import mara.mybox.data2d.Data2D; import mara.mybox.data2d.Data2D_Edit; import mara.mybox.db.data.Data2DColumn; /** * @Author Mara * @CreateDate 2022-2-25 * @License Apache License Version 2.0 */ public class Data2DSaveAttributes extends Data2DModify { protected Data2D attributes; public static Data2DSaveAttributes create(Data2D_Edit data, Data2D attrs) { if (data == null || attrs == null) { return null; } Data2DSaveAttributes operate = new Data2DSaveAttributes(); if (!operate.setSourceData(data)) { return null; } operate.attributes = attrs; operate.initWriter(); return operate; } @Override public void initWriter() { writer = sourceData.selfWriter(); writer.setDataName(attributes.getDataName()) .setTargetData(attributes) .setColumns(attributes.getColumns()) .setHeaderNames(attributes.columnNames()) .setTargetScale(attributes.getScale()) .setTargetMaxRandom(attributes.getMaxRandom()) .setTargetComments(attributes.getComments()); addWriter(writer); } @Override public void handleRow(List<String> row, long index) { try { sourceRow = row; sourceRowIndex = index; targetRow = null; if (sourceRow == null) { return; } targetRow = new ArrayList<>(); for (Data2DColumn col : attributes.columns) { int colIndex = col.getIndex(); if (colIndex < 0 || colIndex >= sourceRow.size()) { targetRow.add(null); } else { targetRow.add(sourceRow.get(colIndex)); } } writeRow(); } catch (Exception e) { showError(e.toString()); } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data2d/modify/Data2DDelete.java
released/MyBox/src/main/java/mara/mybox/data2d/modify/Data2DDelete.java
package mara.mybox.data2d.modify; import java.util.List; import mara.mybox.data2d.Data2D_Edit; import mara.mybox.dev.MyBoxLog; /** * @Author Mara * @CreateDate 2022-8-16 * @License Apache License Version 2.0 */ public class Data2DDelete extends Data2DModify { public static Data2DDelete create(Data2D_Edit data) { if (data == null) { return null; } Data2DDelete operate = new Data2DDelete(); if (!operate.setSourceData(data)) { return null; } operate.initWriter(); return operate; } @Override public void handleRow(List<String> row, long index) { try { sourceRow = row; sourceRowIndex = index; targetRow = null; rowPassFilter = sourceData.filterDataRow(sourceRow, sourceRowIndex); reachMaxFiltered = sourceData.filterReachMaxPassed(); deleteRow(rowPassFilter && !reachMaxFiltered); } catch (Exception e) { MyBoxLog.console(e); } } public void deleteRow(boolean handle) { if (handle) { handledCount++; } else { targetRow = sourceRow; writeRow(); } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data2d/modify/Data2DSetValue.java
released/MyBox/src/main/java/mara/mybox/data2d/modify/Data2DSetValue.java
package mara.mybox.data2d.modify; import java.util.List; import mara.mybox.data.SetValue; import mara.mybox.data2d.Data2D_Edit; /** * @Author Mara * @CreateDate 2022-8-16 * @License Apache License Version 2.0 */ public class Data2DSetValue extends Data2DModify { public static Data2DSetValue create(Data2D_Edit data, SetValue value) { if (data == null || value == null) { return null; } Data2DSetValue operate = new Data2DSetValue(); if (!operate.setSourceData(data) || !operate.initSetValue(value)) { return null; } operate.initWriter(); return operate; } @Override public void handleRow(List<String> row, long index) { setValue(row, index); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data2d/modify/Data2DModify.java
released/MyBox/src/main/java/mara/mybox/data2d/modify/Data2DModify.java
package mara.mybox.data2d.modify; import java.util.ArrayList; import java.util.List; import java.util.Random; import mara.mybox.data.SetValue; import mara.mybox.data2d.DataTable; import mara.mybox.data2d.operate.Data2DOperate; import mara.mybox.data2d.writer.Data2DWriter; import mara.mybox.db.data.ColumnDefinition.InvalidAs; import mara.mybox.db.data.Data2DColumn; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2022-8-16 * @License Apache License Version 2.0 */ public abstract class Data2DModify extends Data2DOperate { protected Data2DWriter writer; protected long rowsNumber; protected int columnsNumber; protected List<Data2DColumn> columns; protected int setValueIndex, setValueDigit; protected SetValue setValue; protected String setValueParameter; protected Random random = new Random(); protected boolean valueInvalid, validateColumn, rejectInvalid, skipInvalid; protected Data2DColumn column; protected String columnName, currentValue, newValue; protected boolean rowChanged, handleRow; protected int rowSize; public void initWriter() { writer = sourceData.selfWriter(); addWriter(writer); } public boolean initSetValue(SetValue v) { if (sourceData == null || v == null) { return false; } setValue = v; setValueDigit = setValue.countFinalDigit(sourceData.getRowsNumber()); setValueIndex = setValue.getStart(); setValueParameter = setValue.getParameter(); random = new Random(); return true; } @Override public boolean checkParameters() { // rowsNumber = 0; valueInvalid = false; rejectInvalid = sourceData.rejectInvalidWhenSave() || invalidAs == InvalidAs.Fail; skipInvalid = invalidAs == InvalidAs.Skip; validateColumn = rejectInvalid || skipInvalid; columns = sourceData.getColumns(); columnsNumber = columns.size(); return super.checkParameters(); } public void setValue(List<String> row, long index) { try { sourceRow = row; sourceRowIndex = index; targetRow = null; if (sourceRow == null) { return; } rowPassFilter = sourceData.filterDataRow(sourceRow, sourceRowIndex); reachMaxFiltered = sourceData.filterReachMaxPassed(); handleRow = rowPassFilter && !reachMaxFiltered; if (!handleRow && (sourceData instanceof DataTable)) { return; } targetRow = new ArrayList<>(); rowSize = sourceRow.size(); rowChanged = false; for (int i = 0; i < columnsNumber; i++) { if (i < rowSize) { currentValue = sourceRow.get(i); } else { currentValue = null; } if (handleRow && cols.contains(i)) { column = columns.get(i); newValue = setValue.makeValue(sourceData, column, currentValue, sourceRow, sourceRowIndex, setValueIndex, setValueDigit, random); valueInvalid = setValue.valueInvalid; if (!valueInvalid && validateColumn) { if (!column.validValue(newValue)) { valueInvalid = true; } } if (valueInvalid) { if (skipInvalid) { newValue = currentValue; } else if (rejectInvalid) { failStop(message("InvalidData") + ". " + message("Column") + ":" + column.getColumnName() + " " + message("Value") + ": " + newValue); return; } } if ((currentValue == null && newValue != null) || (currentValue != null && !currentValue.equals(newValue))) { rowChanged = true; } } else { newValue = currentValue; } targetRow.add(newValue); } if (rowChanged) { handledCount++; setValueIndex++; } writeRow(); } catch (Exception e) { showError(e.toString()); } } @Override public boolean end() { try { if (!super.end() || writer == null || writer.getTargetData() == null) { return false; } rowsNumber = writer.getTargetRowIndex(); sourceData.setRowsNumber(rowsNumber); sourceData.setTableChanged(false); return true; } catch (Exception e) { showError(e.toString()); return false; } } public long rowsCount() { if (failed) { return -1; } else { return rowsNumber; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data2d/modify/Data2DSavePage.java
released/MyBox/src/main/java/mara/mybox/data2d/modify/Data2DSavePage.java
package mara.mybox.data2d.modify; import mara.mybox.data2d.Data2D_Edit; /** * @Author Mara * @CreateDate 2022-2-25 * @License Apache License Version 2.0 */ public class Data2DSavePage extends Data2DModify { public static Data2DSavePage save(Data2D_Edit data) { if (data == null) { return null; } Data2DSavePage operate = new Data2DSavePage(); if (!operate.setSourceData(data)) { return null; } operate.initWriter(); return operate; } @Override public boolean handleRow() { try { targetRow = null; if (sourceRow == null) { return false; } targetRow = sourceRow; return true; } catch (Exception e) { showError(e.toString()); return false; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data2d/modify/DataTableDelete.java
released/MyBox/src/main/java/mara/mybox/data2d/modify/DataTableDelete.java
package mara.mybox.data2d.modify; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.List; import mara.mybox.data2d.DataTable; import mara.mybox.data2d.tools.Data2DRowTools; import mara.mybox.db.Database; import mara.mybox.db.DerbyBase; import mara.mybox.dev.MyBoxLog; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2022-1-29 * @License Apache License Version 2.0 */ public class DataTableDelete extends DataTableModify { protected PreparedStatement delete; public DataTableDelete(DataTable data) { setSourceTable(data); } @Override public boolean go() { handledCount = 0; String sql = "SELECT * FROM " + tableName; showInfo(sql); try (Connection dconn = DerbyBase.getConnection(); PreparedStatement statement = dconn.prepareStatement(sql); ResultSet results = statement.executeQuery(); PreparedStatement dDelete = dconn.prepareStatement(tableData2D.deleteStatement())) { conn = dconn; conn.setAutoCommit(false); delete = dDelete; while (results.next() && !stopped && !reachMaxFiltered) { sourceTableRow = tableData2D.readData(results); sourceRow = Data2DRowTools.toStrings(sourceTableRow, columns); sourceRowIndex++; handleRow(sourceRow, sourceRowIndex); } if (!stopped) { delete.executeBatch(); conn.commit(); updateTable(); } showInfo(message("Deleted") + ": " + handledCount); conn.close(); conn = null; return true; } catch (Exception e) { failStop(e.toString()); return false; } } @Override public void handleRow(List<String> row, long index) { try { sourceRow = row; sourceRowIndex = index; targetRow = null; rowPassFilter = sourceData.filterDataRow(sourceRow, sourceRowIndex); reachMaxFiltered = sourceData.filterReachMaxPassed(); if (rowPassFilter && !reachMaxFiltered) { if (tableData2D.setDeleteStatement(conn, delete, sourceTableRow)) { delete.addBatch(); if (++handledCount % Database.BatchSize == 0) { delete.executeBatch(); conn.commit(); showInfo(message("Deleted") + ": " + handledCount); } } } } catch (Exception e) { MyBoxLog.console(e); } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data2d/modify/Data2DClear.java
released/MyBox/src/main/java/mara/mybox/data2d/modify/Data2DClear.java
package mara.mybox.data2d.modify; import mara.mybox.data2d.Data2D_Edit; /** * @Author Mara * @CreateDate 2022-8-16 * @License Apache License Version 2.0 */ public class Data2DClear extends Data2DModify { public static Data2DClear create(Data2D_Edit data) { if (data == null) { return null; } Data2DClear operate = new Data2DClear(); if (!operate.setSourceData(data)) { return null; } operate.initWriter(); return operate; } @Override public boolean go() { handledCount = sourceData.getRowsNumber(); return true; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data2d/example/Regression.java
released/MyBox/src/main/java/mara/mybox/data2d/example/Regression.java
package mara.mybox.data2d.example; import java.util.ArrayList; import java.util.List; import javafx.event.ActionEvent; import javafx.scene.control.Menu; import javafx.scene.control.MenuItem; import javafx.scene.control.SeparatorMenuItem; import mara.mybox.controller.BaseData2DLoadController; import mara.mybox.data2d.DataFileCSV; import static mara.mybox.data2d.example.Data2DExampleTools.makeExampleFile; import mara.mybox.db.data.ColumnDefinition; import mara.mybox.db.data.Data2DColumn; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.HelpTools; import static mara.mybox.fxml.style.NodeStyleTools.linkStyle; import mara.mybox.fxml.style.StyleTools; import mara.mybox.value.Languages; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2022-9-15 * @License Apache License Version 2.0 */ public class Regression { public static Menu menu(String lang, BaseData2DLoadController controller) { try { Menu regressionMenu = new Menu(message(lang, "RegressionData"), StyleTools.getIconImageView("iconLinearPgression.png")); MenuItem menu = new MenuItem(message(lang, "IncomeHappiness")); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = IncomeHappiness(lang); if (makeExampleFile("DataAnalyse_IncomeHappiness", data)) { controller.loadDef(data); } }); regressionMenu.getItems().add(menu); menu = new MenuItem(message(lang, "ExperienceSalary")); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = ExperienceSalary(lang); if (makeExampleFile("DataAnalyse_ExperienceSalary", data)) { controller.loadDef(data); } }); regressionMenu.getItems().add(menu); menu = new MenuItem(message(lang, "IrisSpecies")); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = IrisSpecies(lang); if (makeExampleFile("DataAnalyse_IrisSpecies", data)) { controller.loadDef(data); } }); regressionMenu.getItems().add(menu); menu = new MenuItem(message(lang, "DiabetesPrediction")); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = DiabetesPrediction(lang); if (makeExampleFile("DataAnalyse_DiabetesPrediction", data)) { controller.loadDef(data); } }); regressionMenu.getItems().add(menu); menu = new MenuItem(message(lang, "DiabetesPredictionStandardized")); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = DiabetesPredictionStandardized(lang); if (makeExampleFile("DataAnalyse_DiabetesPrediction_standardized", data)) { controller.loadDef(data); } }); regressionMenu.getItems().add(menu); menu = new MenuItem(message(lang, "HeartFailure")); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = HeartFailure(lang); if (makeExampleFile("DataAnalyse_HeartFailure", data)) { controller.loadDef(data); } }); regressionMenu.getItems().add(menu); menu = new MenuItem(message(lang, "ConcreteCompressiveStrength")); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = ConcreteCompressiveStrength(lang); if (makeExampleFile("DataAnalyse_ConcreteCompressiveStrength", data)) { controller.loadDef(data); } }); regressionMenu.getItems().add(menu); menu = new MenuItem(message(lang, "DogRadiographsDataset")); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = DogRadiographsDataset(lang); if (makeExampleFile("DataAnalyse_DogRadiographs", data)) { controller.loadDef(data); } }); regressionMenu.getItems().add(menu); menu = new MenuItem(message(lang, "BaseballSalaries")); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = BaseballSalaries(lang); if (makeExampleFile("DataAnalyse_BaseballSalaries", data)) { controller.loadDef(data); } }); regressionMenu.getItems().add(menu); menu = new MenuItem(message(lang, "SouthGermanCredit")); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = SouthGermanCredit(lang); if (makeExampleFile("DataAnalyse_SouthGermanCredit", data)) { controller.loadDef(data); } }); regressionMenu.getItems().add(menu); menu = new MenuItem(message(lang, "BostonHousingPrices")); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = BostonHousingPrices(lang); if (makeExampleFile("DataAnalyse_BostonHousingPrices", data)) { controller.loadDef(data); } }); regressionMenu.getItems().add(menu); regressionMenu.getItems().add(new SeparatorMenuItem()); menu = new MenuItem(message(lang, "AboutDataAnalysis")); menu.setStyle(linkStyle()); menu.setOnAction((ActionEvent event) -> { controller.openHtml(HelpTools.aboutDataAnalysis()); }); regressionMenu.getItems().add(menu); return regressionMenu; } catch (Exception e) { MyBoxLog.error(e); return null; } } /* exmaples of data 2D definition */ public static DataFileCSV IncomeHappiness(String lang) { boolean isChinese = Languages.isChinese(lang); DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(isChinese ? "收入" : "income", ColumnDefinition.ColumnType.Double, true)); columns.add(new Data2DColumn(isChinese ? "快乐" : "happiness", ColumnDefinition.ColumnType.Double, true)); data.setColumns(columns).setDataName(message(lang, "IncomeHappiness")) .setComments("https://www.scribbr.com/statistics/simple-linear-regression/"); return data; } public static DataFileCSV ExperienceSalary(String lang) { boolean isChinese = Languages.isChinese(lang); DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(isChinese ? "工作经验" : "YearsExperience", ColumnDefinition.ColumnType.Double, true)); columns.add(new Data2DColumn(isChinese ? "薪资" : "Salary", ColumnDefinition.ColumnType.Double, true)); data.setColumns(columns).setDataName(message(lang, "ExperienceSalary")) .setComments("https://github.com/krishnaik06/simple-Linear-Regression"); return data; } public static DataFileCSV IrisSpecies(String lang) { boolean isChinese = Languages.isChinese(lang); DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(isChinese ? "花萼长度(cm)" : "SepalLengthCm", ColumnDefinition.ColumnType.Double, true)); columns.add(new Data2DColumn(isChinese ? "花萼宽度(cm)" : "SepalWidthCm", ColumnDefinition.ColumnType.Double, true)); columns.add(new Data2DColumn(isChinese ? "花瓣长度(cm)" : "PetalLengthCm", ColumnDefinition.ColumnType.Double, true)); columns.add(new Data2DColumn(isChinese ? "花瓣宽度(cm)" : "PetalWidthCm", ColumnDefinition.ColumnType.Double, true)); columns.add(new Data2DColumn(isChinese ? "种类" : "Species", ColumnDefinition.ColumnType.String, true)); data.setColumns(columns).setDataName(message(lang, "IrisSpecies")) .setComments("http://archive.ics.uci.edu/ml/datasets/Iris"); return data; } public static DataFileCSV DiabetesPrediction(String lang) { boolean isChinese = Languages.isChinese(lang); DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(isChinese ? "年龄" : "age", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "性别" : "sex", ColumnDefinition.ColumnType.Short)); columns.add(new Data2DColumn(isChinese ? "BMI(体质指数)" : "BMI(body mass index)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "BP(平均血压)" : "BP(average blood pressure)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "S1(血清指标1)" : "S1(blood serum measurement 1)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "S2(血清指标2)" : "S2(blood serum measurement 2)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "S3(血清指标3)" : "S3(blood serum measurement 3)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "S4(血清指标4)" : "S4(blood serum measurement 4)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "S5(血清指标5)" : "S5(blood serum measurement 5)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "S6(血清指标6)" : "S6(blood serum measurement 6)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "一年后病情进展" : "disease progression one year after baseline", ColumnDefinition.ColumnType.Double)); data.setColumns(columns).setDataName(message(lang, "DiabetesPrediction")) .setComments("https://hastie.su.domains/Papers/LARS/"); return data; } public static DataFileCSV DiabetesPredictionStandardized(String lang) { boolean isChinese = Languages.isChinese(lang); DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(isChinese ? "年龄" : "age", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "性别" : "sex", ColumnDefinition.ColumnType.Short)); columns.add(new Data2DColumn(isChinese ? "BMI(体质指数)" : "BMI(body mass index)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "BP(平均血压)" : "BP(average blood pressure)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "S1(血清指标1)" : "S1(blood serum measurement 1)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "S2(血清指标2)" : "S2(blood serum measurement 2)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "S3(血清指标3)" : "S3(blood serum measurement 3)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "S4(血清指标4)" : "S4(blood serum measurement 4)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "S5(血清指标5)" : "S5(blood serum measurement 5)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "S6(血清指标6)" : "S6(blood serum measurement 6)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "一年后病情进展" : "disease progression one year after baseline", ColumnDefinition.ColumnType.Double)); data.setColumns(columns).setDataName(message(lang, "DiabetesPredictionStandardized")) .setComments("https://hastie.su.domains/Papers/LARS/ \n" + "first 10 columns have been normalized to have mean 0 and " + "Euclidean norm 1 and the last column y has been centered (mean 0)."); return data; } public static DataFileCSV HeartFailure(String lang) { boolean isChinese = Languages.isChinese(lang); DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(isChinese ? "年龄" : "age", ColumnDefinition.ColumnType.Integer)); columns.add(new Data2DColumn(isChinese ? "贫血" : "anaemia", ColumnDefinition.ColumnType.Boolean) .setDescription("decrease of red blood cells or hemoglobin (boolean)")); columns.add(new Data2DColumn(isChinese ? "肌酐磷酸激酶(CPK_mcg/L)" : "creatinine_phosphokinase(CPK_mcg/L)", ColumnDefinition.ColumnType.Integer)); columns.add(new Data2DColumn(isChinese ? "糖尿病" : "diabetes", ColumnDefinition.ColumnType.Boolean)); columns.add(new Data2DColumn(isChinese ? "喷血分数" : "ejection fraction", ColumnDefinition.ColumnType.Integer) .setDescription("percentage of blood leaving the heart at each contraction (percentage)")); columns.add(new Data2DColumn(isChinese ? "高血压" : "high blood pressure", ColumnDefinition.ColumnType.Boolean)); columns.add(new Data2DColumn(isChinese ? "血小板(kiloplatelets/mL)" : "platelets(kiloplatelets/mL)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "血清肌酸酐(mg/dL)" : "serum creatinine(mg/dL)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "血清钠(mEq/L)" : "serum sodium(mEq/L)", ColumnDefinition.ColumnType.Integer)); columns.add(new Data2DColumn(isChinese ? "性别" : "sex", ColumnDefinition.ColumnType.Boolean)); columns.add(new Data2DColumn(isChinese ? "抽烟" : "smoking", ColumnDefinition.ColumnType.Boolean)); columns.add(new Data2DColumn(isChinese ? "观察期" : "follow-up period(days)", ColumnDefinition.ColumnType.Short)); columns.add(new Data2DColumn(isChinese ? "死亡" : "death event", ColumnDefinition.ColumnType.Boolean)); data.setColumns(columns).setDataName(message(lang, "HeartFailure")) .setComments("http://archive.ics.uci.edu/ml/datasets/Heart+failure+clinical+records \n" + "Davide Chicco, Giuseppe Jurman: \"Machine learning can predict survival of patients with heart failure " + "from serum creatinine and ejection fraction alone\". BMC Medical Informatics and Decision Making 20, 16 (2020)"); return data; } public static DataFileCSV ConcreteCompressiveStrength(String lang) { boolean isChinese = Languages.isChinese(lang); DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(isChinese ? "水泥(公斤)" : "Cement(kg)", ColumnDefinition.ColumnType.Short)); columns.add(new Data2DColumn(isChinese ? "矿渣(公斤)" : "Blast Furnace Slag(kg)", ColumnDefinition.ColumnType.Short)); columns.add(new Data2DColumn(isChinese ? "煤灰(公斤)" : "Fly Ash(kg)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "水(公斤)" : "Water(kg)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "塑化剂(公斤)" : "Superplasticizer(kg)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "粗颗粒(公斤)" : "Coarse Aggregate(kg)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "细颗料(公斤)" : "Fine Aggregate(kg)", ColumnDefinition.ColumnType.Short)); columns.add(new Data2DColumn(isChinese ? "已使用天数" : "Age(days)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "1立方米混凝土抗压强度(兆帕)" : "Concrete compressive strength(MPa)", ColumnDefinition.ColumnType.Double)); data.setColumns(columns).setDataName(message(lang, "ConcreteCompressiveStrength")) .setComments("http://archive.ics.uci.edu/ml/datasets/Concrete+Compressive+Strength \n" + "https://zhuanlan.zhihu.com/p/168747748"); return data; } public static DataFileCSV DogRadiographsDataset(String lang) { boolean isChinese = Languages.isChinese(lang); DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(isChinese ? "透亮度有改变" : "lucency changed", ColumnDefinition.ColumnType.Boolean) .setDescription("changed(1) or not changed(0)")); columns.add(new Data2DColumn(isChinese ? "刀片尺寸" : "blade size", ColumnDefinition.ColumnType.Short)); columns.add(new Data2DColumn(isChinese ? "胫骨结节面积" : "tibial tuberosity area", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "胫骨结节宽度" : "tibial tuberosity width", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "年龄(年)" : "age in years", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "重量(公斤)" : "weight in kilograms", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "抗滚针的位置" : "location of the anti-rotational pin", ColumnDefinition.ColumnType.Boolean)); columns.add(new Data2DColumn(isChinese ? "双侧手术" : "bilateral surgery", ColumnDefinition.ColumnType.Boolean) .setDescription("bilateral surgery(1) or unilateral surgery(0)")); data.setColumns(columns).setDataName(message(lang, "DogRadiographsDataset")) .setComments("https://www4.stat.ncsu.edu/~boos/var.select/lucency.html \n" + "Radiographic and Clinical Changes of the Tibial Tuberosity after Tibial Plateau Leveling Osteomtomy."); return data; } public static DataFileCSV BaseballSalaries(String lang) { boolean isChinese = Languages.isChinese(lang); DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(isChinese ? "薪水(千美元)" : "Salary (thousands of dollars)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "击球平均得分数" : "Batting average", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "上垒率" : "On-base percentage", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "跑动数" : "Number of runs", ColumnDefinition.ColumnType.Short)); columns.add(new Data2DColumn(isChinese ? "击球数" : "Number of hits", ColumnDefinition.ColumnType.Short)); columns.add(new Data2DColumn(isChinese ? "二垒数" : "Number of doubles", ColumnDefinition.ColumnType.Short)); columns.add(new Data2DColumn(isChinese ? "三垒数" : "Number of triples", ColumnDefinition.ColumnType.Short)); columns.add(new Data2DColumn(isChinese ? "全垒数" : "Number of home runs", ColumnDefinition.ColumnType.Short)); columns.add(new Data2DColumn(isChinese ? "打点数" : "Number of runs batted in", ColumnDefinition.ColumnType.Short)); columns.add(new Data2DColumn(isChinese ? "走动数" : "Number of walks", ColumnDefinition.ColumnType.Short)); columns.add(new Data2DColumn(isChinese ? "三振出局数" : "Number of strike-outs", ColumnDefinition.ColumnType.Short)); columns.add(new Data2DColumn(isChinese ? "盗垒数" : "Number of stolen bases", ColumnDefinition.ColumnType.Short)); columns.add(new Data2DColumn(isChinese ? "失误数" : "Number of errors", ColumnDefinition.ColumnType.Short)); columns.add(new Data2DColumn(isChinese ? "自由球员资格" : "free agency eligibility", ColumnDefinition.ColumnType.Boolean)); columns.add(new Data2DColumn(isChinese ? "1991/2的自由球员" : "free agent in 1991/2", ColumnDefinition.ColumnType.Boolean)); columns.add(new Data2DColumn(isChinese ? "仲裁资格" : "arbitration eligibility", ColumnDefinition.ColumnType.Boolean)); columns.add(new Data2DColumn(isChinese ? "于1991/2仲裁" : "arbitration in 1991/2", ColumnDefinition.ColumnType.Boolean)); data.setColumns(columns).setDataName(message(lang, "BaseballSalaries")) .setComments("https://www4.stat.ncsu.edu/~boos/var.select/baseball.html \n" + "Salary information for 337 Major League Baseball (MLB) players who are not pitchers " + "and played at least one game during both the 1991 and 1992 seasons."); return data; } public static DataFileCSV SouthGermanCredit(String lang) { boolean isChinese = Languages.isChinese(lang); DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(isChinese ? "状态" : "status", ColumnDefinition.ColumnType.Short) .setDescription("status of the debtor's checking account with the bank\n" + "1:no checking account \n" + "2: ... < 0 DM \n" + "3: 0<= ... < 200 DM \n" + "4: >= 200 DM \n" + "salary for at least 1 year")); columns.add(new Data2DColumn(isChinese ? "持续时间(月)" : "duration(months)", ColumnDefinition.ColumnType.Short) .setDescription("credit duration in months")); columns.add(new Data2DColumn(isChinese ? "信用卡历史" : "credit_history", ColumnDefinition.ColumnType.Short) .setDescription("history of compliance with previous or concurrent credit contracts\n" + " 0 : delay in paying off in the past \n" + " 1 : critical account/other credits elsewhere \n" + " 2 : no credits taken/all credits paid back duly\n" + " 3 : existing credits paid back duly till now \n" + " 4 : all credits at this bank paid back duly ")); columns.add(new Data2DColumn(isChinese ? "用途" : "purpose", ColumnDefinition.ColumnType.Short) .setDescription("purpose for which the credit is needed\n" + " 0 : others \n" + " 1 : car (new) \n" + " 2 : car (used) \n" + " 3 : furniture/equipment\n" + " 4 : radio/television \n" + " 5 : domestic appliances\n" + " 6 : repairs \n" + " 7 : education \n" + " 8 : vacation \n" + " 9 : retraining \n" + " 10 : business ")); columns.add(new Data2DColumn(isChinese ? "金额" : "amount", ColumnDefinition.ColumnType.Short) .setDescription("credit amount in DM (quantitative; result of monotonic transformation; " + "actual data and type of transformation unknown)")); columns.add(new Data2DColumn(isChinese ? "储蓄" : "savings", ColumnDefinition.ColumnType.Short) .setDescription("debtor's savings\n" + " 1 : unknown/no savings account\n" + " 2 : ... < 100 DM \n" + " 3 : 100 <= ... < 500 DM \n" + " 4 : 500 <= ... < 1000 DM \n" + " 5 : ... >= 1000 DM ")); columns.add(new Data2DColumn(isChinese ? "职业年限" : "employment_duration", ColumnDefinition.ColumnType.Short) .setDescription("duration of debtor's employment with current employer\n" + " 1 : unemployed \n" + " 2 : < 1 yr \n" + " 3 : 1 <= ... < 4 yrs\n" + " 4 : 4 <= ... < 7 yrs\n" + " 5 : >= 7 yrs ")); columns.add(new Data2DColumn(isChinese ? "信贷率" : "installment_rate", ColumnDefinition.ColumnType.Short) .setDescription("credit installments as a percentage of debtor's disposable income\n" + "1 : >= 35 \n" + " 2 : 25 <= ... < 35\n" + " 3 : 20 <= ... < 25\n" + " 4 : < 20 ")); columns.add(new Data2DColumn(isChinese ? "个人状态" : "personal_status_sex", ColumnDefinition.ColumnType.Short) .setDescription("combined information on sex and marital status\n" + " 1 : male : divorced/separated \n" + " 2 : female : non-single or male : single\n" + " 3 : male : married/widowed \n" + " 4 : female : single ")); columns.add(new Data2DColumn(isChinese ? "其他债务人" : "other_debtors", ColumnDefinition.ColumnType.Short) .setDescription("Is there another debtor or a guarantor for the credit\n" + " 1 : none \n" + " 2 : co-applicant\n" + " 3 : guarantor ")); columns.add(new Data2DColumn(isChinese ? "当前居住年限(年)" : "present_residence", ColumnDefinition.ColumnType.Short) .setDescription("length of time (in years) the debtor lives in the present residence\n" + " 1 : < 1 yr \n" + " 2 : 1 <= ... < 4 yrs\n" + " 3 : 4 <= ... < 7 yrs\n" + " 4 : >= 7 yrs ")); columns.add(new Data2DColumn(isChinese ? "财产" : "property", ColumnDefinition.ColumnType.Short) .setDescription("the debtor's most valuable property\n" + " 1 : unknown / no property \n" + " 2 : car or other \n" + " 3 : building soc. savings agr./life insurance\n" + " 4 : real estate ")); columns.add(new Data2DColumn(isChinese ? "年龄" : "age", ColumnDefinition.ColumnType.Short)); columns.add(new Data2DColumn(isChinese ? "其它贷款计划" : "other_installment_plans", ColumnDefinition.ColumnType.Short) .setDescription("installment plans from providers other than the credit-giving bank\n" + " 1 : bank \n" + " 2 : stores\n" + " 3 : none")); columns.add(new Data2DColumn(isChinese ? "居所类型" : "housing", ColumnDefinition.ColumnType.Short) .setDescription("type of housing the debtor lives in\n" + " 1 : for free\n" + " 2 : rent \n" + " 3 : own ")); columns.add(new Data2DColumn(isChinese ? "信用卡数目" : "number_credits", ColumnDefinition.ColumnType.Short) .setDescription("number of credits including the current one the debtor has (or had) at this bank\n" + " 1 : 1 \n" + " 2 : 2-3 \n" + " 3 : 4-5 \n" + " 4 : >= 6")); columns.add(new Data2DColumn(isChinese ? "工作类型" : "job", ColumnDefinition.ColumnType.Short) .setDescription(" 1 : unemployed/unskilled - non-resident \n" + " 2 : unskilled - resident \n" + " 3 : skilled employee/official \n" + " 4 : manager/self-empl./highly qualif. employee")); columns.add(new Data2DColumn(isChinese ? "被依赖人数" : "people_liable", ColumnDefinition.ColumnType.Short) .setDescription("number of persons who financially depend on the debtor\n" + " 1 : 3 or more\n" + " 2 : 0 to 2")); columns.add(new Data2DColumn(isChinese ? "有电话" : "telephone", ColumnDefinition.ColumnType.Short) .setDescription("Is there a telephone landline registered on the debtor's name? " + "(binary; remember that the data are from the 1970s)\n" + " 1 : no \n" + " 2 : yes (under customer name)")); columns.add(new Data2DColumn(isChinese ? "是外籍雇员" : "foreign_worker", ColumnDefinition.ColumnType.Short) .setDescription("Is the debtor a foreign worker\n" + " 1 : yes\n" + " 2 : no ")); columns.add(new Data2DColumn(isChinese ? "信用风险" : "credit_risk", ColumnDefinition.ColumnType.Short) .setDescription("Has the credit contract been complied with (good) or not (bad) ?\n" + " 0 : bad \n" + " 1 : good")); data.setColumns(columns).setDataName(message(lang, "SouthGermanCredit")) .setComments("http://archive.ics.uci.edu/ml/datasets/South+German+Credit\n" + "700 good and 300 bad credits with 20 predictor variables. Data from 1973 to 1975. " + "Stratified sample from actual credits with bad credits heavily oversampled. A cost matrix can be used."); return data; } public static DataFileCSV BostonHousingPrices(String lang) { boolean isChinese = Languages.isChinese(lang); DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(isChinese ? "镇" : "town", ColumnDefinition.ColumnType.String, true)); columns.add(new Data2DColumn(isChinese ? "经度" : "longitude", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "纬度" : "latitude", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "犯罪率" : "crime_ratio", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "超过25000平米的区" : "zoned_bigger_25000", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "工业用地" : "industrial_land", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "靠近查理斯河" : "near_Charies_River", ColumnDefinition.ColumnType.Boolean)); columns.add(new Data2DColumn(isChinese ? "一氧化氮浓度" : "nitrogen_density", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "平均房间数" : "average_room_number", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "早于1940建成比率" : "built_before_1940_ratio", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "到达市中心的距离" : "distance_to_centre", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "公路可达性" : "accessbility_to_hightway", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "税率" : "tax_rate", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "学生教师比" : "pupil_teacher_ratio", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "低收入比" : "lower_class_ratio", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "价格中位数" : "median_price", ColumnDefinition.ColumnType.Double)); data.setColumns(columns).setDataName(message(lang, "BostonHousingPrices")) .setComments("https://github.com/tomsharp/SVR/tree/master/data"); return data; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data2d/example/Data2DExampleTools.java
released/MyBox/src/main/java/mara/mybox/data2d/example/Data2DExampleTools.java
package mara.mybox.data2d.example; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.control.CheckMenuItem; import javafx.scene.control.MenuItem; import javafx.scene.control.SeparatorMenuItem; import mara.mybox.controller.BaseData2DLoadController; import mara.mybox.data2d.DataFileCSV; import mara.mybox.data2d.DataFileText; import mara.mybox.db.data.Data2DColumn; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxFileTools; import mara.mybox.fxml.style.StyleTools; import mara.mybox.tools.FileDeleteTools; import mara.mybox.value.Languages; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2022-9-15 * @License Apache License Version 2.0 */ public class Data2DExampleTools { public static List<MenuItem> examplesMenu(BaseData2DLoadController controller) { return examplesMenu(controller, Languages.embedFileLang()); } public static List<MenuItem> examplesMenu(BaseData2DLoadController controller, String lang) { try { List<MenuItem> items = new ArrayList<>(); items.add(MyData.menu(lang, controller)); items.add(StatisticDataOfChina.menu(lang, controller)); items.add(Regression.menu(lang, controller)); items.add(Location.menu(lang, controller)); items.add(ChineseCharacters.menu(lang, controller)); items.add(Matrix.menu(lang, controller)); items.add(ProjectManagement.menu(lang, controller)); items.add(SoftwareTesting.menu(lang, controller)); items.add(new SeparatorMenuItem()); CheckMenuItem onlyMenu = new CheckMenuItem(message(lang, "ImportDefinitionOnly"), StyleTools.getIconImageView("iconHeader.png")); onlyMenu.setSelected(UserConfig.getBoolean("Data2DExampleImportDefinitionOnly", false)); onlyMenu.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { UserConfig.setBoolean("Data2DExampleImportDefinitionOnly", onlyMenu.isSelected()); } }); items.add(onlyMenu); return items; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static boolean makeExampleFile(String fileName, DataFileCSV targetData) { try { if (fileName == null || targetData == null) { return false; } File srcFile = FxFileTools.getInternalFile("/data/examples/" + fileName + ".csv"); File targetFile = targetData.tmpFile(fileName, "example", "csv"); if (targetFile.exists()) { targetFile.delete(); } Charset charset = Charset.forName("utf-8"); try (BufferedReader reader = new BufferedReader(new FileReader(srcFile, charset)); BufferedWriter writer = new BufferedWriter(new FileWriter(targetFile, charset, false))) { String line = null; while ((line = reader.readLine()) != null && line.startsWith(DataFileText.CommentsMarker)) { writer.write(line + System.lineSeparator()); } if (line != null) { List<Data2DColumn> columns = targetData.getColumns(); if (columns != null) { String header = null; for (Data2DColumn column : columns) { String name = "\"" + column.getColumnName() + "\""; if (header == null) { header = name; } else { header += "," + name; } } writer.write(header + System.lineSeparator()); } else { writer.write(line + System.lineSeparator()); } if (!UserConfig.getBoolean("Data2DExampleImportDefinitionOnly", false)) { while ((line = reader.readLine()) != null) { writer.write(line + System.lineSeparator()); } } } writer.flush(); } catch (Exception e) { MyBoxLog.error(e); return false; } targetData.setFile(targetFile).setHasHeader(true).setCharset(charset).setDelimiter(","); targetData.saveAttributes(); FileDeleteTools.delete(srcFile); return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data2d/example/Location.java
released/MyBox/src/main/java/mara/mybox/data2d/example/Location.java
package mara.mybox.data2d.example; import java.util.ArrayList; import java.util.List; import javafx.event.ActionEvent; import javafx.scene.control.Menu; import javafx.scene.control.MenuItem; import mara.mybox.controller.BaseData2DLoadController; import mara.mybox.data2d.DataFileCSV; import static mara.mybox.data2d.example.Data2DExampleTools.makeExampleFile; import mara.mybox.db.data.ColumnDefinition; import mara.mybox.db.data.Data2DColumn; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.style.StyleTools; import mara.mybox.value.Languages; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2022-9-15 * @License Apache License Version 2.0 */ public class Location { public static Menu menu(String lang, BaseData2DLoadController controller) { try { Menu locationMenu = new Menu(message(lang, "LocationData"), StyleTools.getIconImageView("iconLocation.png")); MenuItem menu = new MenuItem(message(lang, "ChineseHistoricalCapitals")); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = ChineseHistoricalCapitals(lang); if (makeExampleFile("Location_ChineseHistoricalCapitals_" + lang, data)) { controller.loadDef(data); } }); locationMenu.getItems().add(menu); menu = new MenuItem(message(lang, "AutumnMovementPatternsOfEuropeanGadwalls")); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = AutumnMovementPatternsOfEuropeanGadwalls(lang); if (makeExampleFile("Location_EuropeanGadwalls", data)) { controller.loadDef(data); } }); locationMenu.getItems().add(menu); menu = new MenuItem(message(lang, "SpermWhalesGulfOfMexico")); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = SpermWhalesGulfOfMexico(lang); if (makeExampleFile("Location_SpermWhales", data)) { controller.loadDef(data); } }); locationMenu.getItems().add(menu); menu = new MenuItem(message(lang, "EpidemicReportsCOVID19")); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = EpidemicReportsCOVID19(lang); if (makeExampleFile("Location_EpidemicReports", data)) { controller.loadDef(data); } }); locationMenu.getItems().add(menu); return locationMenu; } catch (Exception e) { MyBoxLog.error(e); return null; } } /* exmaples of data 2D definition */ public static DataFileCSV ChineseHistoricalCapitals(String lang) { boolean isChinese = Languages.isChinese(lang); DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(message(lang, "Country"), ColumnDefinition.ColumnType.String, true).setWidth(140)); columns.add(new Data2DColumn(message(lang, "Capital"), ColumnDefinition.ColumnType.String, true).setWidth(200)); columns.add(new Data2DColumn(message(lang, "Longitude"), ColumnDefinition.ColumnType.Longitude)); columns.add(new Data2DColumn(message(lang, "Latitude"), ColumnDefinition.ColumnType.Latitude)); columns.add(new Data2DColumn(message(lang, "StartTime"), ColumnDefinition.ColumnType.Era).setFormat(isChinese ? "Gy" : "y G")); columns.add(new Data2DColumn(message(lang, "EndTime"), ColumnDefinition.ColumnType.Era).setFormat(isChinese ? "Gy" : "y G")); columns.add(new Data2DColumn(message(lang, "Comments"), ColumnDefinition.ColumnType.String)); data.setColumns(columns).setDataName(message(lang, "ChineseHistoricalCapitals")); return data; } public static DataFileCSV AutumnMovementPatternsOfEuropeanGadwalls(String lang) { DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(message(lang, "StartTime"), ColumnDefinition.ColumnType.Datetime, 180).setFixTwoDigitYear(true)); columns.add(new Data2DColumn(message(lang, "EndTime"), ColumnDefinition.ColumnType.Datetime, 180).setFixTwoDigitYear(true)); columns.add(new Data2DColumn(message(lang, "Longitude"), ColumnDefinition.ColumnType.Longitude)); columns.add(new Data2DColumn(message(lang, "Latitude"), ColumnDefinition.ColumnType.Latitude)); columns.add(new Data2DColumn(message(lang, "CoordinateSystem"), ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(message(lang, "Comments"), ColumnDefinition.ColumnType.String)); data.setColumns(columns).setDataName(message(lang, "AutumnMovementPatternsOfEuropeanGadwalls")) .setComments("https://www.datarepository.movebank.org/handle/10255/move.346"); return data; } public static DataFileCSV SpermWhalesGulfOfMexico(String lang) { DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(message(lang, "Time"), ColumnDefinition.ColumnType.Datetime, 180).setFixTwoDigitYear(true)); columns.add(new Data2DColumn(message(lang, "Longitude"), ColumnDefinition.ColumnType.Longitude)); columns.add(new Data2DColumn(message(lang, "Latitude"), ColumnDefinition.ColumnType.Latitude)); columns.add(new Data2DColumn(message(lang, "CoordinateSystem"), ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(message(lang, "Comments"), ColumnDefinition.ColumnType.String)); data.setColumns(columns).setDataName(message(lang, "SpermWhalesGulfOfMexico")) .setComments("https://www.datarepository.movebank.org/handle/10255/move.1059"); return data; } public static DataFileCSV EpidemicReportsCOVID19(String lang) { DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(message(lang, "Date"), ColumnDefinition.ColumnType.Date) .setFixTwoDigitYear(false).setFormat("yyyy-MM-dd")); columns.add(new Data2DColumn(message(lang, "Country"), ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(message(lang, "Province"), ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(message(lang, "Confirmed"), ColumnDefinition.ColumnType.Integer)); columns.add(new Data2DColumn(message(lang, "Healed"), ColumnDefinition.ColumnType.Integer)); columns.add(new Data2DColumn(message(lang, "Dead"), ColumnDefinition.ColumnType.Integer)); columns.add(new Data2DColumn(message(lang, "Longitude"), ColumnDefinition.ColumnType.Longitude)); columns.add(new Data2DColumn(message(lang, "Latitude"), ColumnDefinition.ColumnType.Latitude)); data.setColumns(columns).setDataName(message(lang, "EpidemicReportsCOVID19")) .setComments("https://github.com/CSSEGISandData/COVID-19"); return data; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data2d/example/MyData.java
released/MyBox/src/main/java/mara/mybox/data2d/example/MyData.java
package mara.mybox.data2d.example; import java.util.ArrayList; import java.util.List; import javafx.event.ActionEvent; import javafx.scene.control.Menu; import javafx.scene.control.MenuItem; import javafx.scene.control.SeparatorMenuItem; import mara.mybox.controller.BaseData2DLoadController; import mara.mybox.data2d.DataFileCSV; import static mara.mybox.data2d.example.Data2DExampleTools.makeExampleFile; import mara.mybox.db.data.ColumnDefinition; import mara.mybox.db.data.Data2DColumn; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.style.StyleTools; import mara.mybox.value.Languages; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2022-9-15 * @License Apache License Version 2.0 */ public class MyData { public static Menu menu(String lang, BaseData2DLoadController controller) { try { Menu myMenu = new Menu(message(lang, "MyData"), StyleTools.getIconImageView("iconCat.png")); MenuItem menu = new MenuItem(message(lang, "Notes")); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = Notes(lang); if (makeExampleFile("MyData_notes_" + lang, data)) { controller.loadDef(data); } }); myMenu.getItems().add(menu); menu = new MenuItem(message(lang, "Contacts")); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = Contacts(lang); if (makeExampleFile("MyData_contacts_" + lang, data)) { controller.loadDef(data); } }); myMenu.getItems().add(menu); menu = new MenuItem(message(lang, "CashFlow")); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = CashFlow(lang); if (makeExampleFile("MyData_cashflow_" + lang, data)) { controller.loadDef(data); } }); myMenu.getItems().add(menu); menu = new MenuItem(message(lang, "PrivateProperty")); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = PrivateProperty(lang); if (makeExampleFile("MyData_property_" + lang, data)) { controller.loadDef(data); } }); myMenu.getItems().add(menu); myMenu.getItems().add(new SeparatorMenuItem()); menu = new MenuItem(message(lang, "Eyesight")); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = Eyesight(lang); if (makeExampleFile("MyData_eyesight", data)) { controller.loadDef(data); } }); myMenu.getItems().add(menu); menu = new MenuItem(message(lang, "Weight")); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = Weight(lang); if (makeExampleFile("MyData_weight", data)) { controller.loadDef(data); } }); myMenu.getItems().add(menu); menu = new MenuItem(message(lang, "Height")); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = Height(lang); if (makeExampleFile("MyData_height", data)) { controller.loadDef(data); } }); myMenu.getItems().add(menu); menu = new MenuItem(message(lang, "Menstruation")); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = Menstruation(lang); if (makeExampleFile("MyData_menstruation", data)) { controller.loadDef(data); } }); myMenu.getItems().add(menu); return myMenu; } catch (Exception e) { MyBoxLog.error(e); return null; } } /* exmaples of data 2D definition */ public static DataFileCSV Notes(String lang) { DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(message(lang, "Time"), ColumnDefinition.ColumnType.Datetime, 180)); columns.add(new Data2DColumn(message(lang, "Title"), ColumnDefinition.ColumnType.String, 180)); columns.add(new Data2DColumn(message(lang, "InvolvedObjects"), ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(message(lang, "Location"), ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(message(lang, "Comments"), ColumnDefinition.ColumnType.String, 300)); data.setColumns(columns).setDataName(message(lang, "Notes")); return data; } public static DataFileCSV Contacts(String lang) { DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(message(lang, "Name"), ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(message(lang, "Relationship"), ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(message(lang, "PhoneNumber") + "1", ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(message(lang, "PhoneNumber") + "2", ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(message(lang, "Email"), ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(message(lang, "Address"), ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(message(lang, "Birthday"), ColumnDefinition.ColumnType.Datetime)); columns.add(new Data2DColumn(message(lang, "Hobbies"), ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(message(lang, "Comments"), ColumnDefinition.ColumnType.String, 300)); data.setColumns(columns).setDataName(message(lang, "Contacts")); return data; } public static DataFileCSV CashFlow(String lang) { DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(message(lang, "Time"), ColumnDefinition.ColumnType.Datetime, 180)); columns.add(new Data2DColumn(message(lang, "Amount"), ColumnDefinition.ColumnType.Float)); columns.add(new Data2DColumn(message(lang, "Type"), ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(message(lang, "Account"), ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(message(lang, "InvolvedObjects"), ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(message(lang, "Comments"), ColumnDefinition.ColumnType.String, 300)); data.setColumns(columns).setDataName(message(lang, "CashFlow")); return data; } public static DataFileCSV PrivateProperty(String lang) { DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(message(lang, "Time"), ColumnDefinition.ColumnType.Datetime, 180)); columns.add(new Data2DColumn(message(lang, "Amount"), ColumnDefinition.ColumnType.Float)); columns.add(new Data2DColumn(message(lang, "Type"), ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(message(lang, "Account"), ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(message(lang, "Comments"), ColumnDefinition.ColumnType.String, 300)); data.setColumns(columns).setDataName(message(lang, "PrivateProperty")); return data; } public static DataFileCSV Eyesight(String lang) { boolean isChinese = Languages.isChinese(lang); DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(message(lang, "Time"), ColumnDefinition.ColumnType.Datetime, true, true).setWidth(180)); columns.add(new Data2DColumn(isChinese ? "左眼" : "left eye", ColumnDefinition.ColumnType.Short)); columns.add(new Data2DColumn(isChinese ? "右眼" : "right eye", ColumnDefinition.ColumnType.Short)); columns.add(new Data2DColumn(isChinese ? "基弧" : "Radian", ColumnDefinition.ColumnType.Short)); columns.add(new Data2DColumn(message(lang, "Comments"), ColumnDefinition.ColumnType.String, 300)); data.setColumns(columns).setDataName(message(lang, "Eyesight")); return data; } public static DataFileCSV Weight(String lang) { DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(message(lang, "Time"), ColumnDefinition.ColumnType.Datetime, true, true).setWidth(180)); columns.add(new Data2DColumn(message(lang, "Weight") + "(kg)", ColumnDefinition.ColumnType.Float).setScale(2)); columns.add(new Data2DColumn(message(lang, "Comments"), ColumnDefinition.ColumnType.String, 300)); data.setColumns(columns).setDataName(message(lang, "Weight")); return data; } public static DataFileCSV Height(String lang) { DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(message(lang, "Time"), ColumnDefinition.ColumnType.Datetime, true, true).setWidth(180)); columns.add(new Data2DColumn(message(lang, "Height") + "(cm)", ColumnDefinition.ColumnType.Float).setScale(2)); columns.add(new Data2DColumn(message(lang, "Comments"), ColumnDefinition.ColumnType.String, 300)); data.setColumns(columns).setDataName(message(lang, "Height")); return data; } public static DataFileCSV Menstruation(String lang) { boolean isChinese = Languages.isChinese(lang); DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(message(lang, "StartTime"), ColumnDefinition.ColumnType.Datetime, true).setWidth(180)); columns.add(new Data2DColumn(message(lang, "EndTime"), ColumnDefinition.ColumnType.Datetime, true).setWidth(180)); columns.add(new Data2DColumn(isChinese ? "疼痛" : "Pain", ColumnDefinition.ColumnType.Short)); columns.add(new Data2DColumn(isChinese ? "卫生巾" : "Pads", ColumnDefinition.ColumnType.Short)); columns.add(new Data2DColumn(message(lang, "Comments"), ColumnDefinition.ColumnType.String, 300)); data.setColumns(columns).setDataName(message(lang, "Menstruation")); return data; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data2d/example/ChineseCharacters.java
released/MyBox/src/main/java/mara/mybox/data2d/example/ChineseCharacters.java
package mara.mybox.data2d.example; import java.util.ArrayList; import java.util.List; import javafx.event.ActionEvent; import javafx.scene.control.Menu; import javafx.scene.control.MenuItem; import javafx.scene.control.SeparatorMenuItem; import mara.mybox.controller.BaseData2DLoadController; import mara.mybox.data2d.DataFileCSV; import static mara.mybox.data2d.example.Data2DExampleTools.makeExampleFile; import mara.mybox.db.data.ColumnDefinition; import mara.mybox.db.data.Data2DColumn; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.style.StyleTools; import mara.mybox.value.Languages; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2022-9-15 * @License Apache License Version 2.0 */ public class ChineseCharacters { public static Menu menu(String lang, BaseData2DLoadController controller) { try { Menu dictionariesMenu = new Menu(message(lang, "ChineseCharacters"), StyleTools.getIconImageView("iconWu.png")); MenuItem menu = new MenuItem(message(lang, "ChineseCharactersStandard")); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = ChineseCharactersStandard(lang); if (makeExampleFile("ChineseCharactersStandard", data)) { controller.loadDef(data); } }); dictionariesMenu.getItems().add(menu); menu = new MenuItem(message(lang, "ChineseRadicals")); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = ChineseRadicals(lang); if (makeExampleFile("ChineseRadicals", data)) { controller.loadDef(data); } }); dictionariesMenu.getItems().add(menu); menu = new MenuItem(message(lang, "ChinesePinyin")); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = ChinesePinyin(lang); if (makeExampleFile("ChinesePinyin", data)) { controller.loadDef(data); } }); dictionariesMenu.getItems().add(menu); menu = new MenuItem(message(lang, "ChinesePhrases")); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = ChinesePhrases(lang); if (makeExampleFile("ChinesePhrases", data)) { controller.loadDef(data); } }); dictionariesMenu.getItems().add(menu); menu = new MenuItem(message(lang, "ChineseTraditional")); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = ChineseTraditional(lang); if (makeExampleFile("ChineseTraditional", data)) { controller.loadDef(data); } }); dictionariesMenu.getItems().add(menu); menu = new MenuItem(message(lang, "ChinesePolyphone")); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = ChinesePolyphone(lang); if (makeExampleFile("ChinesePolyphone", data)) { controller.loadDef(data); } }); dictionariesMenu.getItems().add(menu); dictionariesMenu.getItems().add(new SeparatorMenuItem()); boolean isChinese = Languages.isChinese(lang); Menu blcuMenu = new Menu(isChinese ? "北京语言大学的数据" : "Data from Beijing Language and Culture University"); menu = new MenuItem(isChinese ? "汉字字频-2012-人民日报" : "Counts of Chinese characters in 2012 - People's Daily"); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = ChineseFrequencyBlcuCharactersPD(lang); if (makeExampleFile("ChineseFrequency-blcu-characters-2012-People's Daily", data)) { controller.loadDef(data); } }); blcuMenu.getItems().add(menu); menu = new MenuItem(isChinese ? "历年汉字字频-人民日报" : "Yearly counts of Chinese characters - People's Daily"); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = ChineseFrequencyBlcuYearlyCharactersPD(lang); if (makeExampleFile("ChineseFrequency-blcu-characters-years-People's Daily", data)) { controller.loadDef(data); } }); blcuMenu.getItems().add(menu); menu = new MenuItem(isChinese ? "历年汉字词组-人民日报" : "Yearly counts of Chinese words - People's Daily"); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = ChineseFrequencyBlcuYearlyWordsPD(lang); if (makeExampleFile("ChineseFrequency-blcu-words-years-People's Daily", data)) { controller.loadDef(data); } }); blcuMenu.getItems().add(menu); menu = new MenuItem(isChinese ? "汉语词组-2015-新闻频道" : "Chinese words in news channel in 2015"); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = ChineseFrequencyBlcuNews(lang); if (makeExampleFile("ChineseFrequency-blcu-news-2015", data)) { controller.loadDef(data); } }); blcuMenu.getItems().add(menu); menu = new MenuItem(isChinese ? "汉语词组-2015-技术频道" : "Chinese words in technology channel in 2015"); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = ChineseFrequencyBlcuTechnology(lang); if (makeExampleFile("ChineseFrequency-blcu-technology-2015", data)) { controller.loadDef(data); } }); blcuMenu.getItems().add(menu); menu = new MenuItem(isChinese ? "汉语词组-2015-文学频道" : "Chinese words in literature channel in 2015"); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = ChineseFrequencyBlcuLiterature(lang); if (makeExampleFile("ChineseFrequency-blcu-literature-2015", data)) { controller.loadDef(data); } }); blcuMenu.getItems().add(menu); menu = new MenuItem(isChinese ? "汉语词组-2015-微博频道" : "Chinese words in weibo channel in 2015"); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = ChineseFrequencyBlcuWeibo(lang); if (makeExampleFile("ChineseFrequency-blcu-weibo-2015", data)) { controller.loadDef(data); } }); blcuMenu.getItems().add(menu); menu = new MenuItem(isChinese ? "汉语词组-2015-博客频道" : "Chinese words in blog channel in 2015"); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = ChineseFrequencyBlcuBlog(lang); if (makeExampleFile("ChineseFrequency-blcu-blog-2015", data)) { controller.loadDef(data); } }); blcuMenu.getItems().add(menu); menu = new MenuItem(isChinese ? "汉语词组-2015-频道总和" : "Chinese words in channels in 2015"); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = ChineseFrequencyBlcuGlobal(lang); if (makeExampleFile("ChineseFrequency-blcu-global-2015", data)) { controller.loadDef(data); } }); blcuMenu.getItems().add(menu); menu = new MenuItem(isChinese ? "汉语成语" : "Chinese Idioms"); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = ChineseIdiomsBlcu(lang); if (makeExampleFile("ChineseIdioms-blcu", data)) { controller.loadDef(data); } }); blcuMenu.getItems().add(menu); dictionariesMenu.getItems().add(blcuMenu); Menu othersMenu = new Menu(message(lang, "Others")); menu = new MenuItem(isChinese ? "国家出版局抽样统计最常用的一千个汉字" : "Mostly used chinese characters by State Publication Bureau"); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = ChineseFrequencySPB(lang); if (makeExampleFile("ChineseFrequency-State Publication Bureau", data)) { controller.loadDef(data); } }); othersMenu.getItems().add(menu); menu = new MenuItem(isChinese ? "微信公众号-汉语词频统计-2016" : "Chinese characters statistic of weixin public corpus in 2016"); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = ChineseFrequencyWeixin2016(lang); if (makeExampleFile("ChineseFrequency-weixin_public_corpus-2016", data)) { controller.loadDef(data); } }); othersMenu.getItems().add(menu); menu = new MenuItem(isChinese ? "汉字字频表(基数10亿)" : "Chinese characters statistic based on billion data"); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = ChineseFrequencyBaseBillion(lang); if (makeExampleFile("ChineseFrequency-imewlconverter-BaseBillion", data)) { controller.loadDef(data); } }); othersMenu.getItems().add(menu); menu = new MenuItem(isChinese ? "百度汉字字频表-2009" : "Chinese characters statistic from baidu in 2009"); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = ChineseFrequencyBaidu2009(lang); if (makeExampleFile("ChineseFrequency-Baidu-2009", data)) { controller.loadDef(data); } }); othersMenu.getItems().add(menu); menu = new MenuItem(isChinese ? "Google汉字字频表-2005" : "Chinese characters statistic from Google in 2005"); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = ChineseFrequencyGoogle2005(lang); if (makeExampleFile("ChineseFrequency-Google-2005", data)) { controller.loadDef(data); } }); othersMenu.getItems().add(menu); menu = new MenuItem(isChinese ? "Yahoo汉字字频表-2009" : "Chinese characters statistic from Yahoo in 2009"); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = ChineseFrequencyYahoo2009(lang); if (makeExampleFile("ChineseFrequency-Yahoo-2009", data)) { controller.loadDef(data); } }); othersMenu.getItems().add(menu); menu = new MenuItem(isChinese ? "知乎语料库" : "Chinese characters statistic of Zhihu"); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = ChineseFrequencyZhihu(lang); if (makeExampleFile("ChineseFrequency-Zhihu", data)) { controller.loadDef(data); } }); othersMenu.getItems().add(menu); menu = new MenuItem(isChinese ? "古代汉语语料库字频表" : "Chinese characters statistic in ancient China"); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = ChineseFrequencyCncorpusAncient(lang); if (makeExampleFile("ChineseFrequency-cncorpus-ancient China", data)) { controller.loadDef(data); } }); othersMenu.getItems().add(menu); menu = new MenuItem(isChinese ? "现代汉语语料库字频表" : "Chinese characters statistic in modern China"); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = ChineseFrequencyCncorpusCharactersModern(lang); if (makeExampleFile("ChineseFrequency-cncorpus-characters-modern China", data)) { controller.loadDef(data); } }); othersMenu.getItems().add(menu); menu = new MenuItem(isChinese ? "现代汉语语料库词频表" : "Chinese words statistic in modern China"); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = ChineseFrequencyCncorpusWordsModern(lang); if (makeExampleFile("ChineseFrequency-cncorpus-words-modern China", data)) { controller.loadDef(data); } }); othersMenu.getItems().add(menu); menu = new MenuItem(isChinese ? "现代汉语语料库分词类词频表" : "Chinese participles statistic in modern China"); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = ChineseFrequencyCncorpusParticiplesModern(lang); if (makeExampleFile("ChineseFrequency-cncorpus-participles-modern China", data)) { controller.loadDef(data); } }); othersMenu.getItems().add(menu); menu = new MenuItem(isChinese ? "唐诗宋词元曲" : "Chinese characters statistic about traditional literature"); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = ChineseFrequencyTraditionalLiterature(lang); if (makeExampleFile("ChineseFrequency-traditional literature", data)) { controller.loadDef(data); } }); othersMenu.getItems().add(menu); menu = new MenuItem(isChinese ? "文淵閣四庫全書" : "Chinese characters statistic of the Si Ku Quan Shu"); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = ChineseFrequencySiKuQuanShu(lang); if (makeExampleFile("ChineseFrequency-freemdict-SiKuQuanShu", data)) { controller.loadDef(data); } }); othersMenu.getItems().add(menu); menu = new MenuItem(isChinese ? "殆知阁" : "Chinese characters statistic of the Yi Zhi Ge"); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = ChineseFrequencyYiZhiGe(lang); if (makeExampleFile("ChineseFrequency-mahavivo-YiZhiGe", data)) { controller.loadDef(data); } }); othersMenu.getItems().add(menu); dictionariesMenu.getItems().add(othersMenu); return dictionariesMenu; } catch (Exception e) { MyBoxLog.error(e); return null; } } /* exmaples of data 2D definition */ public static DataFileCSV ChineseCharactersStandard(String lang) { boolean isChinese = Languages.isChinese(lang); DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(isChinese ? "编号" : "Number", ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(isChinese ? "字" : "Character", ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(isChinese ? "级别" : "Level", ColumnDefinition.ColumnType.Short)); columns.add(new Data2DColumn(isChinese ? "部首" : "Radical", ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(isChinese ? "笔画数" : "Stroke Count", ColumnDefinition.ColumnType.Short)); columns.add(new Data2DColumn(isChinese ? "拼音" : "Pinyin", ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(isChinese ? "多音" : "Other Pinyin", ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(isChinese ? "繁体" : "Traditional", ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(isChinese ? "异形" : "Variant", ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(isChinese ? "字形" : "Glyph", ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(isChinese ? "笔顺" : "Strokes", ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(isChinese ? "拼音首" : "Pinyin Front", ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(isChinese ? "拼音尾" : "Pinyin End", ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(isChinese ? "音调" : "Tone", ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(isChinese ? "五笔" : "Wubi", ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(isChinese ? "十六进制" : "Hex", ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(isChinese ? "十进制" : "Dec", ColumnDefinition.ColumnType.String)); data.setColumns(columns).setDataName(message(lang, "ChineseCharactersStandard")); return data; } public static DataFileCSV ChineseRadicals(String lang) { boolean isChinese = Languages.isChinese(lang); DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(isChinese ? "部首" : "Radical", ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(isChinese ? "名字" : "Name", ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(isChinese ? "笔画数" : "Stroke Count", ColumnDefinition.ColumnType.Short)); data.setColumns(columns).setDataName(message(lang, "ChineseRadicals")); return data; } public static DataFileCSV ChinesePinyin(String lang) { boolean isChinese = Languages.isChinese(lang); DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(isChinese ? "拼音" : "Pinyin", ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(isChinese ? "字" : "Characters", ColumnDefinition.ColumnType.String)); data.setColumns(columns).setDataName(message(lang, "ChinesePinyin")); return data; } public static DataFileCSV ChinesePhrases(String lang) { boolean isChinese = Languages.isChinese(lang); DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(isChinese ? "词组" : "Phrase", ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(isChinese ? "繁体" : "Traditional", ColumnDefinition.ColumnType.String)); data.setColumns(columns).setDataName(message(lang, "ChinesePhrases")); return data; } public static DataFileCSV ChineseTraditional(String lang) { boolean isChinese = Languages.isChinese(lang); DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(isChinese ? "字" : "Character", ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(isChinese ? "繁体" : "Traditional", ColumnDefinition.ColumnType.String)); data.setColumns(columns).setDataName(message(lang, "ChineseTraditional")); return data; } public static DataFileCSV ChinesePolyphone(String lang) { boolean isChinese = Languages.isChinese(lang); DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(isChinese ? "编号" : "Number", ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(isChinese ? "字" : "Character", ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(isChinese ? "拼音" : "Pinyin", ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(isChinese ? "多音" : "Other Pinyin", ColumnDefinition.ColumnType.String)); data.setColumns(columns).setDataName(message(lang, "ChinesePolyphone")); return data; } public static DataFileCSV ChineseFrequencyBlcuCharactersPD(String lang) { boolean isChinese = Languages.isChinese(lang); DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(isChinese ? "汉字" : "Character", ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(isChinese ? "排名" : "Rank", ColumnDefinition.ColumnType.Long)); columns.add(new Data2DColumn(isChinese ? "频次" : "Count", ColumnDefinition.ColumnType.Long)); columns.add(new Data2DColumn(isChinese ? "频率" : "Frequency", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "累计频率" : "Cumulative frequency", ColumnDefinition.ColumnType.Double)); data.setColumns(columns).setDataName(isChinese ? "汉字字频-人民日报" : "Counts of Chinese characters - People's Daily"); return data; } public static DataFileCSV ChineseFrequencyBlcuYearlyCharactersPD(String lang) { boolean isChinese = Languages.isChinese(lang); DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(isChinese ? "年份" : "Year", ColumnDefinition.ColumnType.Short)); columns.add(new Data2DColumn(isChinese ? "排名" : "Rank", ColumnDefinition.ColumnType.Long)); columns.add(new Data2DColumn(isChinese ? "汉字" : "Character", ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(isChinese ? "频次" : "Count", ColumnDefinition.ColumnType.Long)); columns.add(new Data2DColumn(isChinese ? "频率" : "Frequency", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "累计频率" : "Cumulative frequency", ColumnDefinition.ColumnType.Double)); data.setColumns(columns).setDataName(isChinese ? "历年汉字字频-人民日报" : "Yearly counts of Chinese characters - People's Daily"); return data; } public static DataFileCSV ChineseFrequencyBlcuYearlyWordsPD(String lang) { boolean isChinese = Languages.isChinese(lang); DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(isChinese ? "年份" : "Year", ColumnDefinition.ColumnType.Short)); columns.add(new Data2DColumn(isChinese ? "排名" : "Rank", ColumnDefinition.ColumnType.Long)); columns.add(new Data2DColumn(isChinese ? "词" : "Word", ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(isChinese ? "频次" : "Count", ColumnDefinition.ColumnType.Long)); columns.add(new Data2DColumn(isChinese ? "频率" : "Frequency", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "累计频率" : "Cumulative frequency", ColumnDefinition.ColumnType.Double)); data.setColumns(columns).setDataName(isChinese ? "历年汉字词组-人民日报" : "Yearly counts of Chinese words - People's Daily"); return data; } public static DataFileCSV ChineseIdiomsBlcu(String lang) { boolean isChinese = Languages.isChinese(lang); DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(isChinese ? "成语" : "Idiom", ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(isChinese ? "拼音" : "Pinyin", ColumnDefinition.ColumnType.String)); data.setColumns(columns).setDataName(isChinese ? "汉语成语" : "Chinese Idioms"); return data; } public static DataFileCSV ChineseFrequencyBlcuNews(String lang) { boolean isChinese = Languages.isChinese(lang); DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(isChinese ? "词" : "Word", ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(isChinese ? "排名" : "Rank", ColumnDefinition.ColumnType.Long)); columns.add(new Data2DColumn(isChinese ? "频次" : "Count", ColumnDefinition.ColumnType.Long)); data.setColumns(columns).setDataName(isChinese ? "汉语词组-2015-新闻频道" : "Chinese words in news channel in 2015"); return data; } public static DataFileCSV ChineseFrequencyBlcuLiterature(String lang) { boolean isChinese = Languages.isChinese(lang); DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(isChinese ? "词" : "Word", ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(isChinese ? "排名" : "Rank", ColumnDefinition.ColumnType.Long)); columns.add(new Data2DColumn(isChinese ? "频次" : "Count", ColumnDefinition.ColumnType.Long)); data.setColumns(columns).setDataName(isChinese ? "汉语词组-2015-文学频道" : "Chinese words in literature channel in 2015"); return data; } public static DataFileCSV ChineseFrequencyBlcuTechnology(String lang) { boolean isChinese = Languages.isChinese(lang); DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(isChinese ? "词" : "Word", ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(isChinese ? "排名" : "Rank", ColumnDefinition.ColumnType.Long)); columns.add(new Data2DColumn(isChinese ? "频次" : "Count", ColumnDefinition.ColumnType.Long)); data.setColumns(columns).setDataName(isChinese ? "汉语词组-2015-技术频道" : "Chinese words in technology channel in 2015"); return data; } public static DataFileCSV ChineseFrequencyBlcuWeibo(String lang) { boolean isChinese = Languages.isChinese(lang); DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(isChinese ? "词" : "Word", ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(isChinese ? "排名" : "Rank", ColumnDefinition.ColumnType.Long)); columns.add(new Data2DColumn(isChinese ? "频次" : "Count", ColumnDefinition.ColumnType.Long)); data.setColumns(columns).setDataName(isChinese ? "汉语词组-2015-微博频道" : "Chinese words in weibo channel in 2015"); return data; } public static DataFileCSV ChineseFrequencyBlcuBlog(String lang) { boolean isChinese = Languages.isChinese(lang); DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(isChinese ? "词" : "Word", ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(isChinese ? "排名" : "Rank", ColumnDefinition.ColumnType.Long)); columns.add(new Data2DColumn(isChinese ? "频次" : "Count", ColumnDefinition.ColumnType.Long)); data.setColumns(columns).setDataName(isChinese ? "汉语词组-2015-博客频道" : "Chinese words in blog channel in 2015"); return data; } public static DataFileCSV ChineseFrequencyBlcuGlobal(String lang) { boolean isChinese = Languages.isChinese(lang); DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(isChinese ? "词" : "Word", ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(isChinese ? "排名" : "Rank", ColumnDefinition.ColumnType.Long)); columns.add(new Data2DColumn(isChinese ? "频次" : "Count", ColumnDefinition.ColumnType.Long)); data.setColumns(columns).setDataName(isChinese ? "汉语词组-2015-频道总和" : "Chinese words in channels in 2015"); return data; } public static DataFileCSV ChineseFrequencySPB(String lang) { boolean isChinese = Languages.isChinese(lang); DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(isChinese ? "排名" : "Rank", ColumnDefinition.ColumnType.Long)); columns.add(new Data2DColumn(isChinese ? "汉字" : "Character", ColumnDefinition.ColumnType.String)); data.setColumns(columns).setDataName(isChinese ? "国家出版局抽样统计最常用的一千个汉字" : "Mostly used chinese characters by State Publication Bureau"); return data; } public static DataFileCSV ChineseFrequencyWeixin2016(String lang) { boolean isChinese = Languages.isChinese(lang); DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(isChinese ? "词" : "Word", ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(isChinese ? "频次" : "Count", ColumnDefinition.ColumnType.Long)); data.setColumns(columns).setDataName(isChinese ? "微信公众号-汉语词频统计-2016" : "Chinese characters statistic of by weixin public corpus in 2016"); return data; } public static DataFileCSV ChineseFrequencyBaseBillion(String lang) { boolean isChinese = Languages.isChinese(lang); DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(isChinese ? "汉字" : "Character", ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(isChinese ? "排名" : "Rank", ColumnDefinition.ColumnType.Long)); columns.add(new Data2DColumn(isChinese ? "频次" : "Count", ColumnDefinition.ColumnType.Long)); columns.add(new Data2DColumn(isChinese ? "频率" : "Frequency", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "累计频率" : "Cumulative frequency", ColumnDefinition.ColumnType.Double)); data.setColumns(columns).setDataName(isChinese ? "汉字字频表(基数10亿)" : "Chinese characters statistic based on billion data"); return data; } public static DataFileCSV ChineseFrequencyBaidu2009(String lang) { boolean isChinese = Languages.isChinese(lang); DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(isChinese ? "汉字" : "Character", ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(isChinese ? "频次" : "Count", ColumnDefinition.ColumnType.Long)); data.setColumns(columns).setDataName(isChinese ? "百度汉字字频表-2009" : "Chinese characters statistic from baidu in 2009"); return data; } public static DataFileCSV ChineseFrequencyGoogle2005(String lang) { boolean isChinese = Languages.isChinese(lang); DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(isChinese ? "汉字" : "Character", ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(isChinese ? "频次" : "Count", ColumnDefinition.ColumnType.Long)); data.setColumns(columns).setDataName(isChinese ? "Google汉字字频表-2005" : "Chinese characters statistic from Google in 2005"); return data; } public static DataFileCSV ChineseFrequencyYahoo2009(String lang) { boolean isChinese = Languages.isChinese(lang); DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(isChinese ? "汉字" : "Character", ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(isChinese ? "频次" : "Count", ColumnDefinition.ColumnType.Long)); data.setColumns(columns).setDataName(isChinese ? "Yahoo汉字字频表-2009" : "Chinese characters statistic from Yahoo in 2009"); return data; } public static DataFileCSV ChineseFrequencyTraditionalLiterature(String lang) { boolean isChinese = Languages.isChinese(lang); DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(isChinese ? "汉字" : "Character", ColumnDefinition.ColumnType.String));
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
true
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data2d/example/StatisticDataOfChina.java
released/MyBox/src/main/java/mara/mybox/data2d/example/StatisticDataOfChina.java
package mara.mybox.data2d.example; import java.util.ArrayList; import java.util.List; import javafx.event.ActionEvent; import javafx.scene.control.Menu; import javafx.scene.control.MenuItem; import javafx.scene.control.SeparatorMenuItem; import mara.mybox.controller.BaseData2DLoadController; import mara.mybox.data2d.DataFileCSV; import static mara.mybox.data2d.example.Data2DExampleTools.makeExampleFile; import mara.mybox.db.data.ColumnDefinition; import mara.mybox.db.data.Data2DColumn; import mara.mybox.dev.MyBoxLog; import static mara.mybox.fxml.style.NodeStyleTools.linkStyle; import mara.mybox.fxml.style.StyleTools; import mara.mybox.value.Languages; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2022-9-15 * @License Apache License Version 2.0 */ public class StatisticDataOfChina { public static Menu menu(String lang, BaseData2DLoadController controller) { try { // https://data.stats.gov.cn/index.htm Menu chinaMenu = new Menu(message(lang, "StatisticDataOfChina"), StyleTools.getIconImageView("iconChina.png")); MenuItem menu = new MenuItem(message(lang, "ChinaPopulation")); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = ChinaPopulation(lang); if (makeExampleFile("ChinaPopulation", data)) { controller.loadDef(data); } }); chinaMenu.getItems().add(menu); menu = new MenuItem(message(lang, "ChinaCensus")); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = ChinaCensus(lang); if (makeExampleFile("ChinaCensus", data)) { controller.loadDef(data); } }); chinaMenu.getItems().add(menu); menu = new MenuItem(message(lang, "ChinaGDP")); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = ChinaGDP(lang); if (makeExampleFile("ChinaGDP", data)) { controller.loadDef(data); } }); chinaMenu.getItems().add(menu); menu = new MenuItem(message(lang, "ChinaCPI")); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = ChinaCPI(lang); if (makeExampleFile("ChinaCPI", data)) { controller.loadDef(data); } }); chinaMenu.getItems().add(menu); menu = new MenuItem(message(lang, "ChinaFoodConsumption")); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = ChinaFoodConsumption(lang); if (makeExampleFile("ChinaFoods_" + lang, data)) { controller.loadDef(data); } }); chinaMenu.getItems().add(menu); menu = new MenuItem(message(lang, "ChinaGraduates")); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = ChinaGraduates(lang); if (makeExampleFile("ChinaGraduates", data)) { controller.loadDef(data); } }); chinaMenu.getItems().add(menu); menu = new MenuItem(message(lang, "ChinaMuseums")); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = ChinaMuseums(lang); if (makeExampleFile("ChinaMuseums", data)) { controller.loadDef(data); } }); chinaMenu.getItems().add(menu); menu = new MenuItem(message(lang, "ChinaHealthPersonnel")); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = ChinaHealthPersonnel(lang); if (makeExampleFile("ChinaHealthPersonnel", data)) { controller.loadDef(data); } }); chinaMenu.getItems().add(menu); menu = new MenuItem(message(lang, "ChinaMarriage")); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = ChinaMarriage(lang); if (makeExampleFile("ChinaMarriage", data)) { controller.loadDef(data); } }); chinaMenu.getItems().add(menu); menu = new MenuItem(message(lang, "ChinaSportWorldChampions")); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = ChinaSportWorldChampions(lang); if (makeExampleFile("ChinaSportWorldChampions", data)) { controller.loadDef(data); } }); chinaMenu.getItems().add(menu); menu = new MenuItem(message(lang, "CrimesFiledByChinaPolice")); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = CrimesFiledByChinaPolice(lang); if (makeExampleFile("ChinaCrimesFiledByPolice", data)) { controller.loadDef(data); } }); chinaMenu.getItems().add(menu); menu = new MenuItem(message(lang, "CrimesFiledByChinaProcuratorate")); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = CrimesFiledByChinaProcuratorate(lang); if (makeExampleFile("ChinaCrimesFiledByProcuratorate", data)) { controller.loadDef(data); } }); chinaMenu.getItems().add(menu); chinaMenu.getItems().add(new SeparatorMenuItem()); menu = new MenuItem(message(lang, "ChinaNationalBureauOfStatistics")); menu.setStyle(linkStyle()); menu.setOnAction((ActionEvent event) -> { controller.browse("https://data.stats.gov.cn/"); }); chinaMenu.getItems().add(menu); return chinaMenu; } catch (Exception e) { MyBoxLog.error(e); return null; } } /* exmaples of data 2D definition */ public static DataFileCSV ChinaPopulation(String lang) { boolean isChinese = Languages.isChinese(lang); DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(isChinese ? "年" : "year_", ColumnDefinition.ColumnType.String, true)); columns.add(new Data2DColumn(isChinese ? "年末总人口(万人)" : "population at year-end(ten thousand)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "男性人口(万人)" : "male(ten thousand)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "女性人口(万人)" : "female(ten thousand)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "城镇人口(万人)" : "urban(ten thousand)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "乡村人口(万人)" : "rural(ten thousand)", ColumnDefinition.ColumnType.Double)); data.setColumns(columns).setDataName(message(lang, "ChinaPopulation")) .setComments("https://data.stats.gov.cn/index.htm"); return data; } public static DataFileCSV ChinaCensus(String lang) { boolean isChinese = Languages.isChinese(lang); DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(isChinese ? "年" : "year_", ColumnDefinition.ColumnType.String, true)); columns.add(new Data2DColumn(isChinese ? "人口普查总人口(万人)" : "total population of census(ten thousand)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "男性(万人)" : "male(ten thousand)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "女性(万人)" : "female(ten thousand)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "性别比(女=100)" : "sex ratio(female=100)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "城镇(万人)" : "urban(ten thousand)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "乡村(万人)" : "rural(ten thousand)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "家庭户规模(人/户)" : "family size", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "0-14岁占比(%)" : "aged 0-14(%)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "15-64岁占比(%)" : "aged 15-64(%)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "65岁及以上占比(%)" : "aged over 65(%)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "汉族(万人)" : "han nationality population(ten thousand)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "汉族占比(%)" : "han nationality precentage(%)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "少数民族(万人)" : "minority nationality population(ten thousand)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "少数民族占比(%)" : "minority nationality precentage(%)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "每十万人口中受大专及以上教育人口数(人)" : "junior college or above education per one hundred thousand", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "每十万人口中受高中和中专教育人口数(人)" : "high school and secondary education per hundred thousand", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "每十万人口中受初中教育人口数(人)" : "junior high school education per hundred thousand", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "每十万人口中受小学教育人口数(人)" : "primary school education per hundred thousand", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "文盲人口数(万人)" : "illiteracy(ten thousand)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "文盲率(%)" : "illiteracy percentage(%)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "城镇化率(%)" : "urbanization rate(%)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "平均预期寿命(岁)" : "average life expectancy(years)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "男性平均预期寿命(岁)" : "male average life expectancy(years)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "女性平均预期寿命(岁)" : "female average life expectancy(years)", ColumnDefinition.ColumnType.Double)); data.setColumns(columns).setDataName(message(lang, "ChinaCensus")) .setComments("https://data.stats.gov.cn/index.htm"); return data; } public static DataFileCSV ChinaGDP(String lang) { boolean isChinese = Languages.isChinese(lang); DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(isChinese ? "年" : "year_", ColumnDefinition.ColumnType.String, true)); columns.add(new Data2DColumn(isChinese ? "国民总收入(GNI 亿元)" : "gross national income(GNI hundred million yuan)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "国内生产总值(GDP 亿元)" : "gross domestic product(GDP hundred million yuan)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "第一产业增加值(VA1 亿元)" : "value-added of first industry(VA1 hundred million yuan)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "第二产业增加值(VA2 亿元)" : "value-added of secondary industry(VA2 hundred million yuan)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "第三产业增加值(VA3 亿元)" : "value-added of tertiary industry(VA3 hundred million yuan)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "人均国内生产总值(元)" : "GDP per capita(yuan)", ColumnDefinition.ColumnType.Double)); data.setColumns(columns).setDataName(message(lang, "ChinaGDP")) .setComments("https://data.stats.gov.cn/index.htm"); return data; } public static DataFileCSV ChinaCPI(String lang) { boolean isChinese = Languages.isChinese(lang); DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(isChinese ? "年" : "year_", ColumnDefinition.ColumnType.String, true)); columns.add(new Data2DColumn(isChinese ? "居民消费价格指数(CPI 上年=100)" : "consumer price index(CPI last_year=100)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "城市居民消费价格指数(上年=100)" : "urban consumer price index(last_year=100)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "农村居民消费价格指数(上年=100)" : "rural consumer price index(last_year=100)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "商品零售价格指数(RPI 上年=100)" : "retail price index(RPI last_year=100)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "工业生产者出厂价格指数(PPI 上年=100)" : "producer price index(PPI last_year=100)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "工业生产者购进价格指数(PPIRM 上年=100)" : "producer price pndices of raw material(PPIRM last_year=100)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "固定资产投资价格指数(上年=100)" : "price indices of investment in fixed assets(last_year=100)", ColumnDefinition.ColumnType.Double)); data.setColumns(columns).setDataName(message(lang, "ChinaCPI")) .setComments("https://data.stats.gov.cn/index.htm"); return data; } public static DataFileCSV ChinaFoodConsumption(String lang) { boolean isChinese = Languages.isChinese(lang); DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(isChinese ? "指标" : "item", ColumnDefinition.ColumnType.String, true)); columns.add(new Data2DColumn(isChinese ? "2020年" : "year 2020", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "2019年" : "year 2019", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "2018年" : "year 2018", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "2017年" : "year 2017", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "2016年" : "year 2016", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "2015年" : "year 2015", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "2014年" : "year 2014", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "2013年" : "year 2013", ColumnDefinition.ColumnType.Double)); data.setColumns(columns).setDataName(message(lang, "ChinaFoodConsumption")) .setComments("https://data.stats.gov.cn/index.htm"); return data; } public static DataFileCSV ChinaGraduates(String lang) { boolean isChinese = Languages.isChinese(lang); DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(isChinese ? "年" : "year_", ColumnDefinition.ColumnType.String, true)); columns.add(new Data2DColumn(isChinese ? "普通高等学校毕业生数(万人)" : "college graduates(ten thousand)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "普通中学毕业生数(万人)" : "middle school graduates(ten thousand)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "普通高中毕业生数(万人)" : "high school graduates(ten thousand)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "初中毕业生数(万人)" : "junior high school graduates(ten thousand)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "职业中学毕业生数(万人)" : "vocational high school graduates(ten thousand)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "普通小学毕业生数(万人)" : "primary school graduates(ten thousand)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "特殊教育学校毕业生数(万人)" : "special education school graduates(ten thousand)", ColumnDefinition.ColumnType.Double)); data.setColumns(columns).setDataName(message(lang, "ChinaGraduates")) .setComments("https://data.stats.gov.cn/index.htm"); return data; } public static DataFileCSV ChinaMuseums(String lang) { boolean isChinese = Languages.isChinese(lang); DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(isChinese ? "年" : "year_", ColumnDefinition.ColumnType.String, true)); columns.add(new Data2DColumn(isChinese ? "博物馆机构数(个)" : "museum institutions", ColumnDefinition.ColumnType.Long)); columns.add(new Data2DColumn(isChinese ? "博物馆从业人员(人)" : "employed", ColumnDefinition.ColumnType.Long)); columns.add(new Data2DColumn(isChinese ? "博物馆文物藏品(件/套)" : "relics", ColumnDefinition.ColumnType.Long)); columns.add(new Data2DColumn(isChinese ? "本年博物馆从有关部门接收文物数(件/套)" : "received in the year", ColumnDefinition.ColumnType.Long)); columns.add(new Data2DColumn(isChinese ? "本年博物馆修复文物数(件/套)" : "fixed in the year", ColumnDefinition.ColumnType.Long)); columns.add(new Data2DColumn(isChinese ? "博物馆考古发掘项目(个)" : "archaeology projects", ColumnDefinition.ColumnType.Long)); columns.add(new Data2DColumn(isChinese ? "博物馆基本陈列(个)" : "basical exhibition", ColumnDefinition.ColumnType.Long)); columns.add(new Data2DColumn(isChinese ? "博物馆举办展览(个)" : "special exhibition", ColumnDefinition.ColumnType.Long)); columns.add(new Data2DColumn(isChinese ? "博物馆参观人次(万人次)" : "visits(ten thousand)", ColumnDefinition.ColumnType.Double)); data.setColumns(columns).setDataName(message(lang, "ChinaMuseums")) .setComments("https://data.stats.gov.cn/index.htm"); return data; } public static DataFileCSV ChinaHealthPersonnel(String lang) { boolean isChinese = Languages.isChinese(lang); DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(isChinese ? "年" : "year_", ColumnDefinition.ColumnType.String, true)); columns.add(new Data2DColumn(isChinese ? "卫生人员数(万人)" : "health personnel(ten thousand)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "卫生技术人员数(万人)" : "medical personnel(ten thousand)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "执业(助理)医师数(万人)" : "practitioner(assistant)(ten thousand)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "执业医师数(万人)" : "practitioner(ten thousand)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "注册护士数(万人)" : "registered nurse(ten thousand)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "药师数(万人)" : "pharmacist(ten thousand)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "乡村医生和卫生员数(万人)" : "rural(ten thousand)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "其他技术人员数(万人)" : "other technical personnel(ten thousand)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "管理人员数(万人)" : "managerial personnel(ten thousand)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "工勤技能人员数(万人)" : "worker(ten thousand)", ColumnDefinition.ColumnType.Double)); data.setColumns(columns).setDataName(message(lang, "ChinaHealthPersonnel")) .setComments("https://data.stats.gov.cn/index.htm"); return data; } public static DataFileCSV ChinaMarriage(String lang) { boolean isChinese = Languages.isChinese(lang); DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(isChinese ? "年" : "year_", ColumnDefinition.ColumnType.String, true)); columns.add(new Data2DColumn(isChinese ? "结婚登记(万对)" : "married(ten thousand pairs)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "内地居民登记结婚(万对)" : "mainland residents married(ten thousand pairs)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "内地居民初婚登记(万人)" : "mainland residents newly married(ten thousand persons)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "内地居民再婚登记(万人)" : "mainland residents remarried(ten thousand persons)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "涉外及港澳台居民登记结婚(万对)" : "foreigners/HongKong/Macao/Taiwan married(ten thousand pairs)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "离婚登记(万对)" : "divorced(ten thousand pairs)", ColumnDefinition.ColumnType.Double)); columns.add(new Data2DColumn(isChinese ? "粗离婚率(千分比)" : "divorced ratio(permillage)", ColumnDefinition.ColumnType.Double)); data.setColumns(columns).setDataName(message(lang, "ChinaMarriage")) .setComments("https://data.stats.gov.cn/index.htm"); return data; } public static DataFileCSV ChinaSportWorldChampions(String lang) { boolean isChinese = Languages.isChinese(lang); DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(isChinese ? "年" : "year_", ColumnDefinition.ColumnType.String, true)); columns.add(new Data2DColumn(isChinese ? "世界冠军项数" : "categories of world champions", ColumnDefinition.ColumnType.Integer)); columns.add(new Data2DColumn(isChinese ? "女子世界冠军项数" : "categories of female world champions", ColumnDefinition.ColumnType.Integer)); columns.add(new Data2DColumn(isChinese ? "世界冠军人数" : "athletes of world champions", ColumnDefinition.ColumnType.Integer)); columns.add(new Data2DColumn(isChinese ? "女子世界冠军人数" : "female athletes of world champions", ColumnDefinition.ColumnType.Integer)); columns.add(new Data2DColumn(isChinese ? "世界冠军个数" : "number of world champions", ColumnDefinition.ColumnType.Integer)); columns.add(new Data2DColumn(isChinese ? "女子世界冠军个数" : "number of female world champions", ColumnDefinition.ColumnType.Integer)); data.setColumns(columns).setDataName(message(lang, "ChinaSportWorldChampions")) .setComments("https://data.stats.gov.cn/index.htm"); return data; } public static DataFileCSV CrimesFiledByChinaPolice(String lang) { boolean isChinese = Languages.isChinese(lang); DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(isChinese ? "年" : "year_", ColumnDefinition.ColumnType.String, true)); columns.add(new Data2DColumn(isChinese ? "立案的刑事案件" : "filed crimes", ColumnDefinition.ColumnType.Integer)); columns.add(new Data2DColumn(isChinese ? "杀人" : "murder", ColumnDefinition.ColumnType.Integer)); columns.add(new Data2DColumn(isChinese ? "伤害" : "injure", ColumnDefinition.ColumnType.Integer)); columns.add(new Data2DColumn(isChinese ? "抢劫" : "rob", ColumnDefinition.ColumnType.Integer)); columns.add(new Data2DColumn(isChinese ? "强奸" : "rape", ColumnDefinition.ColumnType.Integer)); columns.add(new Data2DColumn(isChinese ? "拐卖妇女儿童" : "trafficking", ColumnDefinition.ColumnType.Integer)); columns.add(new Data2DColumn(isChinese ? "盗窃" : "steal", ColumnDefinition.ColumnType.Integer)); columns.add(new Data2DColumn(isChinese ? "诈骗" : "scam", ColumnDefinition.ColumnType.Integer)); columns.add(new Data2DColumn(isChinese ? "走私" : "smuggle", ColumnDefinition.ColumnType.Integer)); columns.add(new Data2DColumn(isChinese ? "假币" : "counterfeit money", ColumnDefinition.ColumnType.Integer)); columns.add(new Data2DColumn(isChinese ? "其他" : "others", ColumnDefinition.ColumnType.Integer)); data.setColumns(columns).setDataName(message(lang, "CrimesFiledByChinaPolice")) .setComments("https://data.stats.gov.cn/index.htm"); return data; } public static DataFileCSV CrimesFiledByChinaProcuratorate(String lang) { boolean isChinese = Languages.isChinese(lang); DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(isChinese ? "年" : "year_", ColumnDefinition.ColumnType.String, true)); columns.add(new Data2DColumn(isChinese ? "受案数" : "filed crimes", ColumnDefinition.ColumnType.Integer)); columns.add(new Data2DColumn(isChinese ? "贪污贿赂" : "corruption and bribery", ColumnDefinition.ColumnType.Integer)); columns.add(new Data2DColumn(isChinese ? "贪污" : "corruption", ColumnDefinition.ColumnType.Integer)); columns.add(new Data2DColumn(isChinese ? "贿赂" : "bribery", ColumnDefinition.ColumnType.Integer)); columns.add(new Data2DColumn(isChinese ? "挪用公款" : "embezzlement", ColumnDefinition.ColumnType.Integer)); columns.add(new Data2DColumn(isChinese ? "集体私分" : "collectively dividing up state-owned properties without permission", ColumnDefinition.ColumnType.Integer)); columns.add(new Data2DColumn(isChinese ? "巨额财产来源不明" : "huge unidentified property", ColumnDefinition.ColumnType.Integer)); columns.add(new Data2DColumn(isChinese ? "其他贪污贿赂" : "other corruption and bribery", ColumnDefinition.ColumnType.Integer)); columns.add(new Data2DColumn(isChinese ? "渎职" : "malfeasance", ColumnDefinition.ColumnType.Integer)); columns.add(new Data2DColumn(isChinese ? "滥用职权" : "abuses of power", ColumnDefinition.ColumnType.Integer)); columns.add(new Data2DColumn(isChinese ? "玩忽职守" : "neglecting of duty", ColumnDefinition.ColumnType.Integer)); columns.add(new Data2DColumn(isChinese ? "徇私舞弊" : "favoritism", ColumnDefinition.ColumnType.Integer)); columns.add(new Data2DColumn(isChinese ? "其他渎职" : "other malfeasance", ColumnDefinition.ColumnType.Integer)); data.setColumns(columns).setDataName(message(lang, "CrimesFiledByChinaProcuratorate")) .setComments("https://data.stats.gov.cn/index.htm"); return data; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data2d/example/Matrix.java
released/MyBox/src/main/java/mara/mybox/data2d/example/Matrix.java
package mara.mybox.data2d.example; import javafx.event.ActionEvent; import javafx.scene.control.Menu; import javafx.scene.control.MenuItem; import mara.mybox.controller.BaseData2DLoadController; import mara.mybox.data2d.DataMatrix; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.style.StyleTools; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2022-9-15 * @License Apache License Version 2.0 */ public class Matrix { public static Menu menu(String lang, BaseData2DLoadController controller) { try { Menu locationMenu = new Menu(message(lang, "Matrix"), StyleTools.getIconImageView("iconMatrix.png")); short scale1 = 4, scale2 = 8; int max = 100000; MenuItem menu = new MenuItem(message(lang, "DoubleMatrix") + " 10*10"); menu.setOnAction((ActionEvent event) -> { DataMatrix matrix = DataMatrix.makeMatrix("Double", 10, 10, scale1, max); controller.loadDef(matrix); }); locationMenu.getItems().add(menu); menu = new MenuItem(message(lang, "DoubleMatrix") + " " + message(lang, "PureDecimal") + " 10*10"); menu.setOnAction((ActionEvent event) -> { DataMatrix matrix = DataMatrix.makeMatrix("Double", 10, 10, scale2, 1); controller.loadDef(matrix); }); locationMenu.getItems().add(menu); menu = new MenuItem(message(lang, "DoubleMatrix") + " 50*50"); menu.setOnAction((ActionEvent event) -> { DataMatrix matrix = DataMatrix.makeMatrix("Double", 50, 50, scale1, max); controller.loadDef(matrix); }); locationMenu.getItems().add(menu); menu = new MenuItem(message(lang, "DoubleMatrix") + " " + message(lang, "PureDecimal") + " 50*50"); menu.setOnAction((ActionEvent event) -> { DataMatrix matrix = DataMatrix.makeMatrix("Double", 50, 50, scale2, 1); controller.loadDef(matrix); }); locationMenu.getItems().add(menu); menu = new MenuItem(message(lang, "DoubleMatrix") + " 500*500"); menu.setOnAction((ActionEvent event) -> { DataMatrix matrix = DataMatrix.makeMatrix("Double", 500, 500, scale1, max); controller.loadDef(matrix); }); locationMenu.getItems().add(menu); menu = new MenuItem(message(lang, "DoubleMatrix") + " 1000*1000"); menu.setOnAction((ActionEvent event) -> { DataMatrix matrix = DataMatrix.makeMatrix("Double", 1000, 1000, scale1, max); controller.loadDef(matrix); }); locationMenu.getItems().add(menu); menu = new MenuItem(message(lang, "FloatMatrix") + " 50*50"); menu.setOnAction((ActionEvent event) -> { DataMatrix matrix = DataMatrix.makeMatrix("Float", 50, 50, scale1, max); controller.loadDef(matrix); }); locationMenu.getItems().add(menu); menu = new MenuItem(message(lang, "FloatMatrix") + " " + message(lang, "PureDecimal") + " 50*50"); menu.setOnAction((ActionEvent event) -> { DataMatrix matrix = DataMatrix.makeMatrix("Float", 50, 50, scale2, 1); controller.loadDef(matrix); }); locationMenu.getItems().add(menu); menu = new MenuItem(message(lang, "IntegerMatrix") + " 50*50"); menu.setOnAction((ActionEvent event) -> { DataMatrix matrix = DataMatrix.makeMatrix("Integer", 50, 50, scale1, max); controller.loadDef(matrix); }); locationMenu.getItems().add(menu); menu = new MenuItem(message(lang, "BooleanMatrix") + " 50*50"); menu.setOnAction((ActionEvent event) -> { DataMatrix matrix = DataMatrix.makeMatrix("NumberBoolean", 50, 50, scale1, max); controller.loadDef(matrix); }); locationMenu.getItems().add(menu); return locationMenu; } catch (Exception e) { MyBoxLog.error(e); return null; } } /* exmaples of data 2D definition */ }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data2d/example/ProjectManagement.java
released/MyBox/src/main/java/mara/mybox/data2d/example/ProjectManagement.java
package mara.mybox.data2d.example; import java.util.ArrayList; import java.util.List; import javafx.event.ActionEvent; import javafx.scene.control.Menu; import javafx.scene.control.MenuItem; import mara.mybox.controller.BaseData2DLoadController; import mara.mybox.data2d.DataFileCSV; import static mara.mybox.data2d.example.Data2DExampleTools.makeExampleFile; import mara.mybox.db.data.ColumnDefinition; import mara.mybox.db.data.Data2DColumn; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.style.StyleTools; import mara.mybox.value.Languages; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2022-9-15 * @License Apache License Version 2.0 */ public class ProjectManagement { public static Menu menu(String lang, BaseData2DLoadController controller) { try { Menu pmMenu = new Menu(message(lang, "ProjectManagement"), StyleTools.getIconImageView("iconCalculator.png")); MenuItem menu = new MenuItem(message(lang, "ProjectRegister")); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = ProjectRegister(lang); if (makeExampleFile("PM_ProjectRegister_" + lang, data)) { controller.loadDef(data); } }); pmMenu.getItems().add(menu); menu = new MenuItem(message(lang, "ProjectStatus")); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = ProjectStatus(lang); if (makeExampleFile("PM_ProjectStatus_" + lang, data)) { controller.loadDef(data); } }); pmMenu.getItems().add(menu); menu = new MenuItem(message(lang, "TaskRegister")); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = TaskRegister(lang); if (makeExampleFile("PM_TaskRegister_" + lang, data)) { controller.loadDef(data); } }); pmMenu.getItems().add(menu); menu = new MenuItem(message(lang, "TaskStatus")); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = TaskStatus(lang); if (makeExampleFile("PM_TaskStatus_" + lang, data)) { controller.loadDef(data); } }); pmMenu.getItems().add(menu); menu = new MenuItem(message(lang, "PersonRegister")); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = PersonRegister(lang); if (makeExampleFile("PM_PersonRegister_" + lang, data)) { controller.loadDef(data); } }); pmMenu.getItems().add(menu); menu = new MenuItem(message(lang, "PersonStatus")); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = PersonStatus(lang); if (makeExampleFile("PM_PersonStatus_" + lang, data)) { controller.loadDef(data); } }); pmMenu.getItems().add(menu); menu = new MenuItem(message(lang, "ResourceRegister")); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = ResourceRegister(lang); if (makeExampleFile("PM_ResourceRegister_" + lang, data)) { controller.loadDef(data); } }); pmMenu.getItems().add(menu); menu = new MenuItem(message(lang, "ResourceStatus")); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = ResourceStatus(lang); if (makeExampleFile("PM_ResourceStatus_" + lang, data)) { controller.loadDef(data); } }); pmMenu.getItems().add(menu); menu = new MenuItem(message(lang, "RiskAnalysis")); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = RiskAnalysis(lang); if (makeExampleFile("PM_RiskAnalysis_" + lang, data)) { controller.loadDef(data); } }); pmMenu.getItems().add(menu); menu = new MenuItem(message(lang, "CostRecord")); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = CostRecord(lang); if (makeExampleFile("PM_CostRecords_" + lang, data)) { controller.loadDef(data); } }); pmMenu.getItems().add(menu); menu = new MenuItem(message(lang, "VerificationRecord")); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = VerificationRecord(lang); if (makeExampleFile("PM_VerifyRecord_" + lang, data)) { controller.loadDef(data); } }); pmMenu.getItems().add(menu); return pmMenu; } catch (Exception e) { MyBoxLog.error(e); return null; } } /* exmaples of data 2D definition */ public static DataFileCSV ProjectRegister(String lang) { boolean isChinese = Languages.isChinese(lang); DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(message(lang, "ConfigurationID"), ColumnDefinition.ColumnType.String, true).setWidth(140)); columns.add(new Data2DColumn(message(lang, "Name"), ColumnDefinition.ColumnType.String, true).setWidth(200)); columns.add(new Data2DColumn(message(lang, "LastStatus"), ColumnDefinition.ColumnType.Enumeration) .setFormat(isChinese ? "申请\n已批准\n需求分析\n设计\n实现\n测试\n验证\n维护\n已完成\n被否定\n失败\n已取消" : "Applying\nApproved\nRequirement\nDesign\nImplementing\nTesting\nValidated\nMaintenance\nCompleted\nDenied\nFailed\nCanceled")); columns.add(new Data2DColumn(isChinese ? "项目经理" : "Manager", ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(isChinese ? "批准者" : "Approver", ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(message(lang, "StartTime"), ColumnDefinition.ColumnType.Datetime)); columns.add(new Data2DColumn(isChinese ? "关闭时间" : "Closed time", ColumnDefinition.ColumnType.Datetime)); columns.add(new Data2DColumn(message(lang, "Comments"), ColumnDefinition.ColumnType.String)); data.setColumns(columns).setDataName(isChinese ? "项目登记" : "Project register"); return data; } public static DataFileCSV ProjectStatus(String lang) { boolean isChinese = Languages.isChinese(lang); DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(isChinese ? "项目编号" : "Project ID", ColumnDefinition.ColumnType.String, true).setWidth(140)); columns.add(new Data2DColumn(message(lang, "Status"), ColumnDefinition.ColumnType.Enumeration) .setFormat(isChinese ? "申请\n已批准\n需求分析\n设计\n实现\n测试\n验证\n维护\n已完成\n被否定\n失败\n已取消" : "Applying\nApproved\nRequirement\nDesign\nImplementing\nTesting\nValidated\nMaintenance\nCompleted\nDenied\nFailed\nCanceled")); columns.add(new Data2DColumn(message(lang, "Comments"), ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(message(lang, "Recorder"), ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(message(lang, "RecordTime"), ColumnDefinition.ColumnType.Datetime)); data.setColumns(columns).setDataName(isChinese ? "项目状态" : "Project Status"); return data; } public static DataFileCSV TaskRegister(String lang) { boolean isChinese = Languages.isChinese(lang); DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(message(lang, "ConfigurationID"), ColumnDefinition.ColumnType.String, true).setWidth(140)); columns.add(new Data2DColumn(isChinese ? "项目编号" : "Project ID", ColumnDefinition.ColumnType.String, true).setWidth(140)); columns.add(new Data2DColumn(message(lang, "Name"), ColumnDefinition.ColumnType.String, true).setWidth(200)); columns.add(new Data2DColumn(message(lang, "LastStatus"), ColumnDefinition.ColumnType.Enumeration) .setFormat(isChinese ? "分派\n执行\n完成\n失败\n取消" : "Assign\nPerform\nComplete\nFail\nCancel")); columns.add(new Data2DColumn(isChinese ? "执行者" : "Performer", ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(isChinese ? "开始时间" : "StartTime", ColumnDefinition.ColumnType.Datetime)); columns.add(new Data2DColumn(isChinese ? "关闭时间" : "ClosedTime", ColumnDefinition.ColumnType.Datetime)); columns.add(new Data2DColumn(message(lang, "Comments"), ColumnDefinition.ColumnType.String)); data.setColumns(columns).setDataName(isChinese ? "任务登记" : "Task register"); return data; } public static DataFileCSV TaskStatus(String lang) { boolean isChinese = Languages.isChinese(lang); DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(isChinese ? "任务编号" : "Task ID", ColumnDefinition.ColumnType.String, true).setWidth(140)); columns.add(new Data2DColumn(message(lang, "Status"), ColumnDefinition.ColumnType.Enumeration) .setFormat(isChinese ? "计划\n执行\n完成\n失败\n取消" : "Plan\nPerform\nComplete\nFail\nCancel")); columns.add(new Data2DColumn(message(lang, "Comments"), ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(message(lang, "Recorder"), ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(message(lang, "RecordTime"), ColumnDefinition.ColumnType.Datetime)); data.setColumns(columns).setDataName(isChinese ? "任务状态" : "Task Status"); return data; } public static DataFileCSV PersonRegister(String lang) { boolean isChinese = Languages.isChinese(lang); DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(message(lang, "ConfigurationID"), ColumnDefinition.ColumnType.String, true).setWidth(140)); columns.add(new Data2DColumn(isChinese ? "任务编号" : "Task ID", ColumnDefinition.ColumnType.String, true).setWidth(140)); columns.add(new Data2DColumn(message(lang, "Role"), ColumnDefinition.ColumnType.Enumeration) .setFormat(isChinese ? "投资人\n监管者\n项目经理\n组长\n设计者\n编程者\n测试者\n其他/她" : "Investor\nSupervisor\nProject manager\nTeam leader\nDesigner\nProgrammer\nTester\n\nOther")); columns.add(new Data2DColumn(message(lang, "Name"), ColumnDefinition.ColumnType.String, true)); columns.add(new Data2DColumn(message(lang, "PhoneNumber"), ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(message(lang, "Comments"), ColumnDefinition.ColumnType.String)); data.setColumns(columns).setDataName(isChinese ? "人员登记" : "Person register"); return data; } public static DataFileCSV PersonStatus(String lang) { boolean isChinese = Languages.isChinese(lang); DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(isChinese ? "人员编号" : "Person ID", ColumnDefinition.ColumnType.String, true).setWidth(140)); columns.add(new Data2DColumn(message(lang, "Status"), ColumnDefinition.ColumnType.Enumeration) .setFormat(isChinese ? "加入\n修改信息\n退出" : "Join\nUpdate information\nQuit")); columns.add(new Data2DColumn(message(lang, "Comments"), ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(message(lang, "Recorder"), ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(message(lang, "RecordTime"), ColumnDefinition.ColumnType.Datetime)); data.setColumns(columns).setDataName(isChinese ? "人员状态" : "Person Status"); return data; } public static DataFileCSV ResourceRegister(String lang) { boolean isChinese = Languages.isChinese(lang); DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(message(lang, "ConfigurationID"), ColumnDefinition.ColumnType.String, true).setWidth(140)); columns.add(new Data2DColumn(isChinese ? "任务编号" : "Task ID", ColumnDefinition.ColumnType.String, true).setWidth(140)); columns.add(new Data2DColumn(message(lang, "Type"), ColumnDefinition.ColumnType.Enumeration) .setFormat(isChinese ? "设备\n程序\n源代码\n文档\n数据\n其它" : "Device\nProgram\nSource codes\nDocument\nData\nOther")); columns.add(new Data2DColumn(message(lang, "Name"), ColumnDefinition.ColumnType.String, true)); columns.add(new Data2DColumn(message(lang, "LastStatus"), ColumnDefinition.ColumnType.Enumeration) .setFormat(isChinese ? "正常\n出借\n出售\n废弃\n损毁\n丢失" : "Normal\nLent\nSaled\nDiscarded\nDamaged\nLost")); columns.add(new Data2DColumn(isChinese ? "保管者" : "Keeper", ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(isChinese ? "登记时间" : "Register time", ColumnDefinition.ColumnType.Datetime)); columns.add(new Data2DColumn(isChinese ? "失效时间" : "Invalid time", ColumnDefinition.ColumnType.Datetime)); columns.add(new Data2DColumn(message(lang, "Comments"), ColumnDefinition.ColumnType.String)); data.setColumns(columns).setDataName(isChinese ? "资源登记" : "Resource register"); return data; } public static DataFileCSV ResourceStatus(String lang) { boolean isChinese = Languages.isChinese(lang); DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(isChinese ? "资源编号" : "Resource ID", ColumnDefinition.ColumnType.String, true).setWidth(140)); columns.add(new Data2DColumn(message(lang, "Status"), ColumnDefinition.ColumnType.Enumeration) .setFormat(isChinese ? "正常\n出借\n出售\n废弃\n损毁\n丢失" : "Normal\nLent\nSaled\nDiscarded\nDamaged\nLost")); columns.add(new Data2DColumn(message(lang, "Comments"), ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(message(lang, "Recorder"), ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(message(lang, "RecordTime"), ColumnDefinition.ColumnType.Datetime)); data.setColumns(columns).setDataName(isChinese ? "资源状态" : "Resource Status"); return data; } public static DataFileCSV RiskAnalysis(String lang) { boolean isChinese = Languages.isChinese(lang); DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(message(lang, "ConfigurationID"), ColumnDefinition.ColumnType.String, true).setWidth(140)); columns.add(new Data2DColumn(isChinese ? "任务编号" : "Task ID", ColumnDefinition.ColumnType.String, true).setWidth(140)); columns.add(new Data2DColumn(message(lang, "Type"), ColumnDefinition.ColumnType.Enumeration) .setFormat(isChinese ? "范围\n质量\n时间\n资金\n技术\n人力\n法律\n其它" : "Scope\nQuality\nTime\nMoney\nTechnique\nHuman\nLaw\nOther")); columns.add(new Data2DColumn(isChinese ? "风险项" : "Risk Item", ColumnDefinition.ColumnType.String, true)); columns.add(new Data2DColumn(isChinese ? "可能性" : "Probability", ColumnDefinition.ColumnType.Integer)); columns.add(new Data2DColumn(isChinese ? "严重性" : "Severity", ColumnDefinition.ColumnType.Integer)); columns.add(new Data2DColumn(isChinese ? "优先级" : "Priority", ColumnDefinition.ColumnType.Integer)); columns.add(new Data2DColumn(message(lang, "Description"), ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(isChinese ? "影响" : "Effects", ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(isChinese ? "应急措施" : "Contingency Actions", ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(isChinese ? "分析者" : "Analyzer", ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(isChinese ? "分析时间" : "Analysis time", ColumnDefinition.ColumnType.Datetime)); data.setColumns(columns).setDataName(isChinese ? "风险分析" : "Risk Analysis"); return data; } public static DataFileCSV CostRecord(String lang) { boolean isChinese = Languages.isChinese(lang); DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(isChinese ? "任务编号" : "Task ID", ColumnDefinition.ColumnType.String, true).setWidth(140)); columns.add(new Data2DColumn(isChinese ? "计划开始日期" : "Planned start time", ColumnDefinition.ColumnType.Date)); columns.add(new Data2DColumn(isChinese ? "计划结束日期" : "Planned end time", ColumnDefinition.ColumnType.Date)); columns.add(new Data2DColumn(isChinese ? "计划工作量(人月)" : "Planned workload(person-month)", ColumnDefinition.ColumnType.Float)); columns.add(new Data2DColumn(isChinese ? "计划成本(元)" : "Planned cost(Yuan)", ColumnDefinition.ColumnType.Float)); columns.add(new Data2DColumn(isChinese ? "计划产出" : "Planned results", ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(isChinese ? "实际开始日期" : "Actual start time", ColumnDefinition.ColumnType.Date)); columns.add(new Data2DColumn(isChinese ? "实际结束日期" : "Actual end time", ColumnDefinition.ColumnType.Date)); columns.add(new Data2DColumn(isChinese ? "实际工作量(人月)" : "Actual workload(person-month)", ColumnDefinition.ColumnType.Float)); columns.add(new Data2DColumn(isChinese ? "实际成本(元)" : "Actual cost(Yuan)", ColumnDefinition.ColumnType.Float)); columns.add(new Data2DColumn(isChinese ? "实际产出" : "Actual results", ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(message(lang, "Recorder"), ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(message(lang, "RecordTime"), ColumnDefinition.ColumnType.Datetime)); data.setColumns(columns).setDataName(isChinese ? "成本记录" : "Cost Records"); return data; } public static DataFileCSV VerificationRecord(String lang) { boolean isChinese = Languages.isChinese(lang); DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(isChinese ? "任务编号" : "Task ID", ColumnDefinition.ColumnType.String, true).setWidth(140)); columns.add(new Data2DColumn(isChinese ? "事项" : "Item", ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(isChinese ? "通过" : "Pass", ColumnDefinition.ColumnType.Boolean)); columns.add(new Data2DColumn(isChinese ? "严重性" : "Severity", ColumnDefinition.ColumnType.Integer)); columns.add(new Data2DColumn(message(lang, "Description"), ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(isChinese ? "影响" : "Effects", ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(isChinese ? "建议" : "Suggestions", ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(isChinese ? "检验者" : "Verifier", ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(isChinese ? "检验时间" : "Verification time", ColumnDefinition.ColumnType.Datetime)); data.setColumns(columns).setDataName(isChinese ? "检验记录" : "Verify Record"); return data; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data2d/example/SoftwareTesting.java
released/MyBox/src/main/java/mara/mybox/data2d/example/SoftwareTesting.java
package mara.mybox.data2d.example; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import javafx.event.ActionEvent; import javafx.scene.control.Menu; import javafx.scene.control.MenuItem; import mara.mybox.controller.BaseController; import mara.mybox.controller.BaseData2DLoadController; import mara.mybox.data.FunctionsList; import mara.mybox.data.StringTable; import mara.mybox.data2d.DataFileCSV; import static mara.mybox.data2d.example.Data2DExampleTools.makeExampleFile; import mara.mybox.db.data.ColumnDefinition; import mara.mybox.db.data.Data2DColumn; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.style.StyleTools; import mara.mybox.tools.DateTools; import mara.mybox.tools.FileTmpTools; import mara.mybox.value.Languages; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2022-9-15 * @License Apache License Version 2.0 */ public class SoftwareTesting { public static Menu menu(String lang, BaseData2DLoadController controller) { try { Menu stMenu = new Menu(message(lang, "SoftwareTesting"), StyleTools.getIconImageView("iconVerify.png")); MenuItem menu = new MenuItem(message(lang, "TestEnvironment")); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = TestEnvironment(lang); if (makeExampleFile("ST_TestEnvironment_" + lang, data)) { controller.loadDef(data); } }); stMenu.getItems().add(menu); menu = new MenuItem(message(lang, "CompatibilityTesting")); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = CompatibilityTesting(lang); if (makeExampleFile("ST_CompatibilityTesting_" + lang, data)) { controller.loadDef(data); } }); stMenu.getItems().add(menu); menu = new MenuItem(message(lang, "DetailedTesting")); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = DetailedTesting(lang); if (makeExampleFile("ST_DetailedTesting_" + lang, data)) { controller.loadDef(data); } }); stMenu.getItems().add(menu); menu = new MenuItem(message(lang, "MyBoxBaseVerificationList")); menu.setOnAction((ActionEvent event) -> { DataFileCSV data = MyBoxBaseVerificationList(controller, lang, UserConfig.getBoolean("Data2DExampleImportDefinitionOnly", false)); controller.loadDef(data); }); stMenu.getItems().add(menu); return stMenu; } catch (Exception e) { MyBoxLog.error(e); return null; } } /* exmaples of data 2D definition */ public static DataFileCSV TestEnvironment(String lang) { DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(message(lang, "Title"), ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(message(lang, "Hardwares"), ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn("CPU", ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(message(lang, "Memory"), ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(message(lang, "OS"), ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(message(lang, "Softwares"), ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(message(lang, "Language"), ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(message(lang, "Target"), ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(message(lang, "Comments"), ColumnDefinition.ColumnType.String)); data.setColumns(columns).setDataName(message(lang, "TestEnvironment")); return data; } public static DataFileCSV CompatibilityTesting(String lang) { DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(message(lang, "TestEnvironment"), ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(message(lang, "Item"), ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(message(lang, "ModifyTime"), ColumnDefinition.ColumnType.Datetime)); columns.add(new Data2DColumn(message(lang, "Description"), ColumnDefinition.ColumnType.String)); data.setColumns(columns).setDataName(message(lang, "CompatibilityTesting")); return data; } public static DataFileCSV DetailedTesting(String lang) { DataFileCSV data = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(message(lang, "TestEnvironment"), ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(message(lang, "Version"), ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(message(lang, "Type"), ColumnDefinition.ColumnType.EnumerationEditable) .setFormat("\n" + message(lang, "Function") + "\n" + message(lang, "UserInterface") + "\n" + message(lang, "Bundary") + "\n" + message(lang, "Invalid") + "\n" + message(lang, "Data") + "\n" + message(lang, "API") + "\n" + message(lang, "IO") + "\n" + message(lang, "Exception") + "\n" + message(lang, "Performance") + "\n" + message(lang, "Robustness") + "\n" + message(lang, "Usability") + "\n" + message(lang, "Compatibility") + "\n" + message(lang, "Security") + "\n" + message(lang, "Document"))); columns.add(new Data2DColumn(message(lang, "Object"), ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(message(lang, "Title"), ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(message(lang, "Steps"), ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(message(lang, "Status"), ColumnDefinition.ColumnType.EnumerationEditable) .setFormat("\n" + message(lang, "NotTested") + "\n" + message(lang, "Testing") + "\n" + message(lang, "Success") + "\n" + message(lang, "Fail"))); columns.add(new Data2DColumn(message(lang, "ModifyTime"), ColumnDefinition.ColumnType.Datetime)); columns.add(new Data2DColumn(message(lang, "Description"), ColumnDefinition.ColumnType.String)); data.setColumns(columns).setDataName(message(lang, "DetailedTesting")); return data; } public static DataFileCSV MyBoxBaseVerificationList(BaseController controller, String lang, boolean onlyDef) { try { boolean isChinese = Languages.isChinese(lang); DataFileCSV targetData = new DataFileCSV(); List<Data2DColumn> columns = new ArrayList<>(); columns.add(new Data2DColumn(message(lang, "Index"), ColumnDefinition.ColumnType.Integer)); columns.add(new Data2DColumn(message(lang, "HierarchyNumber"), ColumnDefinition.ColumnType.String)); for (int i = 1; i <= FunctionsList.MaxLevel; i++) { columns.add(new Data2DColumn(message(lang, "Level") + " " + i, ColumnDefinition.ColumnType.String)); } for (Data2DColumn c : columns) { c.setEditable(false); } int preSize = columns.size(); columns.add(0, new Data2DColumn(message(lang, "TestEnvironment"), ColumnDefinition.ColumnType.String)); String defauleValue = ""; String format = defauleValue + "\n" + message(lang, "Success") + "\n" + message(lang, "Fail"); columns.add(new Data2DColumn(isChinese ? "打开界面" : "Open interface", ColumnDefinition.ColumnType.EnumerationEditable) .setFormat(format)); columns.add(new Data2DColumn(isChinese ? "正常值" : "Normal values", ColumnDefinition.ColumnType.EnumerationEditable) .setFormat(format)); columns.add(new Data2DColumn(isChinese ? "正常操作" : "Normal operations", ColumnDefinition.ColumnType.EnumerationEditable) .setFormat(format)); columns.add(new Data2DColumn(isChinese ? "正常结果" : "Normal results", ColumnDefinition.ColumnType.EnumerationEditable) .setFormat(format)); columns.add(new Data2DColumn(isChinese ? "边界值" : "Boundary values", ColumnDefinition.ColumnType.EnumerationEditable) .setFormat(format)); columns.add(new Data2DColumn(isChinese ? "异常值" : "Abnormal values", ColumnDefinition.ColumnType.EnumerationEditable) .setFormat(format)); columns.add(new Data2DColumn(isChinese ? "异常操作" : "Abnormal operations", ColumnDefinition.ColumnType.EnumerationEditable) .setFormat(format)); columns.add(new Data2DColumn(isChinese ? "异常结果" : "Exception results", ColumnDefinition.ColumnType.EnumerationEditable) .setFormat(format)); columns.add(new Data2DColumn(isChinese ? "提示" : "Tips", ColumnDefinition.ColumnType.EnumerationEditable) .setFormat(format)); columns.add(new Data2DColumn(isChinese ? "按钮" : "Buttons", ColumnDefinition.ColumnType.EnumerationEditable) .setFormat(format)); columns.add(new Data2DColumn(isChinese ? "快捷键" : "Shortcuts", ColumnDefinition.ColumnType.EnumerationEditable) .setFormat(format)); columns.add(new Data2DColumn(isChinese ? "菜单" : "Menu", ColumnDefinition.ColumnType.EnumerationEditable) .setFormat(format)); columns.add(new Data2DColumn(isChinese ? "响应时间" : "Response time", ColumnDefinition.ColumnType.EnumerationEditable) .setFormat(format)); columns.add(new Data2DColumn(isChinese ? "内存占用" : "Memory occupied", ColumnDefinition.ColumnType.EnumerationEditable) .setFormat(format)); columns.add(new Data2DColumn(isChinese ? "检验者" : "Verifier", ColumnDefinition.ColumnType.String)); columns.add(new Data2DColumn(message(lang, "ModifyTime"), ColumnDefinition.ColumnType.Datetime)); columns.add(new Data2DColumn(message(lang, "Description"), ColumnDefinition.ColumnType.String)); String dataName = message(lang, "MyBoxBaseVerificationList") + " - " + DateTools.nowString(); targetData.setColumns(columns).setDataName(dataName); File targetFile = FileTmpTools.generateFile(dataName, "csv"); if (targetFile.exists()) { targetFile.delete(); } Charset charset = Charset.forName("utf-8"); try (BufferedWriter writer = new BufferedWriter(new FileWriter(targetFile, charset, false))) { String header = null; for (Data2DColumn column : columns) { String name = "\"" + column.getColumnName() + "\""; if (header == null) { header = name; } else { header += "," + name; } } writer.write(header + System.lineSeparator()); if (!onlyDef) { FunctionsList list = new FunctionsList(controller, false, lang); StringTable table = list.make(); if (table == null) { return null; } String values = ""; for (int i = 0; i < columns.size() - preSize; i++) { values += "," + defauleValue; } String line; for (List<String> row : table.getData()) { line = "win"; for (String v : row) { line += "," + v; } writer.write(line + values + System.lineSeparator()); } } writer.flush(); } catch (Exception e) { MyBoxLog.error(e); return null; } targetData.setFile(targetFile).setHasHeader(true).setCharset(charset).setDelimiter(","); targetData.saveAttributes(); return targetData; } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data/BytesEditInformation.java
released/MyBox/src/main/java/mara/mybox/data/BytesEditInformation.java
package mara.mybox.data; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.tools.ByteTools; import mara.mybox.tools.FileTmpTools; import mara.mybox.tools.FileTools; import mara.mybox.tools.StringTools; /** * @Author Mara * @CreateDate 2018-12-10 13:06:33 * @License Apache License Version 2.0 */ public class BytesEditInformation extends FileEditInformation { public BytesEditInformation() { editType = Edit_Type.Bytes; } public BytesEditInformation(File file) { super(file); editType = Edit_Type.Bytes; initValues(); } @Override public boolean readTotalNumbers(FxTask currentTask) { try { if (file == null) { return false; } pagination.objectsNumber = 0; pagination.rowsNumber = 0; pagination.pagesNumber = 1; boolean byWidth = lineBreak == Line_Break.Width && lineBreakWidth > 0; if (!byWidth && lineBreakValue == null) { return false; } long byteIndex = 0, totalLBNumber = 0; try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file))) { int bufSize = FileTools.bufSize(file, 16), bufLen; byte[] buf = new byte[bufSize]; while ((bufLen = inputStream.read(buf)) > 0) { if (currentTask != null && !currentTask.isWorking()) { return false; } if (bufLen < bufSize) { buf = ByteTools.subBytes(buf, 0, bufLen); } byteIndex += bufLen; if (!byWidth) { totalLBNumber += FindReplaceString.count(currentTask, ByteTools.bytesToHexFormat(buf), lineBreakValue); } } } pagination.objectsNumber = byteIndex; pagination.pagesNumber = pagination.objectsNumber / pagination.pageSize; if (pagination.objectsNumber % pagination.pageSize > 0) { pagination.pagesNumber++; } if (byWidth) { pagination.rowsNumber = pagination.objectsNumber / lineBreakWidth + 1; } else { pagination.rowsNumber = totalLBNumber + 1; } totalNumberRead = true; return true; } catch (Exception e) { MyBoxLog.debug(e); return false; } } @Override public String readPage(FxTask currentTask, long pageNumber) { return readObjects(currentTask, pageNumber * pagination.pageSize, pagination.pageSize); } @Override public String readObjects(FxTask currentTask, long from, long number) { if (file == null || pagination.pageSize <= 0 || from < 0 || number < 0 || (pagination.objectsNumber > 0 && from >= pagination.objectsNumber)) { return null; } boolean byWidth = lineBreak == Line_Break.Width && lineBreakWidth > 0; if (!byWidth && lineBreakValue == null) { return null; } String bufHex = null; long pageNumber = from / pagination.pageSize, byteIndex = 0, totalLBNumber = 0, pageLBNumber = 0, pageIndex = 0; int bufLen; try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file))) { int bufSize; byte[] buf; boolean isCurrentPage; while (true) { if (currentTask != null && !currentTask.isWorking()) { return null; } isCurrentPage = pageIndex++ == pageNumber; if (isCurrentPage) { bufSize = (int) (Math.max(pagination.pageSize, from - pageNumber * pagination.pageSize + number)); } else { bufSize = pagination.pageSize; } buf = new byte[bufSize]; bufLen = inputStream.read(buf); if (bufLen <= 0) { break; } if (bufLen < bufSize) { buf = ByteTools.subBytes(buf, 0, bufLen); } byteIndex += bufLen; if (!byWidth) { bufHex = ByteTools.bytesToHexFormat(buf); pageLBNumber = FindReplaceString.count(currentTask, bufHex, lineBreakValue); if (currentTask != null && !currentTask.isWorking()) { return null; } totalLBNumber += pageLBNumber; } if (isCurrentPage) { if (bufHex == null) { bufHex = ByteTools.bytesToHexFormat(buf); } break; } } } catch (Exception e) { MyBoxLog.debug(e); return null; } if (currentTask != null && !currentTask.isWorking()) { return null; } if (bufHex == null) { return null; } pagination.currentPage = pageNumber; pagination.startObjectOfCurrentPage = byteIndex - bufLen; pagination.endObjectOfCurrentPage = byteIndex; if (byWidth) { pagination.startRowOfCurrentPage = pagination.startObjectOfCurrentPage / lineBreakWidth; pagination.endRowOfCurrentPage = pagination.endObjectOfCurrentPage / lineBreakWidth + 1; } else { pagination.startRowOfCurrentPage = totalLBNumber - pageLBNumber; pagination.endRowOfCurrentPage = totalLBNumber + 1; } return bufHex; } @Override public String readObject(FxTask currentTask, long index) { return readObjects(currentTask, index, 1); } @Override public String readLines(FxTask currentTask, long from, long number) { if (file == null || from < 0 || number < 0 || (pagination.rowsNumber > 0 && from >= pagination.rowsNumber)) { return null; } boolean byWidth = lineBreak == Line_Break.Width && lineBreakWidth > 0; if (!byWidth && lineBreakValue == null) { return null; } long byteIndex = 0, totalLBNumber = 0, pageLBNumber = 0, fromLBNumber = 0, fromByteIndex = 0; String pageHex = null; int bufLen; try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file))) { byte[] buf = new byte[(int) pagination.pageSize]; long lbEnd = Math.min(from + number, pagination.rowsNumber) - 1; String bufHex; while ((bufLen = inputStream.read(buf)) > 0) { if (currentTask != null && !currentTask.isWorking()) { return null; } if (bufLen < pagination.pageSize) { buf = ByteTools.subBytes(buf, 0, bufLen); } bufHex = ByteTools.bytesToHexFormat(buf); byteIndex += bufLen; if (byWidth) { totalLBNumber = byteIndex / lineBreakWidth; } else { pageLBNumber = FindReplaceString.count(currentTask, bufHex, lineBreakValue); if (currentTask != null && !currentTask.isWorking()) { return null; } totalLBNumber += pageLBNumber; } if (totalLBNumber >= from) { if (pageHex == null) { pageHex = bufHex; fromLBNumber = totalLBNumber - pageLBNumber; fromByteIndex = byteIndex - bufLen; } else { pageHex += bufHex; } if (totalLBNumber >= lbEnd) { break; } } } } catch (Exception e) { MyBoxLog.debug(e); return null; } if (currentTask != null && !currentTask.isWorking()) { return null; } if (pageHex == null) { return null; } pagination.currentPage = fromByteIndex / pagination.pageSize; pagination.startObjectOfCurrentPage = fromByteIndex; pagination.endObjectOfCurrentPage = byteIndex; if (byWidth) { pagination.startRowOfCurrentPage = fromByteIndex / lineBreakWidth; pagination.endRowOfCurrentPage = byteIndex / lineBreakWidth + 1; } else { pagination.startRowOfCurrentPage = fromLBNumber; pagination.endRowOfCurrentPage = totalLBNumber + 1; } return pageHex; } @Override public File filter(FxTask currentTask, boolean recordLineNumbers) { try { if (file == null || filterStrings == null || filterStrings.length == 0) { return file; } boolean lbWidth = (lineBreak == Line_Break.Width && lineBreakWidth > 0); if (!lbWidth && lineBreakValue == null) { return null; } File targetFile = FileTmpTools.getTempFile(); int lineEnd = 0, lineStart = 0; try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file)); BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(targetFile)); OutputStreamWriter writer = new OutputStreamWriter(outputStream, "UTF-8")) { byte[] buf = new byte[pagination.pageSize]; int bufLen; String pageHex; while ((bufLen = inputStream.read(buf)) > 0) { if (currentTask != null && !currentTask.isWorking()) { return null; } if (bufLen < pagination.pageSize) { buf = ByteTools.subBytes(buf, 0, bufLen); } pageHex = ByteTools.bytesToHexFormat(buf); pageHex = ByteTools.formatHex(pageHex, lineBreak, lineBreakWidth, lineBreakValue); String[] lines = pageHex.split("\n"); lineEnd = lineStart + lines.length - 1; for (int i = 0; i < lines.length; ++i) { if (currentTask != null && !currentTask.isWorking()) { return null; } lines[i] += " "; if (isMatchFilters(lines[i])) { if (recordLineNumbers) { String lineNumber = StringTools.fillRightBlank(lineStart + i, 15); writer.write(lineNumber + " " + lines[i] + System.lineSeparator()); } else { writer.write(lines[i] + System.lineSeparator()); } } } if (lbWidth) { lineStart = lineEnd + 1; } else { lineStart = lineEnd; } } } return targetFile; } catch (Exception e) { MyBoxLog.debug(e); return null; } } @Override public boolean writeObject(FxTask currentTask, String hex) { try { if (file == null || charset == null || hex == null || hex.isEmpty()) { return false; } try (BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(file))) { byte[] bytes = ByteTools.hexFormatToBytes(hex); outputStream.write(bytes); } return true; } catch (Exception e) { MyBoxLog.debug(e); return false; } } @Override public boolean writePage(FxTask currentTask, FileEditInformation sourceInfo, String hex) { try { MyBoxLog.console(file); if (file == null || hex == null || hex.isEmpty() || sourceInfo.getFile() == null || sourceInfo.getCharset() == null) { return false; } int psize = sourceInfo.pagination.pageSize; long pageStartByte = sourceInfo.pagination.startObjectOfCurrentPage, pLen = sourceInfo.pagination.endObjectOfCurrentPage - pageStartByte; if (psize <= 0 || pageStartByte < 0 || pLen <= 0) { return false; } File targetFile = file; if (sourceInfo.getFile().equals(file)) { targetFile = FileTmpTools.getTempFile(); } try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(sourceInfo.getFile())); BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(targetFile))) { int bufSize, bufLen; byte[] buf; long byteIndex = 0; while (true) { if (currentTask != null && !currentTask.isWorking()) { return false; } if (byteIndex < pageStartByte) { bufSize = (int) Math.min(psize, pageStartByte - byteIndex); } else if (byteIndex == pageStartByte) { outputStream.write(ByteTools.hexFormatToBytes(hex)); inputStream.skip(pLen); byteIndex += pLen; continue; } else { bufSize = psize; } buf = new byte[bufSize]; bufLen = inputStream.read(buf); if (bufLen <= 0) { break; } if (bufLen < bufSize) { buf = ByteTools.subBytes(buf, 0, bufLen); } outputStream.write(buf); byteIndex += bufLen; } } if (currentTask != null && !currentTask.isWorking()) { return false; } if (sourceInfo.getFile().equals(file)) { FileTools.override(targetFile, file); } return true; } catch (Exception e) { MyBoxLog.debug(e); return false; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data/FindReplaceTextFile.java
released/MyBox/src/main/java/mara/mybox/data/FindReplaceTextFile.java
package mara.mybox.data; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.OutputStreamWriter; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javafx.scene.control.IndexRange; import mara.mybox.data.FindReplaceString.Operation; import mara.mybox.data2d.DataFileCSV; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.tools.CsvTools; import mara.mybox.tools.FileTmpTools; import mara.mybox.tools.FileTools; import static mara.mybox.value.Languages.message; import org.apache.commons.csv.CSVPrinter; /** * @Author Mara * @CreateDate 2020-11-9 * @License Apache License Version 2.0 */ public class FindReplaceTextFile { public static boolean countText(FxTask currentTask, FileEditInformation sourceInfo, FindReplaceFile findReplaceFile) { if (sourceInfo == null || sourceInfo.getFile() == null || sourceInfo.getCharset() == null || sourceInfo.getLineBreakValue() == null || findReplaceFile == null || findReplaceFile.getFindString() == null || findReplaceFile.getFindString().isEmpty()) { if (findReplaceFile != null) { findReplaceFile.setError(message("InvalidParameters")); } return false; } sourceInfo.setFindReplace(findReplaceFile); findReplaceFile.setFileInfo(sourceInfo); int count = 0; File sourceFile = sourceInfo.getFile(); int maxLen = FileTools.bufSize(sourceFile, 16); String findString = findReplaceFile.getFindString(); FindReplaceString findReplaceString = findReplaceFile.findReplaceString() .setFindString(findString).setAnchor(0).setWrap(false); int findLen = findReplaceFile.isIsRegex() ? maxLen : findString.length(); int backFrom, textLen, backLen = 0; StringBuilder s = new StringBuilder(); String text, checkString, backString = ""; boolean moreLine = false; try (BufferedReader reader = new BufferedReader(new FileReader(sourceFile, sourceInfo.getCharset()))) { String line; while ((line = reader.readLine()) != null) { if (currentTask != null && !currentTask.isWorking()) { return false; } if (moreLine) { line = "\n" + line; } else { moreLine = true; } s.append(line); textLen = s.length(); if (textLen + backLen < maxLen) { // read as more as possible continue; } text = s.toString(); checkString = backString.concat(text); findReplaceString.setInputString(checkString) .setAnchor(0).handleString(currentTask); if (currentTask != null && !currentTask.isWorking()) { return false; } IndexRange lastRange = findReplaceString.getStringRange(); if (lastRange != null) { count += findReplaceString.getCount(); if (lastRange.getEnd() == checkString.length()) { backString = ""; } else { backFrom = Math.max(lastRange.getStart() - backLen + 1, Math.max(1, textLen - findLen + 1)); backString = text.substring(backFrom, textLen); } } else { backFrom = Math.max(1, textLen - findLen + 1); backString = text.substring(backFrom, textLen); } backLen = backString.length(); s = new StringBuilder(); } if (!s.isEmpty()) { findReplaceString.setInputString(backString.concat(s.toString())) .handleString(currentTask); if (currentTask != null && !currentTask.isWorking()) { return false; } IndexRange lastRange = findReplaceString.getStringRange(); if (lastRange != null) { count += findReplaceString.getCount(); } } findReplaceFile.setCount(count); return true; } catch (Exception e) { MyBoxLog.debug(e); return false; } } public static boolean findNextText(FxTask currentTask, FileEditInformation sourceInfo, FindReplaceFile findReplaceFile) { try { LongRange found = findNextTextRange(currentTask, sourceInfo, findReplaceFile); if (currentTask != null && !currentTask.isWorking()) { return false; } if (found == null) { return findReplaceFile != null && findReplaceFile.getError() == null; } String pageText = sourceInfo.readObjects(currentTask, found.getStart(), found.getLength()); if (currentTask != null && !currentTask.isWorking()) { return false; } IndexRange stringRange = pageRange(findReplaceFile); if (stringRange == null) { findReplaceFile.setError(message("InvalidData")); return false; } findReplaceFile.setFileRange(found); findReplaceFile.setStringRange(stringRange); findReplaceFile.setOuputString(pageText); return true; } catch (Exception e) { findReplaceFile.setError(e.toString()); MyBoxLog.debug(e); return false; } } public static LongRange findNextTextRange(FxTask currentTask, FileEditInformation sourceInfo, FindReplaceFile findReplaceFile) { if (sourceInfo == null || sourceInfo.getFile() == null || sourceInfo.getCharset() == null || sourceInfo.getLineBreakValue() == null || findReplaceFile == null || findReplaceFile.getFindString() == null || findReplaceFile.getFindString().isEmpty()) { if (findReplaceFile != null) { findReplaceFile.setError(message("InvalidParameters")); } return null; } findReplaceFile.setError(null); findReplaceFile.setFileRange(null); findReplaceFile.setStringRange(null); try { sourceInfo.setFindReplace(findReplaceFile); findReplaceFile.setFileInfo(sourceInfo); File sourceFile = sourceInfo.getFile(); Charset charset = sourceInfo.getCharset(); long fileLength = sourceFile.length(); long startPosition = findReplaceFile.getPosition(); if (startPosition < 0 || startPosition >= fileLength) { if (findReplaceFile.isWrap()) { startPosition = 0; } else { // findReplaceFile.setError(message("InvalidParameters")); return null; } } int maxLen = FileTools.bufSize(sourceFile, 16); String findString = findReplaceFile.getFindString(); FindReplaceString findReplaceString = findReplaceFile.findReplaceString() .setAnchor(0).setWrap(false).setFindString(findString); int findLen = findReplaceFile.isIsRegex() ? maxLen : findString.length(); LongRange found = findNextTextRange(currentTask, sourceFile, charset, findReplaceString, startPosition, fileLength, findLen); if (currentTask != null && !currentTask.isWorking()) { return null; } if (found == null && findReplaceString.getError() != null) { findReplaceFile.setError(findReplaceString.getError()); return null; } if (found == null && findReplaceFile.isWrap() && startPosition > 0 && startPosition < fileLength) { long endPosition; if (findReplaceFile.isIsRegex()) { endPosition = fileLength; } else { endPosition = startPosition + findLen; } found = findNextTextRange(currentTask, sourceFile, charset, findReplaceString, 0, endPosition, findLen); if (currentTask != null && !currentTask.isWorking()) { return null; } if (found == null && findReplaceString.getError() != null) { findReplaceFile.setError(findReplaceString.getError()); return null; } } findReplaceFile.setFileRange(found); return found; } catch (Exception e) { MyBoxLog.debug(e); findReplaceFile.setError(e.toString()); return null; } } public static LongRange findNextTextRange(FxTask currentTask, File file, Charset charset, FindReplaceString findReplaceString, long startPosition, long endPosition, int findLen) { if (file == null || charset == null || findReplaceString == null || startPosition >= endPosition) { return null; } findReplaceString.setError(null); findReplaceString.setStringRange(null); try (BufferedReader reader = new BufferedReader(new FileReader(file, charset))) { String line; LongRange found = null; int charIndex = 0, textLen, lineLen, backLen = 0, keepLen; StringBuilder s = new StringBuilder(); String text, backString = ""; boolean moreLine = false, skipped = startPosition <= 0; long textStart = startPosition; IndexRange range; while ((line = reader.readLine()) != null) { if (currentTask != null && !currentTask.isWorking()) { return null; } if (moreLine) { line = "\n" + line; } else { moreLine = true; } lineLen = line.length(); charIndex += lineLen; if (!skipped) { keepLen = (int) (charIndex - startPosition); if (keepLen < 0) { continue; } s = new StringBuilder(); if (keepLen > 0) { // start from startPosition s.append(line.substring((int) (lineLen - keepLen), lineLen)); } textLen = s.length(); skipped = true; } else { s.append(line); textLen = s.length(); } keepLen = (int) (charIndex - endPosition); if (keepLen < 0 && textLen + backLen < findLen) { // find as early as possible continue; } if (keepLen > 0) { // end at endPosition s.delete((int) (textLen - keepLen), textLen); textLen = s.length(); } text = s.toString(); findReplaceString.setInputString(backString.concat(text)) .setAnchor(0).handleString(currentTask); if (currentTask != null && !currentTask.isWorking()) { return null; } range = findReplaceString.getStringRange(); if (range != null) { found = new LongRange(); found.setStart(textStart + range.getStart() - backLen); found.setEnd(found.getStart() + range.getLength()); break; } else { // backword some string to match each possible backString = text.substring(Math.max(1, textLen - findLen + 1), textLen); backLen = backString.length(); } textStart += textLen; s = new StringBuilder(); if (keepLen >= 0) { break; } } if (currentTask != null && !currentTask.isWorking()) { return null; } textLen = s.length(); if (found == null && textLen > 0 && charIndex >= startPosition && charIndex < endPosition) { keepLen = (int) (charIndex - endPosition); if (keepLen > 0) { s.delete((int) (textLen - keepLen), textLen); } findReplaceString.setInputString(backString.concat(s.toString())) .setAnchor(0).handleString(currentTask); if (currentTask != null && !currentTask.isWorking()) { return null; } range = findReplaceString.getStringRange(); if (range != null) { found = new LongRange(); found.setStart(textStart + range.getStart() - backLen); found.setEnd(found.getStart() + range.getLength()); } } return found; } catch (Exception e) { MyBoxLog.debug(e); findReplaceString.setError(e.toString()); return null; } } public static boolean findPreviousText(FxTask currentTask, FileEditInformation sourceInfo, FindReplaceFile findReplaceFile) { try { LongRange found = findPreviousTextRange(currentTask, sourceInfo, findReplaceFile); if (currentTask != null && !currentTask.isWorking()) { return false; } if (found == null) { return findReplaceFile != null && findReplaceFile.getError() == null; } String pageText = sourceInfo.readObjects(currentTask, found.getStart(), found.getLength()); if (currentTask != null && !currentTask.isWorking()) { return false; } IndexRange stringRange = pageRange(findReplaceFile); if (stringRange == null) { findReplaceFile.setError(message("InvalidData")); return false; } findReplaceFile.setFileRange(found); findReplaceFile.setStringRange(stringRange); findReplaceFile.setOuputString(pageText); return true; } catch (Exception e) { MyBoxLog.debug(e); findReplaceFile.setError(e.toString()); return false; } } public static LongRange findPreviousTextRange(FxTask currentTask, FileEditInformation sourceInfo, FindReplaceFile findReplaceFile) { if (sourceInfo == null || sourceInfo.getFile() == null || sourceInfo.getCharset() == null || sourceInfo.getLineBreakValue() == null || findReplaceFile == null || findReplaceFile.getFindString() == null || findReplaceFile.getFindString().isEmpty()) { if (findReplaceFile != null) { findReplaceFile.setError(message("InvalidParameters")); } return null; } findReplaceFile.setError(null); findReplaceFile.setFileRange(null); findReplaceFile.setStringRange(null); try { sourceInfo.setFindReplace(findReplaceFile); findReplaceFile.setFileInfo(sourceInfo); File sourceFile = sourceInfo.getFile(); Charset charset = sourceInfo.getCharset(); long fileLength = sourceFile.length(); long endPostion = findReplaceFile.getPosition(); if (endPostion <= 0 || endPostion > fileLength) { if (findReplaceFile.isWrap()) { endPostion = fileLength; } else { // findReplaceFile.setError(message("InvalidParameters")); return null; } } int maxLen = FileTools.bufSize(sourceFile, 16); String findString = findReplaceFile.getFindString(); FindReplaceString findReplaceString = findReplaceFile.findReplaceString() .setFindString(findString).setAnchor(0).setWrap(false); int findLen = findReplaceFile.isIsRegex() ? maxLen : findString.length(); LongRange found = findPreviousTextRange(currentTask, sourceFile, charset, findReplaceString, 0, endPostion, maxLen, findLen); if (currentTask != null && !currentTask.isWorking()) { return null; } if (found == null && findReplaceString.getError() != null) { findReplaceFile.setError(findReplaceString.getError()); return null; } if (found == null && findReplaceFile.isWrap() && endPostion > 0 && endPostion <= fileLength) { long startPosition; if (findReplaceFile.isIsRegex()) { startPosition = 0; } else { startPosition = Math.max(0, endPostion - findLen); } found = findPreviousTextRange(currentTask, sourceFile, charset, findReplaceString, startPosition, fileLength, maxLen, findLen); if (currentTask != null && !currentTask.isWorking()) { return null; } if (found == null && findReplaceString.getError() != null) { findReplaceFile.setError(findReplaceString.getError()); return null; } } findReplaceFile.setFileRange(found); return found; } catch (Exception e) { findReplaceFile.setError(e.toString()); MyBoxLog.debug(e); return null; } } public static LongRange findPreviousTextRange(FxTask currentTask, File file, Charset charset, FindReplaceString findReplaceString, long startPosition, long endPosition, long maxLen, int findLen) { if (file == null || charset == null || findReplaceString == null) { return null; } findReplaceString.setError(null); findReplaceString.setStringRange(null); try (BufferedReader reader = new BufferedReader(new FileReader(file, charset))) { String line; LongRange found = null; int backFrom, textLen, backLen = 0, checkLen, lineLen, keepLen; StringBuilder s = new StringBuilder(); String text, backString = "", checkString; boolean moreLine = false, skipped = startPosition <= 0; long charIndex = 0, textStart = startPosition; IndexRange range; while ((line = reader.readLine()) != null) { if (currentTask != null && !currentTask.isWorking()) { return null; } if (moreLine) { line = "\n" + line; } else { moreLine = true; } lineLen = line.length(); charIndex += lineLen; if (!skipped) { // start from startPosition keepLen = (int) (charIndex - startPosition); if (keepLen < 0) { continue; } s = new StringBuilder(); if (keepLen > 0) { s.append(line.substring((int) (lineLen - keepLen), lineLen)); } textLen = s.length(); skipped = true; } else { s.append(line); textLen = s.length(); } keepLen = (int) (charIndex - endPosition); // end at startPosition if (keepLen < 0 && textLen + backLen < maxLen) { // read as more as possible continue; } if (keepLen > 0) { s.delete((int) (textLen - keepLen), textLen); textLen = s.length(); } text = s.toString(); checkString = backString.concat(text); checkLen = checkString.length(); findReplaceString.setInputString(checkString).setAnchor(checkLen) .handleString(currentTask); if (currentTask != null && !currentTask.isWorking()) { return null; } range = findReplaceString.getStringRange(); if (range != null) { found = new LongRange(); found.setStart(textStart + range.getStart() - backLen); found.setEnd(found.getStart() + range.getLength()); if (range.getEnd() == checkLen) { backString = ""; } else { backFrom = Math.max(1, textLen - findLen + 1); backFrom = Math.max(range.getStart() - backLen + 1, backFrom); backString = text.substring(backFrom, textLen); } } else { backFrom = Math.max(1, textLen - findLen + 1); backString = text.substring(backFrom, textLen); } backLen = backString.length(); textStart += textLen; s = new StringBuilder(); if (keepLen >= 0) { break; } } if (currentTask != null && !currentTask.isWorking()) { return null; } textLen = s.length(); if (found == null && textLen > 0 && charIndex >= startPosition && charIndex < endPosition) { keepLen = (int) (charIndex - endPosition); if (keepLen > 0) { s.delete((int) (textLen - keepLen), textLen); } checkString = backString.concat(s.toString()); checkLen = checkString.length(); findReplaceString.setInputString(checkString) .setAnchor(checkLen).handleString(currentTask); if (currentTask != null && !currentTask.isWorking()) { return null; } range = findReplaceString.getStringRange(); if (range != null) { found = new LongRange(); found.setStart(textStart + range.getStart() - backLen); found.setEnd(found.getStart() + range.getLength()); } } return found; } catch (Exception e) { MyBoxLog.debug(e); findReplaceString.setError(e.toString()); return null; } } public static boolean replaceFirstText(FxTask currentTask, FileEditInformation sourceInfo, FindReplaceFile findReplaceFile) { try { if (findReplaceFile == null) { return false; } String replaceString = findReplaceFile.getReplaceString(); if (replaceString == null) { return false; } findReplaceFile.setOperation(Operation.FindNext); findNextText(currentTask, sourceInfo, findReplaceFile); if (currentTask != null && !currentTask.isWorking()) { return false; } IndexRange stringRange = findReplaceFile.getStringRange(); findReplaceFile.setOperation(Operation.ReplaceFirst); if (stringRange == null) { return false; } String pageText = findReplaceFile.getOutputString(); if (stringRange.getStart() < 0 || stringRange.getStart() > stringRange.getEnd() || stringRange.getEnd() > pageText.length()) { return false; } String output = pageText.substring(0, stringRange.getStart()) + replaceString + pageText.substring(stringRange.getEnd(), pageText.length()); findReplaceFile.setOuputString(output); return true; } catch (Exception e) { findReplaceFile.setError(e.toString()); MyBoxLog.debug(e); return false; } } public static boolean replaceAllText(FxTask currentTask, FileEditInformation sourceInfo, FindReplaceFile findReplaceFile) { if (sourceInfo == null || sourceInfo.getFile() == null || findReplaceFile == null || sourceInfo.getCharset() == null || sourceInfo.getLineBreakValue() == null || findReplaceFile.getFindString() == null || findReplaceFile.getFindString().isEmpty()) { if (findReplaceFile != null) { findReplaceFile.setError(message("InvalidParameters")); } return false; } int total = 0; findReplaceFile.setError(null); findReplaceFile.setFileRange(null); findReplaceFile.setStringRange(null); sourceInfo.setFindReplace(findReplaceFile); findReplaceFile.setFileInfo(sourceInfo); File sourceFile = sourceInfo.getFile(); File tmpFile = FileTmpTools.getTempFile(); // MyBoxLog.debug(sourceFile + " --> " + tmpFile); Charset charset = sourceInfo.getCharset(); try (BufferedReader reader = new BufferedReader(new FileReader(sourceFile, charset)); BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(tmpFile)); OutputStreamWriter writer = new OutputStreamWriter(outputStream, charset)) { String findString = findReplaceFile.getFindString(); String replaceString = findReplaceFile.getReplaceString(); FindReplaceString findReplaceString = findReplaceFile.findReplaceString() .setFindString(findString).setReplaceString(replaceString) .setAnchor(0).setWrap(false); int maxLen = FileTools.bufSize(sourceFile, 16); int findLen = findReplaceFile.isIsRegex() ? maxLen : findString.length(); int backFrom, textLen, backLen = 0, lastReplacedLength; // MyBoxLog.debug(" maxLen: " + maxLen + " findLen: " + findLen); StringBuilder s = new StringBuilder(); boolean moreLine = false; String line, replacedString, text, backString = "", checkedString; IndexRange range; while ((line = reader.readLine()) != null) { if (currentTask != null && !currentTask.isWorking()) { return false; } if (moreLine) { line = "\n" + line; } else { moreLine = true; } s.append(line); textLen = s.length(); if (textLen + backLen < maxLen) { // read as more as possible continue; } text = s.toString(); checkedString = backString.concat(text); findReplaceString.setInputString(checkedString) .setAnchor(0).handleString(currentTask); if (currentTask != null && !currentTask.isWorking()) { return false; } range = findReplaceString.getStringRange(); if (range != null) { replacedString = findReplaceString.getOutputString(); lastReplacedLength = findReplaceString.getLastReplacedLength(); writer.write(replacedString.substring(0, lastReplacedLength)); backString = replacedString.substring(lastReplacedLength, replacedString.length()); total += findReplaceString.getCount(); // MyBoxLog.debug(replacedString.length() + " " + lastReplacedLength + " " + backString.length() + " " + findReplaceString.getCount()); } else { if (!backString.isEmpty()) { writer.write(backString); } backFrom = Math.max(1, textLen - findLen + 1); backString = text.substring(backFrom, textLen); writer.write(text.substring(0, backFrom)); } backLen = backString.length(); s = new StringBuilder(); } if (currentTask != null && !currentTask.isWorking()) { return false; } if (!s.isEmpty()) { // MyBoxLog.debug(backString.length() + " " + s.toString().length()); findReplaceString.setInputString(backString.concat(s.toString())) .setAnchor(0).handleString(currentTask); if (currentTask != null && !currentTask.isWorking()) { return false; } // MyBoxLog.debug(findReplaceString.getOutputString().length()); writer.write(findReplaceString.getOutputString()); total += findReplaceString.getCount(); } findReplaceFile.setCount(total); } catch (Exception e) { MyBoxLog.debug(e); findReplaceFile.setError(e.toString()); return false; } if (tmpFile != null && tmpFile.exists()) { if (total > 0) { findReplaceFile.backup(currentTask, sourceFile); return FileTools.override(tmpFile, sourceFile); } else { return true; } } return false; } public static IndexRange pageRange(FindReplaceFile findReplace) { if (findReplace == null) { return null; } IndexRange pageRange = null; LongRange fileRange = findReplace.getFileRange(); FileEditInformation fileInfo = findReplace.getFileInfo(); if (fileRange != null && fileInfo != null) { long pageStart = fileInfo.pagination.startObjectOfCurrentPage * findReplace.getUnit(); pageRange = new IndexRange((int) (fileRange.getStart() - pageStart), (int) (fileRange.getEnd() - pageStart)); } findReplace.setStringRange(pageRange); return pageRange; } public static LongRange fileRange(FindReplaceFile findReplace) { if (findReplace == null) { return null; } LongRange fileRange = null; IndexRange pageRange = findReplace.getStringRange(); FileEditInformation fileInfo = findReplace.getFileInfo(); if (pageRange != null && fileInfo != null) { long pageStart = fileInfo.pagination.startObjectOfCurrentPage * findReplace.getUnit(); fileRange = new LongRange(pageRange.getStart() + pageStart, pageRange.getEnd() + pageStart); } findReplace.setFileRange(fileRange); return fileRange; } public static boolean findAllText(FxTask currentTask, FileEditInformation sourceInfo, FindReplaceFile findReplaceFile) { if (sourceInfo == null || sourceInfo.getFile() == null || sourceInfo.getCharset() == null || sourceInfo.getLineBreakValue() == null || findReplaceFile == null || findReplaceFile.getFindString() == null || findReplaceFile.getFindString().isEmpty()) { if (findReplaceFile != null) { findReplaceFile.setError(message("InvalidParameters")); } return false; } findReplaceFile.setError(null); findReplaceFile.setFileRange(null); findReplaceFile.setStringRange(null); findReplaceFile.setCount(0); findReplaceFile.setMatches(null); findReplaceFile.setMatchesData(null); sourceInfo.setFindReplace(findReplaceFile); findReplaceFile.setFileInfo(sourceInfo); File sourceFile = sourceInfo.getFile(); int maxLen = FileTools.bufSize(sourceFile, 16);
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
true
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data/FindReplaceBytesFile.java
released/MyBox/src/main/java/mara/mybox/data/FindReplaceBytesFile.java
package mara.mybox.data; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javafx.scene.control.IndexRange; import mara.mybox.data2d.DataFileCSV; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.tools.ByteTools; import mara.mybox.tools.CsvTools; import mara.mybox.tools.FileTmpTools; import mara.mybox.tools.FileTools; import static mara.mybox.value.Languages.message; import org.apache.commons.csv.CSVPrinter; /** * @Author Mara * @CreateDate 2020-11-9 * @License Apache License Version 2.0 */ public class FindReplaceBytesFile { public static boolean countBytes(FxTask currentTask, FileEditInformation sourceInfo, FindReplaceFile findReplaceFile) { if (sourceInfo == null || sourceInfo.getFile() == null || findReplaceFile == null || findReplaceFile.getFindString() == null || findReplaceFile.getFindString().isEmpty()) { if (findReplaceFile != null) { findReplaceFile.setError(message("InvalidParameters")); } return false; } sourceInfo.setFindReplace(findReplaceFile); findReplaceFile.setFileInfo(sourceInfo); int count = 0; File sourceFile = sourceInfo.getFile(); try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(sourceFile))) { int pageSize = FileTools.bufSize(sourceFile, 48); byte[] pageBytes = new byte[pageSize]; String findString = findReplaceFile.getFindString(); int findLen = findReplaceFile.isIsRegex() ? pageSize * 3 : findString.length(); FindReplaceString findReplaceString = findReplaceFile.findReplaceString() .setFindString(findString).setAnchor(0).setWrap(false); int bufLen, backFrom, hexLen; String pageHex, backString = "", checkedString; while ((bufLen = inputStream.read(pageBytes)) > 0) { if (currentTask != null && !currentTask.isWorking()) { return false; } if (bufLen < pageSize) { pageBytes = ByteTools.subBytes(pageBytes, 0, bufLen); } pageHex = ByteTools.bytesToHexFormat(pageBytes); hexLen = pageHex.length(); checkedString = backString + pageHex; findReplaceString.setInputString(checkedString).handleString(currentTask); if (currentTask != null && !currentTask.isWorking()) { return false; } IndexRange lastRange = findReplaceString.getStringRange(); if (lastRange != null) { count += findReplaceString.getCount(); if (lastRange.getEnd() == checkedString.length()) { backString = ""; } else { backFrom = Math.max(3, hexLen - findLen + 3); backFrom = Math.max(lastRange.getStart() - backString.length() + 3, backFrom); backString = pageHex.substring(backFrom, hexLen); } } else { backFrom = Math.max(3, hexLen - findLen + 3); backString = pageHex.substring(backFrom, hexLen); } } findReplaceFile.setCount(count); return true; } catch (Exception e) { MyBoxLog.debug(e); findReplaceFile.setError(e.toString()); return false; } } public static boolean findNextBytes(FxTask currentTask, FileEditInformation sourceInfo, FindReplaceFile findReplaceFile) { try { LongRange found = findNextBytesRange(currentTask, sourceInfo, findReplaceFile); if (currentTask != null && !currentTask.isWorking()) { return false; } if (found == null) { return findReplaceFile != null && findReplaceFile.getError() == null; } String pageText = sourceInfo.readObjects(currentTask, found.getStart() / 3, found.getLength() / 3); if (currentTask != null && !currentTask.isWorking()) { return false; } IndexRange stringRange = FindReplaceTextFile.pageRange(findReplaceFile); if (stringRange == null) { findReplaceFile.setError(message("InvalidData")); return false; } findReplaceFile.setFileRange(found); findReplaceFile.setStringRange(stringRange); findReplaceFile.setOuputString(pageText); return true; } catch (Exception e) { MyBoxLog.debug(e); findReplaceFile.setError(e.toString()); return false; } } public static LongRange findNextBytesRange(FxTask currentTask, FileEditInformation sourceInfo, FindReplaceFile findReplaceFile) { if (sourceInfo == null || sourceInfo.getFile() == null || findReplaceFile == null || findReplaceFile.getFindString() == null || findReplaceFile.getFindString().isEmpty()) { if (findReplaceFile != null) { findReplaceFile.setError(message("InvalidParameters")); } return null; } findReplaceFile.setError(null); findReplaceFile.setFileRange(null); findReplaceFile.setStringRange(null); try { sourceInfo.setFindReplace(findReplaceFile); findReplaceFile.setFileInfo(sourceInfo); File sourceFile = sourceInfo.getFile(); long fileLength = sourceFile.length(); long hexStartPosition = (findReplaceFile.getPosition() / 3) * 3; long bytesStartPosition = hexStartPosition / 3; if (bytesStartPosition < 0 || bytesStartPosition >= fileLength) { if (findReplaceFile.isWrap()) { hexStartPosition = 0; bytesStartPosition = 0; } else { // findReplaceFile.setError(message("InvalidParameters")); return null; } } int maxBytesLen = FileTools.bufSize(sourceFile, 48); String findString = findReplaceFile.getFindString(); FindReplaceString findReplaceString = findReplaceFile.findReplaceString() .setFindString(findString).setAnchor(0).setWrap(false); // findString should have been in hex format int findHexLen = findReplaceFile.isIsRegex() ? maxBytesLen * 3 : findString.length(); LongRange found = findNextBytesRange(currentTask, sourceFile, findReplaceString, hexStartPosition, fileLength * 3, maxBytesLen, findHexLen); if (currentTask != null && !currentTask.isWorking()) { return null; } if (found == null && findReplaceString.getError() != null) { findReplaceFile.setError(findReplaceString.getError()); return null; } if (found == null && findReplaceFile.isWrap() && bytesStartPosition > 0 && bytesStartPosition < fileLength * 3) { long hexEndPosition; if (findReplaceFile.isIsRegex()) { hexEndPosition = fileLength * 3; } else { hexEndPosition = hexStartPosition + findHexLen; } found = findNextBytesRange(currentTask, sourceFile, findReplaceString, 0, hexEndPosition, maxBytesLen, findHexLen); if (currentTask != null && !currentTask.isWorking()) { return null; } } if (found == null && findReplaceString.getError() != null) { findReplaceFile.setError(findReplaceString.getError()); return null; } findReplaceFile.setFileRange(found); return found; } catch (Exception e) { findReplaceFile.setError(e.toString()); MyBoxLog.debug(e); return null; } } public static LongRange findNextBytesRange(FxTask currentTask, File file, FindReplaceString findReplaceString, long hexStartPosition, long hexEndPosition, long maxBytesLen, int findHexLen) { if (file == null || findReplaceString == null || hexStartPosition >= hexEndPosition) { return null; } findReplaceString.setError(null); findReplaceString.setStringRange(null); try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file))) { if (hexStartPosition > 0) { inputStream.skip(hexStartPosition / 3); } int bufSize = (int) Math.min(maxBytesLen, (hexEndPosition - hexStartPosition) / 3); byte[] bufBytes = new byte[bufSize]; IndexRange range; String bufHex, backString = ""; long hexIndex = hexStartPosition; int bufLen, backFrom, hexLen, keepLen; LongRange found = null; while ((bufLen = inputStream.read(bufBytes)) > 0) { if (currentTask != null && !currentTask.isWorking()) { return null; } if (bufLen < bufSize) { bufBytes = ByteTools.subBytes(bufBytes, 0, bufLen); } bufHex = ByteTools.bytesToHexFormat(bufBytes); hexLen = bufHex.length(); hexIndex += hexLen; keepLen = (int) (hexIndex - hexEndPosition); if (keepLen > 0) { bufHex = bufHex.substring(0, hexLen - keepLen); hexLen = bufHex.length(); } findReplaceString.setInputString(backString.concat(bufHex)) .setAnchor(0).handleString(currentTask); if (currentTask != null && !currentTask.isWorking()) { return null; } range = findReplaceString.getStringRange(); if (range != null) { found = new LongRange(); found.setStart(hexIndex - hexLen + range.getStart() - backString.length()); found.setEnd(found.getStart() + range.getLength()); break; } if (keepLen >= 0) { break; } backFrom = Math.max(3, hexLen - findHexLen + 3); if (backFrom < hexLen) { backString = bufHex.substring(backFrom, hexLen); } else { backString = ""; } } return found; } catch (Exception e) { MyBoxLog.debug(e); findReplaceString.setError(e.toString()); return null; } } public static boolean findPreviousBytes(FxTask currentTask, FileEditInformation sourceInfo, FindReplaceFile findReplaceFile) { try { LongRange found = findPreviousBytesRange(currentTask, sourceInfo, findReplaceFile); if (found == null) { return findReplaceFile != null && findReplaceFile.getError() == null; } String pageText = sourceInfo.readObjects(currentTask, found.getStart() / 3, found.getLength() / 3); if (currentTask != null && !currentTask.isWorking()) { return false; } IndexRange stringRange = FindReplaceTextFile.pageRange(findReplaceFile); if (stringRange == null) { findReplaceFile.setError(message("InvalidData")); return false; } findReplaceFile.setFileRange(found); findReplaceFile.setStringRange(stringRange); findReplaceFile.setOuputString(pageText); return true; } catch (Exception e) { MyBoxLog.debug(e); findReplaceFile.setError(e.toString()); return false; } } public static LongRange findPreviousBytesRange(FxTask currentTask, FileEditInformation sourceInfo, FindReplaceFile findReplaceFile) { if (sourceInfo == null || sourceInfo.getFile() == null || findReplaceFile == null || findReplaceFile.getFindString() == null || findReplaceFile.getFindString().isEmpty()) { if (findReplaceFile != null) { findReplaceFile.setError(message("InvalidParameters")); } return null; } try { sourceInfo.setFindReplace(findReplaceFile); findReplaceFile.setFileInfo(sourceInfo); File sourceFile = sourceInfo.getFile(); long fileLength = sourceFile.length(); long hexEndPosition = (findReplaceFile.getPosition() / 3) * 3; long bytesEndPosition = hexEndPosition / 3; if (bytesEndPosition <= 0 || bytesEndPosition > fileLength) { if (findReplaceFile.isWrap()) { bytesEndPosition = fileLength; hexEndPosition = bytesEndPosition * 3; } else { // findReplaceFile.setError(message("InvalidParameters")); return null; } } int maxBytesLen = FileTools.bufSize(sourceFile, 48); String findString = findReplaceFile.getFindString(); FindReplaceString findReplaceString = findReplaceFile.findReplaceString() .setFindString(findString).setAnchor(0).setWrap(false); // findString should have been in hex format int findHexLen = findReplaceFile.isIsRegex() ? maxBytesLen * 3 : findString.length(); LongRange found = findPreviousBytesRange(currentTask, sourceFile, findReplaceString, 0, hexEndPosition, maxBytesLen, findHexLen); if (currentTask != null && !currentTask.isWorking()) { return null; } if (found == null && findReplaceString.getError() != null) { findReplaceFile.setError(findReplaceString.getError()); return null; } if (found == null && findReplaceFile.isWrap() && hexEndPosition > 0 && hexEndPosition <= fileLength * 3) { long hexStartPosition; if (findReplaceFile.isIsRegex()) { hexStartPosition = 0; } else { hexStartPosition = Math.max(0, hexEndPosition - findHexLen); } found = findPreviousBytesRange(currentTask, sourceFile, findReplaceString, hexStartPosition, fileLength * 3, maxBytesLen, findHexLen); if (currentTask != null && !currentTask.isWorking()) { return null; } } if (found == null && findReplaceString.getError() != null) { findReplaceFile.setError(findReplaceString.getError()); return null; } findReplaceFile.setFileRange(found); return found; } catch (Exception e) { findReplaceFile.setError(e.toString()); MyBoxLog.debug(e); return null; } } public static LongRange findPreviousBytesRange(FxTask currentTask, File file, FindReplaceString findReplaceString, long hexStartPosition, long hexEndPosition, long maxBytesLen, int findHexLen) { if (file == null || findReplaceString == null || hexStartPosition >= hexEndPosition) { return null; } findReplaceString.setError(null); findReplaceString.setStringRange(null); try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file))) { if (hexStartPosition > 0) { inputStream.skip(hexStartPosition / 3); } int bufSize = (int) Math.min(maxBytesLen, (hexEndPosition - hexStartPosition) / 3); byte[] bufBytes = new byte[bufSize]; IndexRange range; String bufHex, backString = "", checkString; long hexIndex = hexStartPosition; int bufLen, backFrom, hexLen, checkLen, keepLen; LongRange found = null; while ((bufLen = inputStream.read(bufBytes)) > 0) { if (currentTask != null && !currentTask.isWorking()) { return null; } if (bufLen < maxBytesLen) { bufBytes = ByteTools.subBytes(bufBytes, 0, bufLen); } bufHex = ByteTools.bytesToHexFormat(bufBytes); hexLen = bufHex.length(); hexIndex += hexLen; keepLen = (int) (hexIndex - hexEndPosition); if (keepLen > 0) { bufHex = bufHex.substring(0, hexLen - keepLen); hexLen = bufHex.length(); } checkString = backString.concat(bufHex); checkLen = checkString.length(); findReplaceString.setInputString(checkString) .setAnchor(checkLen).handleString(currentTask); if (currentTask != null && !currentTask.isWorking()) { return null; } range = findReplaceString.getStringRange(); if (range != null) { found = new LongRange(); found.setStart(hexIndex - hexLen + range.getStart() - backString.length()); found.setEnd(found.getStart() + range.getLength()); if (range.getEnd() == checkLen) { backString = ""; } else { backFrom = Math.max(range.getStart() - backString.length() + 3, Math.max(3, hexLen - findHexLen + 3)); if (backFrom < hexLen) { backString = bufHex.substring(backFrom, hexLen); } else { backString = ""; } } } else { backFrom = Math.max(3, hexLen - findHexLen + 3); if (backFrom < hexLen) { backString = bufHex.substring(backFrom, hexLen); } else { backString = ""; } } if (keepLen >= 0) { break; } } return found; } catch (Exception e) { MyBoxLog.debug(e); findReplaceString.setError(e.toString()); return null; } } public static boolean replaceFirstBytes(FxTask currentTask, FileEditInformation sourceInfo, FindReplaceFile findReplaceFile) { try { if (findReplaceFile == null) { return false; } String replaceString = findReplaceFile.getReplaceString(); if (replaceString == null) { return false; } findReplaceFile.setOperation(FindReplaceString.Operation.FindNext); findNextBytes(currentTask, sourceInfo, findReplaceFile); if (currentTask != null && !currentTask.isWorking()) { return false; } IndexRange stringRange = findReplaceFile.getStringRange(); findReplaceFile.setOperation(FindReplaceString.Operation.ReplaceFirst); if (stringRange == null) { return false; } String pageText = findReplaceFile.getOutputString(); if (stringRange.getStart() < 0 || stringRange.getStart() > stringRange.getEnd() || stringRange.getEnd() > pageText.length()) { return false; } String output = pageText.substring(0, stringRange.getStart()) + replaceString + pageText.substring(stringRange.getEnd(), pageText.length()); findReplaceFile.setOuputString(output); return true; } catch (Exception e) { findReplaceFile.setError(e.toString()); MyBoxLog.debug(e); return false; } } public static boolean replaceAllBytes(FxTask currentTask, FileEditInformation sourceInfo, FindReplaceFile findReplaceFile) { if (sourceInfo == null || sourceInfo.getFile() == null || findReplaceFile.getFindString() == null || findReplaceFile.getFindString().isEmpty()) { if (findReplaceFile != null) { findReplaceFile.setError(message("InvalidParameters")); } return false; } int total = 0; findReplaceFile.setError(null); findReplaceFile.setFileRange(null); findReplaceFile.setStringRange(null); sourceInfo.setFindReplace(findReplaceFile); findReplaceFile.setFileInfo(sourceInfo); File sourceFile = sourceInfo.getFile(); File tmpFile = FileTmpTools.getTempFile(); try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(sourceFile)); BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(tmpFile))) { int pageSize = FileTools.bufSize(sourceFile, 48); String findString = findReplaceFile.getFindString(); String replaceString = findReplaceFile.getReplaceString(); FindReplaceString findReplaceString = findReplaceFile.findReplaceString() .setFindString(findString).setReplaceString(replaceString) .setAnchor(0).setWrap(false); int findLen = findReplaceFile.isIsRegex() ? pageSize * 3 : findString.length(); byte[] pageBytes = new byte[pageSize]; IndexRange range; String pageHex, backString = "", checkedString, replacedString; int pageLen, backFrom, lastReplacedLength; while ((pageLen = inputStream.read(pageBytes)) > 0) { if (currentTask != null && !currentTask.isWorking()) { return false; } if (pageLen < pageSize) { pageBytes = ByteTools.subBytes(pageBytes, 0, pageLen); } pageHex = ByteTools.bytesToHexFormat(pageBytes); pageLen = pageHex.length(); checkedString = backString + pageHex; findReplaceString.setInputString(checkedString) .setAnchor(0).handleString(currentTask); if (currentTask != null && !currentTask.isWorking()) { return false; } range = findReplaceString.getStringRange(); if (range != null) { replacedString = findReplaceString.getOutputString(); lastReplacedLength = findReplaceString.getLastReplacedLength(); byte[] replacedBytes = ByteTools.hexFormatToBytes(replacedString.substring(0, lastReplacedLength)); outputStream.write(replacedBytes); backString = replacedString.substring(lastReplacedLength, replacedString.length()); total += findReplaceString.getCount(); } else { if (!backString.isEmpty()) { byte[] backBytes = ByteTools.hexFormatToBytes(backString); outputStream.write(backBytes); } backFrom = Math.max(3, pageLen - findLen + 3); backString = pageHex.substring(backFrom, pageLen); byte[] passBytes = ByteTools.hexFormatToBytes(pageHex.substring(0, backFrom)); outputStream.write(passBytes); } } if (!backString.isEmpty()) { byte[] backBytes = ByteTools.hexFormatToBytes(backString); outputStream.write(backBytes); } } catch (Exception e) { MyBoxLog.debug(e); findReplaceFile.setError(e.toString()); return false; } if (currentTask != null && !currentTask.isWorking()) { return false; } findReplaceFile.setCount(total); if (tmpFile != null && tmpFile.exists()) { if (total > 0) { findReplaceFile.backup(currentTask, sourceFile); return FileTools.override(tmpFile, sourceFile); } else { return true; } } return false; } public static boolean findAllBytes(FxTask currentTask, FileEditInformation sourceInfo, FindReplaceFile findReplaceFile) { if (sourceInfo == null || sourceInfo.getFile() == null || findReplaceFile.getFindString() == null || findReplaceFile.getFindString().isEmpty()) { if (findReplaceFile != null) { findReplaceFile.setError(message("InvalidParameters")); } return false; } findReplaceFile.setError(null); findReplaceFile.setFileRange(null); findReplaceFile.setStringRange(null); findReplaceFile.setCount(0); findReplaceFile.setMatches(null); findReplaceFile.setMatchesData(null); sourceInfo.setFindReplace(findReplaceFile); findReplaceFile.setFileInfo(sourceInfo); File sourceFile = sourceInfo.getFile(); int count = 0; File tmpFile = FileTmpTools.getTempFile(); try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(sourceFile)); CSVPrinter csvPrinter = CsvTools.csvPrinter(tmpFile)) { int pageSize = FileTools.bufSize(sourceFile, 48); String findString = findReplaceFile.getFindString(); String replaceString = findReplaceFile.getReplaceString(); FindReplaceString findReplaceString = findReplaceFile.findReplaceString() .setFindString(findString).setReplaceString(replaceString) .setAnchor(0).setWrap(false); int findLen = findReplaceFile.isIsRegex() ? pageSize * 3 : findString.length(); byte[] pageBytes = new byte[pageSize]; IndexRange range; String pageHex, backString = "", checkedString; int pageLen, backFrom; long bytesStart = 0; List<String> names = new ArrayList<>(); names.addAll(Arrays.asList(message("Start"), message("End"), message("String"))); csvPrinter.printRecord(names); List<String> row = new ArrayList<>(); while ((pageLen = inputStream.read(pageBytes)) > 0) { if (currentTask != null && !currentTask.isWorking()) { return false; } if (pageLen < pageSize) { pageBytes = ByteTools.subBytes(pageBytes, 0, pageLen); } pageHex = ByteTools.bytesToHexFormat(pageBytes); pageLen = pageHex.length(); checkedString = backString + pageHex; findReplaceString.setInputString(checkedString) .setAnchor(0).handleString(currentTask); if (currentTask != null && !currentTask.isWorking()) { return false; } range = findReplaceString.getStringRange(); if (range != null) { long offset = bytesStart - backString.length(); List<FindReplaceMatch> sMatches = findReplaceString.getMatches(); if (sMatches != null && !sMatches.isEmpty()) { for (FindReplaceMatch m : sMatches) { row.clear(); row.add(((offset + m.getStart()) / 3 + 1) + ""); row.add((offset + m.getEnd()) / 3 + ""); row.add(m.getMatchedPrefix()); csvPrinter.printRecord(row); count++; } } backString = checkedString.length() == range.getEnd() ? "" : checkedString.substring(range.getEnd()); } else { backFrom = Math.max(3, pageLen - findLen + 3); backString = pageHex.substring(backFrom, pageLen); } bytesStart += pageLen; } csvPrinter.flush(); } catch (Exception e) { MyBoxLog.debug(e); findReplaceFile.setError(e.toString()); return false; } if (currentTask != null && !currentTask.isWorking()) { return false; } if (tmpFile == null || !tmpFile.exists()) { return false; } if (count == 0) { return true; } DataFileCSV matchesData = findReplaceFile.initMatchesData(sourceFile); File matchesFile = matchesData.getFile(); if (!FileTools.override(tmpFile, matchesFile)) { return false; } matchesData.setRowsNumber(count); findReplaceFile.setCount(count); findReplaceFile.setMatchesData(matchesData); return true; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data/UserLanguage.java
released/MyBox/src/main/java/mara/mybox/data/UserLanguage.java
package mara.mybox.data; import java.io.File; import java.util.Enumeration; import java.util.Map; import java.util.ResourceBundle; import java.util.Set; import mara.mybox.tools.ConfigTools; import static mara.mybox.value.AppVariables.useChineseWhenBlankTranslation; import mara.mybox.value.Languages; /** * @Author Mara * @CreateDate 2019-12-27 * @License Apache License Version 2.0 */ public class UserLanguage extends ResourceBundle { protected Map<String, String> items; protected String language; public UserLanguage(String name) throws Exception { File file = Languages.interfaceLanguageFile(name); if (!file.exists()) { items = null; throw new Exception(); } else { language = name; items = ConfigTools.readValues(file); } } public UserLanguage(Map<String, String> items) { this.items = items; } public boolean isValid() { return items != null; } @Override public Object handleGetObject(String key) { String value = null; if (items != null) { value = items.get(key); } if (value == null) { value = useChineseWhenBlankTranslation ? Languages.BundleZhCN.getString(key) : Languages.BundleEn.getString(key); } if (value == null) { value = key; } return value; } @Override protected Set<String> handleKeySet() { return Languages.BundleEn.keySet(); } /* get/set */ @Override public Enumeration<String> getKeys() { return Languages.BundleEn.getKeys(); } public Map<String, String> getItems() { return items; } public UserLanguage setItems(Map<String, String> items) { this.items = items; return this; } public String getLanguage() { return language; } public UserLanguage setLanguage(String language) { this.language = language; return this; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data/JsonTreeNode.java
released/MyBox/src/main/java/mara/mybox/data/JsonTreeNode.java
package mara.mybox.data; import com.fasterxml.jackson.core.json.JsonReadFeature; import com.fasterxml.jackson.core.json.JsonWriteFeature; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.json.JsonMapper; import java.sql.Connection; import javafx.beans.property.BooleanProperty; import javafx.beans.property.SimpleBooleanProperty; import mara.mybox.db.DerbyBase; import mara.mybox.dev.MyBoxLog; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2023-4-30 * @License Apache License Version 2.0 */ public class JsonTreeNode { public static ObjectMapper jsonMapper; protected String title; protected JsonNode jsonNode; protected NodeType type; protected final BooleanProperty selected = new SimpleBooleanProperty(false); public static enum NodeType { Array, Object, String, Number, Boolean, Null, Unknown } public JsonTreeNode() { title = null; jsonNode = null; type = null; } public JsonTreeNode(String name, JsonNode jsonNode) { this.title = name; this.jsonNode = jsonNode; if (jsonNode == null) { type = NodeType.Unknown; } else if (jsonNode.isNull()) { type = NodeType.Null; } else { if (jsonNode.isBoolean()) { type = NodeType.Boolean; } else if (jsonNode.isNumber()) { type = NodeType.Number; } else if (jsonNode.isTextual() || jsonNode.isBinary()) { type = NodeType.String; } else if (jsonNode.isArray()) { type = NodeType.Array; } else if (jsonNode.isObject()) { type = NodeType.Object; } else { type = NodeType.Unknown; } } } public String getTypename() { return type == null ? null : message(type.name()); } public String getValue() { return jsonNode == null || type == NodeType.Null ? null : formatByJackson(jsonNode); } public boolean isValue() { return jsonNode != null && type != NodeType.Array && type != NodeType.Object; } public boolean isArray() { return jsonNode != null && type == NodeType.Array; } public boolean isObject() { return jsonNode != null && type == NodeType.Object; } public boolean isNull() { return jsonNode != null || type == NodeType.Null; } public boolean isString() { return jsonNode != null || type == NodeType.String; } public boolean isNumber() { return jsonNode != null || type == NodeType.Number; } public boolean isBoolean() { return jsonNode != null || type == NodeType.Boolean; } public String stringByJackson() { return stringByJackson(jsonNode); } public String formatByJackson() { return formatByJackson(jsonNode); } /* static */ public static ObjectMapper jsonMapper() { if (jsonMapper == null) { try (Connection conn = DerbyBase.getConnection()) { JsonMapper.Builder builder = JsonMapper.builder(); if (UserConfig.getBoolean(conn, "JacksonAllowJavaComments", false)) { builder.enable(JsonReadFeature.ALLOW_JAVA_COMMENTS); } else { builder.disable(JsonReadFeature.ALLOW_JAVA_COMMENTS); } if (UserConfig.getBoolean(conn, "JacksonAllowYamlComments", false)) { builder.enable(JsonReadFeature.ALLOW_YAML_COMMENTS); } else { builder.disable(JsonReadFeature.ALLOW_YAML_COMMENTS); } if (UserConfig.getBoolean(conn, "JacksonAllowSingleQuotes", false)) { builder.enable(JsonReadFeature.ALLOW_SINGLE_QUOTES); } else { builder.disable(JsonReadFeature.ALLOW_SINGLE_QUOTES); } if (UserConfig.getBoolean(conn, "JacksonAllowUnquotedFieldNames", false)) { builder.enable(JsonReadFeature.ALLOW_UNQUOTED_FIELD_NAMES); } else { builder.disable(JsonReadFeature.ALLOW_UNQUOTED_FIELD_NAMES); } if (UserConfig.getBoolean(conn, "JacksonAllowUnescapedControlChars", false)) { builder.enable(JsonReadFeature.ALLOW_UNESCAPED_CONTROL_CHARS); } else { builder.disable(JsonReadFeature.ALLOW_UNESCAPED_CONTROL_CHARS); } if (UserConfig.getBoolean(conn, "JacksonAllowBackslashEscapingAny", false)) { builder.enable(JsonReadFeature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER); } else { builder.disable(JsonReadFeature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER); } if (UserConfig.getBoolean(conn, "JacksonAllowLeadingZerosForNumbers", false)) { builder.enable(JsonReadFeature.ALLOW_LEADING_ZEROS_FOR_NUMBERS); } else { builder.disable(JsonReadFeature.ALLOW_LEADING_ZEROS_FOR_NUMBERS); } if (UserConfig.getBoolean(conn, "JacksonAllowLeadingPlusSignForNumbers", false)) { builder.enable(JsonReadFeature.ALLOW_LEADING_PLUS_SIGN_FOR_NUMBERS); } else { builder.disable(JsonReadFeature.ALLOW_LEADING_PLUS_SIGN_FOR_NUMBERS); } if (UserConfig.getBoolean(conn, "JacksonAllowLeadingDecimalPointForNumbers", false)) { builder.enable(JsonReadFeature.ALLOW_LEADING_DECIMAL_POINT_FOR_NUMBERS); } else { builder.disable(JsonReadFeature.ALLOW_LEADING_DECIMAL_POINT_FOR_NUMBERS); } if (UserConfig.getBoolean(conn, "JacksonAllowTrailingDecimalPointForNumbers", false)) { builder.enable(JsonReadFeature.ALLOW_TRAILING_DECIMAL_POINT_FOR_NUMBERS); } else { builder.disable(JsonReadFeature.ALLOW_TRAILING_DECIMAL_POINT_FOR_NUMBERS); } if (UserConfig.getBoolean(conn, "JacksonAllowNonNumericNumbers", false)) { builder.enable(JsonReadFeature.ALLOW_NON_NUMERIC_NUMBERS); } else { builder.disable(JsonReadFeature.ALLOW_NON_NUMERIC_NUMBERS); } if (UserConfig.getBoolean(conn, "JacksonAllowMissingValues", false)) { builder.enable(JsonReadFeature.ALLOW_MISSING_VALUES); } else { builder.disable(JsonReadFeature.ALLOW_MISSING_VALUES); } if (UserConfig.getBoolean(conn, "JacksonAllowTrailingComma", false)) { builder.enable(JsonReadFeature.ALLOW_TRAILING_COMMA); } else { builder.disable(JsonReadFeature.ALLOW_TRAILING_COMMA); } if (UserConfig.getBoolean(conn, "JacksonQuoteFieldNames", true)) { builder.enable(JsonWriteFeature.QUOTE_FIELD_NAMES); } else { builder.disable(JsonWriteFeature.QUOTE_FIELD_NAMES); } if (UserConfig.getBoolean(conn, "JacksonWriteNanAsStrings", true)) { builder.enable(JsonWriteFeature.WRITE_NAN_AS_STRINGS); } else { builder.disable(JsonWriteFeature.WRITE_NAN_AS_STRINGS); } if (UserConfig.getBoolean(conn, "JacksonWriteNumbersAsStrings", false)) { builder.enable(JsonWriteFeature.WRITE_NUMBERS_AS_STRINGS); } else { builder.disable(JsonWriteFeature.WRITE_NUMBERS_AS_STRINGS); } if (UserConfig.getBoolean(conn, "JacksonEscapeNonASCII", false)) { builder.enable(JsonWriteFeature.ESCAPE_NON_ASCII); } else { builder.disable(JsonWriteFeature.ESCAPE_NON_ASCII); } jsonMapper = builder.build(); } catch (Exception e) { MyBoxLog.error(e); return null; } } return jsonMapper; } public static void resetJsonMapper() { jsonMapper = null; } public static String stringByJackson(JsonNode jsonNode) { try { if (jsonNode == null) { return null; } return jsonMapper().writeValueAsString(jsonNode); } catch (Exception e) { MyBoxLog.error(e); return null; } } public static String formatByJackson(JsonNode jsonNode) { try { if (jsonNode == null) { return null; } return jsonMapper().writerWithDefaultPrettyPrinter() .writeValueAsString(jsonNode); } catch (Exception e) { MyBoxLog.error(e); return null; } } public static JsonNode parseByJackson(String json) { try { if (json == null) { return null; } return jsonMapper().readTree(json); } catch (Exception e) { MyBoxLog.error(e); return null; } } /* set */ public JsonTreeNode setTitle(String title) { this.title = title; return this; } public JsonTreeNode setJsonNode(JsonNode node) { this.jsonNode = node; return this; } /* get */ public String getTitle() { return title; } public JsonNode getJsonNode() { return jsonNode; } public NodeType getType() { return type; } public BooleanProperty getSelected() { return selected; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data/FileSynchronizeAttributes.java
released/MyBox/src/main/java/mara/mybox/data/FileSynchronizeAttributes.java
package mara.mybox.data; import java.util.List; /** * @Author Mara * @CreateDate 2018-7-8 13:14:38 * @Version 1.0 * @License Apache License Version 2.0 */ public class FileSynchronizeAttributes { private boolean continueWhenError, conditionalCopy, copySubdir, copyEmpty, copyNew, copyHidden, onlyCopyReadonly, copyExisted, onlyCopyModified, deleteNotExisteds, notCopySome, canReplace, copyAttrinutes, copyMTime, setPermissions; private long modifyAfter, copiedFilesNumber, copiedDirectoriesNumber, totalFilesNumber, totalDirectoriesNumber, totalSize, copiedSize, deletedFiles, deletedDirectories, deletedSize, failedDeletedFiles, failedDeletedDirectories, failedDeletedSize; private List<String> notCopyNames; private int permissions; public FileSynchronizeAttributes() { continueWhenError = conditionalCopy = copySubdir = copyEmpty = copyNew = copyHidden = true; copyExisted = onlyCopyModified = canReplace = copyAttrinutes = copyMTime = true; onlyCopyReadonly = deleteNotExisteds = notCopySome = setPermissions = false; copiedFilesNumber = copiedDirectoriesNumber = totalFilesNumber = totalDirectoriesNumber = 0; totalSize = copiedSize = deletedFiles = deletedDirectories = deletedSize = 0; failedDeletedFiles = failedDeletedDirectories = failedDeletedSize = 0; permissions = -1; } public boolean isContinueWhenError() { return continueWhenError; } public void setContinueWhenError(boolean continueWhenError) { this.continueWhenError = continueWhenError; } public boolean isConditionalCopy() { return conditionalCopy; } public void setConditionalCopy(boolean conditionalCopy) { this.conditionalCopy = conditionalCopy; } public boolean isCopySubdir() { return copySubdir; } public void setCopySubdir(boolean copySubdir) { this.copySubdir = copySubdir; } public boolean isCopyEmpty() { return copyEmpty; } public void setCopyEmpty(boolean copyEmpty) { this.copyEmpty = copyEmpty; } public boolean isCopyNew() { return copyNew; } public void setCopyNew(boolean copyNew) { this.copyNew = copyNew; } public boolean isCopyHidden() { return copyHidden; } public void setCopyHidden(boolean copyHidden) { this.copyHidden = copyHidden; } public boolean isOnlyCopyReadonly() { return onlyCopyReadonly; } public void setOnlyCopyReadonly(boolean onlyCopyReadonly) { this.onlyCopyReadonly = onlyCopyReadonly; } public boolean isCopyExisted() { return copyExisted; } public void setCopyExisted(boolean copyExisted) { this.copyExisted = copyExisted; } public boolean isOnlyCopyModified() { return onlyCopyModified; } public void setOnlyCopyModified(boolean onlyCopyModified) { this.onlyCopyModified = onlyCopyModified; } public boolean isDeleteNotExisteds() { return deleteNotExisteds; } public void setDeleteNotExisteds(boolean deleteNotExisteds) { this.deleteNotExisteds = deleteNotExisteds; } public boolean isNotCopySome() { return notCopySome; } public void setNotCopySome(boolean notCopySome) { this.notCopySome = notCopySome; } public boolean isCanReplace() { return canReplace; } public void setCanReplace(boolean canReplace) { this.canReplace = canReplace; } public boolean isCopyAttrinutes() { return copyAttrinutes; } public void setCopyAttrinutes(boolean copyAttrinutes) { this.copyAttrinutes = copyAttrinutes; } public long getModifyAfter() { return modifyAfter; } public void setModifyAfter(long modifyAfter) { this.modifyAfter = modifyAfter; } public List<String> getNotCopyNames() { return notCopyNames; } public void setNotCopyNames(List<String> notCopyNames) { this.notCopyNames = notCopyNames; } public long getCopiedFilesNumber() { return copiedFilesNumber; } public void setCopiedFilesNumber(long copiedFilesNumber) { this.copiedFilesNumber = copiedFilesNumber; } public long getCopiedDirectoriesNumber() { return copiedDirectoriesNumber; } public void setCopiedDirectoriesNumber(long copiedDirectoriesNumber) { this.copiedDirectoriesNumber = copiedDirectoriesNumber; } public long getTotalFilesNumber() { return totalFilesNumber; } public void setTotalFilesNumber(long totalFilesNumber) { this.totalFilesNumber = totalFilesNumber; } public long getTotalDirectoriesNumber() { return totalDirectoriesNumber; } public void setTotalDirectoriesNumber(long totalDirectoriesNumber) { this.totalDirectoriesNumber = totalDirectoriesNumber; } public long getTotalSize() { return totalSize; } public void setTotalSize(long totalSize) { this.totalSize = totalSize; } public long getCopiedSize() { return copiedSize; } public void setCopiedSize(long copiedSize) { this.copiedSize = copiedSize; } public long getDeletedFiles() { return deletedFiles; } public void setDeletedFiles(long deletedFiles) { this.deletedFiles = deletedFiles; } public long getDeletedDirectories() { return deletedDirectories; } public void setDeletedDirectories(long deletedDirectories) { this.deletedDirectories = deletedDirectories; } public long getDeletedSize() { return deletedSize; } public void setDeletedSize(long deletedSize) { this.deletedSize = deletedSize; } public long getFailedDeletedFiles() { return failedDeletedFiles; } public void setFailedDeletedFiles(long failedDeletedFiles) { this.failedDeletedFiles = failedDeletedFiles; } public long getFailedDeletedDirectories() { return failedDeletedDirectories; } public void setFailedDeletedDirectories(long failedDeletedDirectories) { this.failedDeletedDirectories = failedDeletedDirectories; } public long getFailedDeletedSize() { return failedDeletedSize; } public void setFailedDeletedSize(long failedDeletedSize) { this.failedDeletedSize = failedDeletedSize; } public boolean isCopyMTime() { return copyMTime; } public void setCopyMTime(boolean copyMTime) { this.copyMTime = copyMTime; } public boolean isSetPermissions() { return setPermissions; } public void setSetPermissions(boolean setPermissions) { this.setPermissions = setPermissions; } public int getPermissions() { return permissions; } public void setPermissions(int permissions) { this.permissions = permissions; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data/FxWindow.java
released/MyBox/src/main/java/mara/mybox/data/FxWindow.java
package mara.mybox.data; import javafx.stage.Stage; import javafx.stage.Window; import mara.mybox.controller.BaseController; import mara.mybox.controller.BaseController_Attributes.StageType; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2023-9-13 * @License Apache License Version 2.0 */ public class FxWindow { protected Window window; protected String title, type, name, modality; protected int width, height, x, y; protected boolean isShowing, isAlwaysOnTop, isFocused, isChild, isFullScreen, isIconified, isMaximized, isResizable; public FxWindow() { init(); } final public void init() { window = null; title = null; type = null; modality = null; name = null; isShowing = isAlwaysOnTop = isFocused = isChild = isFullScreen = isIconified = isMaximized = isResizable = false; } public FxWindow(Window w) { init(); this.window = w; if (window == null) { return; } type = StageType.Normal.name(); name = window.getClass().toString(); width = (int) window.getWidth(); height = (int) window.getHeight(); x = (int) window.getX(); y = (int) window.getY(); isShowing = window.isShowing(); isFocused = window.isFocused(); if (window instanceof Stage) { Stage stage = (Stage) window; title = stage.getTitle(); if (null == stage.getModality()) { modality = null; } else { switch (stage.getModality()) { case APPLICATION_MODAL: modality = message("Application"); break; case WINDOW_MODAL: modality = message("Window"); break; default: modality = null; break; } } isAlwaysOnTop = stage.isAlwaysOnTop(); isChild = stage.getOwner() != null; isFullScreen = stage.isFullScreen(); isIconified = stage.isIconified(); isMaximized = stage.isMaximized(); isResizable = stage.isResizable(); Object u = stage.getUserData(); if (u != null && (u instanceof BaseController)) { BaseController controller = (BaseController) u; name = controller.getClass().toString(); type = controller.getStageType().name(); } } } /* get/set */ public Window getWindow() { return window; } public void setWindow(Window window) { this.window = window; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getModality() { return modality; } public void setModality(String modality) { this.modality = modality; } public int getWidth() { return width; } public void setWidth(int width) { this.width = width; } public int getHeight() { return height; } public void setHeight(int height) { this.height = height; } public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } public boolean isIsShowing() { return isShowing; } public void setIsShowing(boolean isShowing) { this.isShowing = isShowing; } public boolean isIsAlwaysOnTop() { return isAlwaysOnTop; } public void setIsAlwaysOnTop(boolean isAlwaysOnTop) { this.isAlwaysOnTop = isAlwaysOnTop; } public boolean isIsFocused() { return isFocused; } public void setIsFocused(boolean isFocused) { this.isFocused = isFocused; } public boolean isIsChild() { return isChild; } public void setIsChild(boolean isChild) { this.isChild = isChild; } public boolean isIsFullScreen() { return isFullScreen; } public void setIsFullScreen(boolean isFullScreen) { this.isFullScreen = isFullScreen; } public boolean isIsIconified() { return isIconified; } public void setIsIconified(boolean isIconified) { this.isIconified = isIconified; } public boolean isIsMaximized() { return isMaximized; } public void setIsMaximized(boolean isMaximized) { this.isMaximized = isMaximized; } public boolean isIsResizable() { return isResizable; } public void setIsResizable(boolean isResizable) { this.isResizable = isResizable; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data/FileUnarchive.java
released/MyBox/src/main/java/mara/mybox/data/FileUnarchive.java
package mara.mybox.data; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.nio.file.Files; import java.util.Enumeration; import java.util.List; import mara.mybox.controller.BaseTaskController; import static mara.mybox.value.Languages.message; import org.apache.commons.compress.archivers.ArchiveEntry; import org.apache.commons.compress.archivers.ArchiveInputStream; import org.apache.commons.compress.archivers.ArchiveStreamFactory; import org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry; import org.apache.commons.compress.archivers.sevenz.SevenZFile; import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipFile; import org.apache.commons.io.IOUtils; /** * @Author Mara * @CreateDate 2019-11-14 * @License Apache License Version 2.0 */ // http://commons.apache.org/proper/commons-compress/examples.html public class FileUnarchive { protected File sourceFile, targetPath; protected String archiver, charset, error; protected List<String> selected; protected int archiveSuccess, archiveFail; protected boolean charsetIncorrect, verbose; protected long totalFiles, totalSize; protected BaseTaskController taskController; protected ArchiveStreamFactory aFactory; public FileUnarchive() { totalFiles = totalSize = archiveFail = archiveSuccess = 0; charsetIncorrect = false; error = null; selected = null; } public FileUnarchive create() { return new FileUnarchive(); } public boolean start() { try { if (taskController == null || sourceFile == null || archiver == null || charset == null) { return false; } // archiver should have been determinied at this moment if (archiver.equalsIgnoreCase(ArchiveStreamFactory.SEVEN_Z)) { unarchive7z(); } else if (archiver.equalsIgnoreCase(ArchiveStreamFactory.ZIP)) { unarchiveZip(); } else { unarchive(); } return true; } catch (Exception e) { taskController.updateLogs(e.toString()); return false; } } protected void unarchive() { if (aFactory == null) { aFactory = new ArchiveStreamFactory(); } try (BufferedInputStream fileIn = new BufferedInputStream(new FileInputStream(sourceFile))) { if (archiver != null && aFactory.getInputStreamArchiveNames().contains(archiver)) { try (ArchiveInputStream in = aFactory.createArchiveInputStream(archiver, fileIn, charset)) { unarchive(in); } catch (Exception e) { unarchive(fileIn); } } else { unarchive(fileIn); } } catch (Exception e) { taskController.updateLogs(e.toString()); } } public void unarchive(BufferedInputStream fileIn) { try { archiver = ArchiveStreamFactory.detect(fileIn); if (archiver == null) { return; } try (ArchiveInputStream in = aFactory.createArchiveInputStream(archiver, fileIn, charset)) { unarchive(in); } catch (Exception ex) { taskController.updateLogs(ex.toString()); } } catch (Exception e) { taskController.updateLogs(e.toString()); } } protected void unarchive(ArchiveInputStream in) { try { if (archiver == null || !aFactory.getInputStreamArchiveNames().contains(archiver)) { return; } ArchiveEntry entry; File tfile; while ((entry = in.getNextEntry()) != null) { if (selected != null && !selected.contains(entry.getName())) { continue; } if (verbose) { taskController.updateLogs(message("Handling...") + ": " + entry.getName()); } if (!in.canReadEntryData(entry)) { archiveFail++; taskController.updateLogs(message("CanNotReadEntryData" + ":" + entry.getName())); continue; } try { tfile = new File(targetPath + File.separator + entry.getName()); tfile = taskController.makeTargetFile(tfile, tfile.getParentFile()); } catch (Exception e) { recordError(e.toString()); continue; } if (entry.isDirectory()) { archiveSuccess++; continue; } try (OutputStream o = Files.newOutputStream(tfile.toPath())) { IOUtils.copy(in, o); } catch (Exception e) { recordError(e.toString()); continue; } if (verbose) { taskController.targetFileGenerated(tfile); } archiveSuccess++; } } catch (Exception e) { recordError(e.toString()); } } protected void unarchive7z() { try (SevenZFile sevenZFile = SevenZFile.builder().setFile(sourceFile).get()) { SevenZArchiveEntry entry; File tfile; while ((entry = sevenZFile.getNextEntry()) != null) { if (selected != null && !selected.contains(entry.getName())) { continue; } if (verbose) { taskController.updateLogs(message("Handling...") + ": " + entry.getName()); } try { tfile = new File(targetPath + File.separator + entry.getName()); tfile = taskController.makeTargetFile(tfile, tfile.getParentFile()); } catch (Exception e) { recordError(e.toString()); continue; } if (entry.isDirectory()) { archiveSuccess++; continue; } try (FileOutputStream out = new FileOutputStream(tfile)) { byte[] content = new byte[(int) entry.getSize()]; sevenZFile.read(content, 0, content.length); out.write(content); } catch (Exception e) { recordError(e.toString()); continue; } if (verbose) { taskController.targetFileGenerated(tfile); } archiveSuccess++; } } catch (Exception e) { recordError(e.toString()); } } protected void unarchiveZip() { try (ZipFile zipFile = ZipFile.builder().setFile(sourceFile).setCharset(charset).get()) { Enumeration<ZipArchiveEntry> zEntries = zipFile.getEntries(); File tfile; while (zEntries.hasMoreElements()) { ZipArchiveEntry entry = zEntries.nextElement(); if (selected != null && !selected.contains(entry.getName())) { continue; } if (verbose) { taskController.updateLogs(message("Handling...") + ": " + entry.getName()); } try { tfile = new File(targetPath + File.separator + entry.getName()); tfile = taskController.makeTargetFile(tfile, tfile.getParentFile()); } catch (Exception e) { recordError(e.toString()); continue; } if (entry.isDirectory()) { archiveSuccess++; continue; } try (FileOutputStream out = new FileOutputStream(tfile); InputStream in = zipFile.getInputStream(entry)) { if (in != null) { IOUtils.copy(in, out); if (verbose) { taskController.targetFileGenerated(tfile); } } } catch (Exception e) { recordError(e.toString()); continue; } archiveSuccess++; } } catch (Exception e) { recordError(e.toString()); } } protected void recordError(String error) { taskController.updateLogs(error); archiveFail++; if (error.contains("java.nio.charset.MalformedInputException") || error.contains("Illegal char")) { charsetIncorrect = true; } } /* get/set */ public File getSourceFile() { return sourceFile; } public FileUnarchive setSourceFile(File sourceFile) { this.sourceFile = sourceFile; return this; } public File getTargetPath() { return targetPath; } public FileUnarchive setTargetPath(File targetPath) { this.targetPath = targetPath; return this; } public String getArchiver() { return archiver; } public FileUnarchive setArchiver(String archiver) { this.archiver = archiver; return this; } public String getError() { return error; } public FileUnarchive setError(String error) { this.error = error; return this; } public List<String> getSelected() { return selected; } public FileUnarchive setSelected(List<String> selected) { this.selected = selected; return this; } public int getArchiveSuccess() { return archiveSuccess; } public FileUnarchive setArchiveSuccess(int archiveSuccess) { this.archiveSuccess = archiveSuccess; return this; } public int getArchiveFail() { return archiveFail; } public FileUnarchive setArchiveFail(int archiveFail) { this.archiveFail = archiveFail; return this; } public boolean isCharsetIncorrect() { return charsetIncorrect; } public FileUnarchive setCharsetIncorrect(boolean charsetIncorrect) { this.charsetIncorrect = charsetIncorrect; return this; } public long getTotalFiles() { return totalFiles; } public FileUnarchive setTotalFiles(long totalFiles) { this.totalFiles = totalFiles; return this; } public long getTotalSize() { return totalSize; } public FileUnarchive setTotalSize(long totalSize) { this.totalSize = totalSize; return this; } public BaseTaskController getTaskController() { return taskController; } public FileUnarchive setTaskController(BaseTaskController taskController) { this.taskController = taskController; return this; } public String getCharset() { return charset; } public FileUnarchive setCharset(String charset) { this.charset = charset; return this; } public boolean isVerbose() { return verbose; } public FileUnarchive setVerbose(boolean verbose) { this.verbose = verbose; return this; } public ArchiveStreamFactory getaFactory() { return aFactory; } public FileUnarchive setaFactory(ArchiveStreamFactory aFactory) { this.aFactory = aFactory; return this; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data/DoublePath.java
released/MyBox/src/main/java/mara/mybox/data/DoublePath.java
package mara.mybox.data; import java.awt.Shape; import java.awt.geom.AffineTransform; import java.awt.geom.Arc2D; import java.awt.geom.Path2D; import java.awt.geom.PathIterator; import java.util.ArrayList; import java.util.List; import javafx.scene.shape.Path; import mara.mybox.controller.BaseController; import mara.mybox.data.DoublePathSegment.PathSegmentType; import static mara.mybox.data.DoublePathSegment.PathSegmentType.Arc; import static mara.mybox.data.DoublePathSegment.PathSegmentType.Close; import static mara.mybox.data.DoublePathSegment.PathSegmentType.Cubic; import static mara.mybox.data.DoublePathSegment.PathSegmentType.CubicSmooth; import static mara.mybox.data.DoublePathSegment.PathSegmentType.Line; import static mara.mybox.data.DoublePathSegment.PathSegmentType.LineHorizontal; import static mara.mybox.data.DoublePathSegment.PathSegmentType.LineVertical; import static mara.mybox.data.DoublePathSegment.PathSegmentType.Move; import static mara.mybox.data.DoublePathSegment.PathSegmentType.Quadratic; import static mara.mybox.data.DoublePathSegment.PathSegmentType.QuadraticSmooth; import mara.mybox.dev.MyBoxLog; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; import org.apache.batik.dom.GenericDOMImplementation; import org.apache.batik.ext.awt.geom.ExtendedGeneralPath; import org.apache.batik.svggen.SVGGeneratorContext; import org.apache.batik.svggen.SVGPath; import org.w3c.dom.DOMImplementation; import org.w3c.dom.Document; /** * @Author Mara * @CreateDate 2023-7-12 * @License Apache License Version 2.0 */ public class DoublePath implements DoubleShape { protected String content; protected List<DoublePathSegment> segments; protected int scale; public DoublePath() { init(); } public DoublePath(BaseController controller, String content) { init(); parseContent(controller, content); } public DoublePath(List<DoublePathSegment> segments) { init(); parseSegments(segments); } final public void init() { content = ""; segments = null; scale = UserConfig.imageScale(); } @Override public String name() { return message("SVGPath"); } public final List<DoublePathSegment> parseContent(BaseController controller, String content) { this.content = content; segments = stringToSegments(controller, content, scale); return segments; } public final String parseSegments(List<DoublePathSegment> segments) { this.segments = segments; content = segmentsToString(segments, " "); return content; } public String typesetting(String separator) { return segmentsToString(segments, separator); } @Override public Path2D.Double getShape() { Path2D.Double path = new Path2D.Double(); addToPath2D(path, segments); return path; } @Override public DoublePath copy() { DoublePath path = new DoublePath(); path.setContent(content); if (segments != null) { List<DoublePathSegment> list = new ArrayList<>(); for (DoublePathSegment seg : segments) { list.add(seg.copy()); } path.setSegments(list); } return path; } @Override public boolean isValid() { return content != null && segments != null; } @Override public boolean isEmpty() { return !isValid() || segments.isEmpty(); } @Override public boolean translateRel(double offsetX, double offsetY) { try { if (segments == null) { return true; } for (int i = 0; i < segments.size(); i++) { DoublePathSegment seg = segments.get(i); segments.set(i, seg.translate(offsetX, offsetY)); } content = segmentsToString(segments, " "); return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } @Override public boolean scale(double scaleX, double scaleY) { try { if (segments == null) { return true; } for (int i = 0; i < segments.size(); i++) { DoublePathSegment seg = segments.get(i); segments.set(i, seg.scale(scaleX, scaleY)); } content = segmentsToString(segments, " "); return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } @Override public String pathAbs() { try { if (segments == null || segments.isEmpty()) { return null; } String path = null; for (DoublePathSegment seg : segments) { if (path != null) { path += "\n" + seg.abs(); } else { path = seg.abs(); } } return path; } catch (Exception e) { MyBoxLog.console(e); return null; } } @Override public String pathRel() { try { if (segments == null || segments.isEmpty()) { return null; } String path = null; for (DoublePathSegment seg : segments) { if (path != null) { path += "\n" + seg.rel(); } else { path = seg.rel(); } } return path; } catch (Exception e) { MyBoxLog.console(e); return null; } } @Override public String elementAbs() { return "<path d=\"\n" + pathAbs() + "\n\"> "; } @Override public String elementRel() { return "<path d=\"\n" + pathRel() + "\n\"> "; } public DoublePoint lastPoint() { if (isEmpty()) { return null; } return segments.get(segments.size() - 1).getEndPoint(); } public boolean replace(int index, DoublePathSegment seg) { if (segments == null || index < 0 || index >= segments.size()) { return false; } segments.set(index, seg); content = segmentsToString(segments, " "); return true; } public boolean insert(int index, DoublePathSegment seg) { if (segments == null || index < 0 || index > segments.size()) { return false; } segments.add(index, seg); content = segmentsToString(segments, " "); return true; } public boolean add(DoublePathSegment seg) { if (segments == null) { return false; } segments.add(seg); content = segmentsToString(segments, " "); return true; } public boolean toAbs(BaseController controller) { try { parseContent(controller, pathAbs()); return true; } catch (Exception e) { MyBoxLog.console(e); return false; } } public boolean toRel(BaseController controller) { try { parseContent(controller, pathRel()); return true; } catch (Exception e) { MyBoxLog.console(e); return false; } } public void clear() { content = ""; segments = null; } /* static */ public static List<DoublePathSegment> stringToSegments(BaseController controller, String content, int scale) { if (content == null || content.isBlank()) { return null; } DoublePathParser parser = new DoublePathParser().parse(controller, content, scale); if (parser == null) { return null; } else { return parser.getSegments(); } } public static String segmentsToString(List<DoublePathSegment> segments, String separator) { try { if (segments == null || segments.isEmpty()) { return null; } String path = null; for (DoublePathSegment seg : segments) { if (path != null) { path += separator + seg.text(); } else { path = seg.text(); } } return path; } catch (Exception e) { MyBoxLog.console(e); return null; } } public static boolean addToPath2D(Path2D.Double path, List<DoublePathSegment> segments) { try { if (path == null || segments == null) { return false; } for (DoublePathSegment seg : segments) { PathSegmentType type = seg.getType(); if (type == null) { continue; } switch (type) { case Move: path.moveTo(seg.getEndPoint().getX(), seg.getEndPoint().getY()); break; case Line: case LineHorizontal: case LineVertical: path.lineTo(seg.getEndPoint().getX(), seg.getEndPoint().getY()); break; case Quadratic: case QuadraticSmooth: path.quadTo(seg.getControlPoint1().getX(), seg.getControlPoint1().getY(), seg.getEndPoint().getX(), seg.getEndPoint().getY()); break; case Cubic: case CubicSmooth: path.curveTo(seg.getControlPoint1().getX(), seg.getControlPoint1().getY(), seg.getControlPoint2().getX(), seg.getControlPoint2().getY(), seg.getEndPoint().getX(), seg.getEndPoint().getY()); break; case Arc: double angle = seg.getValue(); Arc2D arc = ExtendedGeneralPath.computeArc( seg.getStartPoint().getX(), seg.getStartPoint().getY(), seg.getArcRadius().getX(), seg.getArcRadius().getY(), angle, seg.isFlag1(), seg.isFlag2(), seg.getEndPoint().getX(), seg.getEndPoint().getY()); // https://svn.apache.org/repos/asf/xmlgraphics/batik/branches/svg11/sources/org/apache/batik/ext/awt/geom/ExtendedGeneralPath.java AffineTransform t = AffineTransform.getRotateInstance( Math.toRadians(angle), arc.getCenterX(), arc.getCenterY()); Shape s = t.createTransformedShape(arc); path.append(s, true); break; case Close: path.closePath(); break; } } return true; } catch (Exception e) { MyBoxLog.console(e); return false; } } public static List<DoublePathSegment> shapeToSegments(Shape shape) { try { if (shape == null) { return null; } PathIterator iterator = shape.getPathIterator(null); if (iterator == null) { return null; } List<DoublePathSegment> segments = new ArrayList<>(); double[] coords = new double[6]; int index = 0; int scale = UserConfig.imageScale(); double currentX = 0, currentY = 0; DoublePathSegment segment; while (!iterator.isDone()) { int type = iterator.currentSegment(coords); switch (type) { case PathIterator.SEG_MOVETO: segment = new DoublePathSegment() .setType(PathSegmentType.Move) .setIsAbsolute(true) .setScale(scale) .setEndPoint(new DoublePoint(coords[0], coords[1])) .setEndPointRel(new DoublePoint(coords[0] - currentX, coords[1] - currentY)) .setStartPoint(new DoublePoint(currentX, currentY)) .setIndex(index++); segments.add(segment); currentX = coords[0]; currentY = coords[1]; break; case PathIterator.SEG_LINETO: segment = new DoublePathSegment() .setType(PathSegmentType.Line) .setIsAbsolute(true) .setScale(scale) .setEndPoint(new DoublePoint(coords[0], coords[1])) .setEndPointRel(new DoublePoint(coords[0] - currentX, coords[1] - currentY)) .setStartPoint(new DoublePoint(currentX, currentY)) .setIndex(index++); segments.add(segment); currentX = coords[0]; currentY = coords[1]; break; case PathIterator.SEG_QUADTO: segment = new DoublePathSegment() .setType(PathSegmentType.Quadratic) .setIsAbsolute(true) .setScale(scale) .setControlPoint1(new DoublePoint(coords[0], coords[1])) .setControlPoint1Rel(new DoublePoint(coords[0] - currentX, coords[1] - currentY)) .setEndPoint(new DoublePoint(coords[2], coords[3])) .setEndPointRel(new DoublePoint(coords[2] - currentX, coords[3] - currentY)) .setStartPoint(new DoublePoint(currentX, currentY)) .setIndex(index++); segments.add(segment); currentX = coords[2]; currentY = coords[3]; break; case PathIterator.SEG_CUBICTO: segment = new DoublePathSegment() .setType(PathSegmentType.Cubic) .setIsAbsolute(true) .setScale(scale) .setControlPoint1(new DoublePoint(coords[0], coords[1])) .setControlPoint1Rel(new DoublePoint(coords[0] - currentX, coords[1] - currentY)) .setControlPoint2(new DoublePoint(coords[2], coords[3])) .setControlPoint2Rel(new DoublePoint(coords[2] - currentX, coords[3] - currentY)) .setEndPoint(new DoublePoint(coords[4], coords[5])) .setEndPointRel(new DoublePoint(coords[4] - currentX, coords[5] - currentY)) .setStartPoint(new DoublePoint(currentX, currentY)) .setIndex(index++); segments.add(segment); currentX = coords[4]; currentY = coords[5]; break; case PathIterator.SEG_CLOSE: segment = new DoublePathSegment() .setType(PathSegmentType.Close) .setIsAbsolute(true) .setScale(scale) .setStartPoint(new DoublePoint(currentX, currentY)) .setIndex(index++); segments.add(segment); break; } iterator.next(); } return segments; } catch (Exception e) { MyBoxLog.console(e); return null; } } public static DoublePath shapeToPathData(Shape shape) { try { List<DoublePathSegment> segments = shapeToSegments(shape); if (segments == null || segments.isEmpty()) { return null; } DoublePath shapeData = new DoublePath(); shapeData.parseSegments(segments); return shapeData; } catch (Exception e) { MyBoxLog.console(e); return null; } } public static String shapeToStringByBatik(Shape shape) { try { if (shape == null) { return null; } DOMImplementation impl = GenericDOMImplementation.getDOMImplementation(); Document myFactory = impl.createDocument("http://www.w3.org/2000/svg", "svg", null); SVGGeneratorContext ctx = SVGGeneratorContext.createDefault(myFactory); return SVGPath.toSVGPathData(shape, ctx); } catch (Exception e) { MyBoxLog.console(e); return null; } } public static DoublePath shapeToPathDataByBatik(Shape shape) { try { String s = shapeToStringByBatik(shape); if (s == null) { return null; } DoublePath shapeData = new DoublePath(); shapeData.parseContent(null, s); return shapeData; } catch (Exception e) { MyBoxLog.console(e); return null; } } public static boolean addToFxPath(Path path, List<DoublePathSegment> segments) { try { if (path == null || segments == null) { return false; } for (DoublePathSegment seg : segments) { path.getElements().add(DoublePathSegment.pathElement(seg)); } return true; } catch (Exception e) { MyBoxLog.console(e); return false; } } public static String typesetting(BaseController controller, String content, String separator, int scale) { try { List<DoublePathSegment> segments = stringToSegments(controller, content, scale); return segmentsToString(segments, separator); } catch (Exception e) { MyBoxLog.console(e); return content; } } public static DoublePath scale(DoublePath path, double scaleX, double scaleY) { try { if (path == null) { return null; } DoublePath scaled = path.copy(); scaled.scale(scaleX, scaleY); return scaled; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static DoublePath translateRel(DoublePath path, double offsetX, double offsetY) { try { if (path == null) { return null; } DoublePath trans = path.copy(); trans.translateRel(offsetX, offsetY); return trans; } catch (Exception e) { MyBoxLog.error(e); return null; } } /* set */ public void setContent(String content) { this.content = content; } public void setSegments(List<DoublePathSegment> segments) { this.segments = segments; } /* get */ public String getContent() { return content; } public List<DoublePathSegment> getSegments() { return segments; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data/Era.java
released/MyBox/src/main/java/mara/mybox/data/Era.java
package mara.mybox.data; import java.util.Date; import mara.mybox.tools.DateTools; import mara.mybox.value.AppValues; import mara.mybox.value.TimeFormats; /** * @Author Mara * @CreateDate 2020-7-13 * @License Apache License Version 2.0 */ /* "1970-01-01 08:00:00 AD" = 0 "0 AD" = "1 BC" = "0" = "-0" = "0000" = "-0000" = "0001-01-01 00:00:00 BC" = -62167420800000 "1 AD" = "1" = "0001" = "0001-01-01 00:00:00" = "0001-01-01 00:00:00 AD" = -62135798400000 "202 BC" = "-203" = "-0203" = "-0203-01-01 00:00:00" = "0202-01-01 00:00:00 BC" = -68510476800000 "202 AD" = "202" = "0202" = "0202-01-01 00:00:00" = "0202-01-01 00:00:00 AD" = -55792742400000 */ public class Era { protected long value = AppValues.InvalidLong; protected String format = TimeFormats.Datetime; protected boolean ignoreAD = true; public Era(long value) { this.value = value; } public Era(long value, String format, boolean ignoreAD) { this.value = value; this.format = format; this.ignoreAD = ignoreAD; } public Era(String s) { Date d = DateTools.encodeDate(s); if (d != null) { value = d.getTime(); } } public String text() { if (value == AppValues.InvalidLong) { return null; } return DateTools.textEra(value, format); } /* get/set */ public long getValue() { return value; } public Era setValue(long value) { this.value = value; return this; } public String getFormat() { return format; } public Era setFormat(String format) { this.format = format; return this; } public boolean isIgnoreAD() { return ignoreAD; } public Era setIgnoreAD(boolean ignoreAD) { this.ignoreAD = ignoreAD; return this; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data/PaginatedPdfTable.java
released/MyBox/src/main/java/mara/mybox/data/PaginatedPdfTable.java
package mara.mybox.data; import java.io.File; import java.util.ArrayList; import java.util.List; import mara.mybox.dev.MyBoxLog; import mara.mybox.tools.PdfTools; import mara.mybox.value.Languages; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDPage; import org.apache.pdfbox.pdmodel.PDPageContentStream; import org.apache.pdfbox.pdmodel.common.PDRectangle; import org.apache.pdfbox.pdmodel.font.PDFont; /** * Reference: https://github.com/eduardohl/Paginated-PDFBox-Table-Sample By * Eduardo Lomonaco * * @Author Mara * @CreateDate 2020-12-10 * @License Apache License Version 2.0 */ public class PaginatedPdfTable { protected File file; protected PDDocument doc; protected List<String> columns; protected List<Integer> columnWidths; protected List<List<String>> rows; protected PDRectangle pageSize; protected String ttf, author, producer, header, footer; protected PDFont textFont; protected float fontSize, margin, cellMargin, contentWidth, contentHeight, rowHeight; protected int rowsPerPage, numberOfPages, defaultZoom, currentPageNumber; protected boolean showPageNumber; public PaginatedPdfTable() { pageSize = PDRectangle.A4; margin = 20; textFont = PdfTools.HELVETICA(); rowHeight = 24; cellMargin = 2; fontSize = 14; } public static PaginatedPdfTable create() { return new PaginatedPdfTable(); } public boolean createDoc(File file) { try { doc = null; if (file == null) { return false; } this.file = file; // MyBoxLog.console("pageSize:" + pageSize.getWidth() + " " + pageSize.getHeight()); contentWidth = pageSize.getWidth() - 2 * margin; contentHeight = pageSize.getHeight() - 2 * margin; if (columnWidths == null) { columnWidths = new ArrayList<>(); } float totalWidth = 0; for (int i = 0; i < columnWidths.size(); i++) { totalWidth += columnWidths.get(i); } if (totalWidth > contentWidth) { columnWidths = new ArrayList<>(); } if (columns.size() > columnWidths.size()) { int avg = (int) ((contentWidth - totalWidth) / (columns.size() - columnWidths.size())); for (int i = columnWidths.size(); i < columns.size(); i++) { columnWidths.add(avg); } } doc = new PDDocument(); rowHeight = fontSize + 2 * cellMargin; // MyBoxLog.console("fontSize:" + fontSize + " cellMargin:" + cellMargin + " rowHeight:" + rowHeight // + " getFontBoundingBox:" + textFont.getFontDescriptor().getFontBoundingBox().getHeight()); rowsPerPage = Double.valueOf(Math.floor(contentHeight / rowHeight)).intValue() - 1; if (ttf != null) { textFont = PdfTools.getFont(doc, ttf); } currentPageNumber = 0; // MyBoxLog.console(textFont.getName() + " " + ttf); return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } public void closeDoc() { if (doc == null) { return; } try { PdfTools.setAttributes(doc, author, defaultZoom); doc.save(file); doc.close(); } catch (Exception e) { MyBoxLog.error(e); } doc = null; } public void writePages() { if (rows == null || rows.isEmpty()) { return; } if (doc == null) { if (file != null) { doc = new PDDocument(); } else { return; } } numberOfPages = Double.valueOf(Math.ceil(rows.size() * 1f / rowsPerPage)).intValue(); // MyBoxLog.console(rowsPerPage + " " + numberOfPages); for (int pageCount = 0; pageCount < numberOfPages; pageCount++) { int startRange = pageCount * rowsPerPage; int endRange = (pageCount * rowsPerPage) + rowsPerPage; if (endRange > rows.size()) { endRange = rows.size(); } List<List<String>> pageRows = new ArrayList<>(); pageRows.addAll(getRows().subList(startRange, endRange)); writePage(pageRows); } } public boolean writePage(List<List<String>> data) { if (doc == null || data == null || data.isEmpty()) { return false; } try { PDPage page = new PDPage(); page.setMediaBox(pageSize); doc.addPage(page); try (PDPageContentStream contentStream = new PDPageContentStream(doc, page)) { contentStream.setFont(textFont, fontSize); float tableTopY = pageSize.getHeight() - margin; // Draws grid and borders float nextY = tableTopY; for (int i = 0; i <= data.size() + 1; i++) { writeLine(contentStream, margin, nextY, margin + getWidth(), nextY); nextY -= rowHeight; } // Draw column lines final float tableYLength = rowHeight + (rowHeight * data.size()); final float tableBottomY = tableTopY - tableYLength; float nextX = margin; writeLine(contentStream, nextX, tableTopY, nextX, tableBottomY); for (int i = 0; i < getNumberOfColumns(); i++) { nextX += columnWidths.get(i); writeLine(contentStream, nextX, tableTopY, nextX, tableBottomY); } // Position cursor to start drawing content float nextTextX = margin + cellMargin; // Calculate center alignment for text in cell considering font height float nextTextY = tableTopY - (rowHeight / 2) - ((textFont.getFontDescriptor().getFontBoundingBox().getHeight() / 1000 * fontSize) / 4); // Write column headers writeRow(contentStream, columns, nextTextX, nextTextY); nextTextY -= rowHeight; nextTextX = margin + cellMargin; // Write content for (int i = 0; i < data.size(); i++) { writeRow(contentStream, data.get(i), nextTextX, nextTextY); nextTextY -= rowHeight; nextTextX = margin + cellMargin; } if (header != null && !header.trim().isEmpty()) { contentStream.beginText(); contentStream.newLineAtOffset(margin, page.getTrimBox().getHeight() - margin + 2); contentStream.showText(header.trim()); contentStream.endText(); } if (footer != null && !footer.trim().isEmpty()) { contentStream.beginText(); contentStream.newLineAtOffset(margin, margin + 2); contentStream.showText(footer.trim()); contentStream.endText(); } if (showPageNumber) { contentStream.beginText(); contentStream.newLineAtOffset(page.getTrimBox().getWidth() - margin * 2 + margin - 80, 5); contentStream.showText(Languages.message("Page") + " " + (++currentPageNumber)); contentStream.endText(); } } catch (Exception e) { MyBoxLog.console(e); } return true; } catch (Exception e) { MyBoxLog.console(e); return false; } } public void writeLine(PDPageContentStream contentStream, float startx, float starty, float endx, float endy) { try { contentStream.moveTo(startx, starty); contentStream.lineTo(endx, endy); contentStream.stroke(); } catch (Exception e) { MyBoxLog.error(e); } } public void writeRow(PDPageContentStream contentStream, List<String> row, float x, float y) { try { float nextX = x; int actualCols = Math.min(getNumberOfColumns(), row.size()); for (int i = 0; i < actualCols; i++) { String text = row.get(i); contentStream.beginText(); contentStream.newLineAtOffset(nextX, y); try { contentStream.showText(text != null ? text : ""); } catch (Exception e) { // MyBoxLog.console(e); } contentStream.endText(); nextX += columnWidths.get(i); } } catch (Exception e) { MyBoxLog.error(e); } } /* get/set */ public Integer getNumberOfColumns() { return this.getColumns().size(); } public float getWidth() { float tableWidth = 0f; for (int width : columnWidths) { tableWidth += width; } return tableWidth; } public float getMargin() { return margin; } public PaginatedPdfTable setMargin(float margin) { this.margin = margin; return this; } public PDRectangle getPageSize() { return pageSize; } public PaginatedPdfTable setPageSize(PDRectangle pageSize) { this.pageSize = pageSize; return this; } public PDFont getTextFont() { return textFont; } public PaginatedPdfTable setTextFont(PDFont textFont) { this.textFont = textFont; return this; } public float getFontSize() { return fontSize; } public PaginatedPdfTable setFontSize(float fontSize) { this.fontSize = fontSize; return this; } public List<String> getColumns() { return columns; } public PaginatedPdfTable setColumns(List<String> columns) { this.columns = columns; return this; } public List<Integer> getColumnWidths() { return columnWidths; } public PaginatedPdfTable setColumnWidths(List<Integer> columnWidths) { this.columnWidths = columnWidths; return this; } public List<List<String>> getRows() { return rows; } public PaginatedPdfTable setRows(List<List<String>> rows) { this.rows = rows; return this; } public float getContentHeight() { return contentHeight; } public PaginatedPdfTable setHeight(float height) { this.contentHeight = height; return this; } public float getRowHeight() { return rowHeight; } public PaginatedPdfTable setRowHeight(float rowHeight) { this.rowHeight = rowHeight; return this; } public float getCellMargin() { return cellMargin; } public PaginatedPdfTable setCellMargin(float cellMargin) { this.cellMargin = cellMargin; return this; } public PDDocument getDoc() { return doc; } public PaginatedPdfTable setDoc(PDDocument doc) { this.doc = doc; return this; } public float getContentWidth() { return contentWidth; } public PaginatedPdfTable setContentWidth(float contentWidth) { this.contentWidth = contentWidth; return this; } public File getFile() { return file; } public void setFile(File file) { this.file = file; } public int getRowsPerPage() { return rowsPerPage; } public void setRowsPerPage(int rowsPerPage) { this.rowsPerPage = rowsPerPage; } public int getNumberOfPages() { return numberOfPages; } public void setNumberOfPages(int numberOfPages) { this.numberOfPages = numberOfPages; } public String getTtf() { return ttf; } public PaginatedPdfTable setTtf(String ttf) { this.ttf = ttf; return this; } public String getAuthor() { return author; } public PaginatedPdfTable setAuthor(String author) { this.author = author; return this; } public String getProducer() { return producer; } public PaginatedPdfTable setProducer(String producer) { this.producer = producer; return this; } public int getDefaultZoom() { return defaultZoom; } public PaginatedPdfTable setDefaultZoom(int defaultZoom) { this.defaultZoom = defaultZoom; return this; } public String getHeader() { return header; } public PaginatedPdfTable setHeader(String header) { this.header = header; return this; } public String getFooter() { return footer; } public PaginatedPdfTable setFooter(String footer) { this.footer = footer; return this; } public boolean isShowPageNumber() { return showPageNumber; } public PaginatedPdfTable setShowPageNumber(boolean showPageNumber) { this.showPageNumber = showPageNumber; return this; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data/MediaInformation.java
released/MyBox/src/main/java/mara/mybox/data/MediaInformation.java
/* * Apache License Version 2.0 */ package mara.mybox.data; import java.io.File; import java.net.URI; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import javafx.scene.media.Media; import javafx.scene.media.MediaException; import javafx.scene.media.Track; import javafx.util.Duration; import mara.mybox.db.table.TableMedia; import mara.mybox.dev.MyBoxLog; import mara.mybox.tools.DateTools; import mara.mybox.tools.FileTools; import mara.mybox.value.Languages; import static mara.mybox.value.Languages.message; /** * * @author mara */ public class MediaInformation extends FileInformation { protected String address, resolution, info, videoEncoding, audioEncoding; protected boolean isCurrent = false, finish = false; protected int width, height; protected String html; public MediaInformation(File file) { super(file); if (file != null) { address = file.getAbsolutePath(); } } public MediaInformation(String address) { this.address = address; } public MediaInformation(URI uri) { this.address = uri.toString(); } public static String exceptionMessage(MediaException exception) { String msg = ""; switch (exception.getType()) { case MEDIA_UNSUPPORTED: String errorMsg = exception.getMessage(); if (errorMsg.contains("ERROR_MEDIA_AUDIO_FORMAT_UNSUPPORTED")) { msg = Languages.message("AUDIO_FORMAT_UNSUPPORTED"); } else if (errorMsg.contains("ERROR_MEDIA_VIDEO_FORMAT_UNSUPPORTED")) { msg = Languages.message("VIDEO_FORMAT_UNSUPPORTED"); } else if (errorMsg.contains("ERROR_MEDIA_AUDIO_FORMAT_UNSUPPORTED")) { msg = Languages.message("MEDIA_UNSUPPORTED"); } break; case MEDIA_CORRUPTED: case MEDIA_INACCESSIBLE: case MEDIA_UNAVAILABLE: case MEDIA_UNSPECIFIED: case OPERATION_UNSUPPORTED: msg = Languages.message(exception.getType().name()); break; default: msg = Languages.message("PLAYBACK_ERROR"); break; } return msg; } public URI getURI() { try { if (file != null) { return file.toURI(); } else { File f = new File(address); if (f.exists()) { setFileAttributes(f); return file.toURI(); } else { return new URI(address); } } } catch (Exception e) { return null; } } public boolean readMediaInfo(Media media) { try { if (address == null || media == null) { return false; } StringBuilder s = new StringBuilder(); s.append(message("Address")).append(getURI().toString()).append("\n"); Duration dur = media.getDuration(); if (dur != null) { setDuration(Math.round(dur.toMillis())); s.append(message("Duration")).append(": ").append(DateTools.datetimeMsDuration(getDuration())).append("\n"); } if (media.getWidth() > 0 && media.getHeight() > 0) { setWidth(media.getWidth()); setHeight(media.getHeight()); s.append(message("Resolution")).append(": ").append(getResolution()).append("\n"); } if (getFileSize() > 0) { s.append(message("Size")).append(": ").append(FileTools.showFileSize(getFileSize())).append("\n"); } Map<String, Object> meta = media.getMetadata(); if (meta != null && !meta.isEmpty()) { for (String mk : meta.keySet()) { s.append(mk).append(": ").append(meta.get(mk).toString()).append("\n"); } } Map<String, Duration> markers = media.getMarkers(); if (markers != null && !markers.isEmpty()) { for (String mk : markers.keySet()) { s.append(mk).append(": ").append(markers.get(mk).toString()).append("\n"); } } List<Track> tracks = media.getTracks(); if (tracks != null && !tracks.isEmpty()) { for (Track track : tracks) { String name = ""; s.append("Track: ").append(track.getTrackID()).append("\n"); if (track.getName() != null) { s.append("Name: ").append(track.getName()).append("\n"); name = track.getName(); } if (track.getLocale() != null) { s.append("Locale: ").append(track.getLocale().getDisplayName()).append("\n"); } Map<String, Object> trackMeta = track.getMetadata(); if (trackMeta != null && !trackMeta.isEmpty()) { for (String mk : trackMeta.keySet()) { s.append(mk).append(": ").append(trackMeta.get(mk).toString()).append("\n"); if (mk.toLowerCase().contains("encoding")) { if (name.toLowerCase().contains("audio")) { setAudioEncoding(name + " " + trackMeta.get(mk).toString()); } else if (name.toLowerCase().contains("video")) { setVideoEncoding(name + " " + trackMeta.get(mk).toString()); } } } } } } setInfo(s.toString()); setFinish(true); makeHtml(media); TableMedia.write(this); return true; } catch (Exception e) { MyBoxLog.debug(e); setFinish(true); return false; } } public void makeHtml(Media media) { if (info == null) { return; } StringBuilder s = new StringBuilder(); s.append("<h1 class=\"center\">").append(getAddress()).append("</h1>\n"); s.append("<hr>\n"); List<String> names = new ArrayList<>(); names.addAll(Arrays.asList(message("Name"), message("Value"))); StringTable table = new StringTable(names); List<String> row = new ArrayList<>(); row.addAll(Arrays.asList(message("Duration"), DateTools.datetimeMsDuration(getDuration()))); table.add(row); row = new ArrayList<>(); row.addAll(Arrays.asList(message("Resolution"), getResolution())); table.add(row); if (getFileSize() > 0) { row = new ArrayList<>(); row.addAll(Arrays.asList(message("Size"), FileTools.showFileSize(getFileSize()))); table.add(row); } if (getVideoEncoding() != null) { row = new ArrayList<>(); row.addAll(Arrays.asList(message("VideoEncoding"), getVideoEncoding())); table.add(row); } if (getAudioEncoding() != null) { row = new ArrayList<>(); row.addAll(Arrays.asList(message("AudioEncoding"), getAudioEncoding())); table.add(row); } s.append(StringTable.tableDiv(table)); if (media == null) { setHtml(s.toString()); return; } Map<String, Object> meta = media.getMetadata(); if (meta != null && !meta.isEmpty()) { s.append("<h2 class=\"center\">").append("MetaData").append("</h2>\n"); names = new ArrayList<>(); names.addAll(Arrays.asList(message("Meta"), message("Value"))); table = new StringTable(names); for (String mk : meta.keySet()) { row = new ArrayList<>(); row.addAll(Arrays.asList(mk, meta.get(mk).toString())); table.add(row); } s.append(StringTable.tableDiv(table)); } Map<String, Duration> markers = media.getMarkers(); if (markers != null && !markers.isEmpty()) { s.append("<h2 class=\"center\">").append("Markers").append("</h2>\n"); names = new ArrayList<>(); names.addAll(Arrays.asList(message("Marker"), message("Value"))); table = new StringTable(names); for (String mk : markers.keySet()) { row = new ArrayList<>(); row.addAll(Arrays.asList(mk, markers.get(mk).toString())); table.add(row); } s.append(StringTable.tableDiv(table)); } List<Track> tracks = media.getTracks(); if (tracks != null && !tracks.isEmpty()) { s.append("<h2 class=\"center\">").append("Tracks").append("</h2>\n"); for (Track track : tracks) { s.append("<h3 class=\"center\">").append("trackID:").append(track.getTrackID()).append("</h3>\n"); names = new ArrayList<>(); names.addAll(Arrays.asList(message("Name"), message("Value"))); table = new StringTable(names); if (track.getName() != null) { row = new ArrayList<>(); row.addAll(Arrays.asList("Name", track.getName())); table.add(row); } if (track.getLocale() != null) { row = new ArrayList<>(); row.addAll(Arrays.asList("Locale", track.getLocale().getDisplayName())); table.add(row); } Map<String, Object> trackMeta = track.getMetadata(); if (trackMeta != null && !trackMeta.isEmpty()) { for (String mk : trackMeta.keySet()) { row = new ArrayList<>(); row.addAll(Arrays.asList(mk, trackMeta.get(mk).toString())); table.add(row); } } s.append(StringTable.tableDiv(table)); } } setHtml(s.toString()); } /* get/set */ public String getVideoEncoding() { if (videoEncoding != null) { return videoEncoding; } else { return ""; } } public void setVideoEncoding(String videoEncoding) { this.videoEncoding = videoEncoding; } public String getAudioEncoding() { if (audioEncoding != null) { return audioEncoding; } else { return ""; } } public void setAudioEncoding(String audioEncoding) { this.audioEncoding = audioEncoding; } public String getResolution() { if (width > 0 && height > 0) { return width + "x" + height; } else { return ""; } } public void setResolution(String resolution) { this.resolution = resolution; } public String getAddress() { return address; } public boolean isIsCurrent() { return isCurrent; } public void setIsCurrent(boolean isCurrent) { this.isCurrent = isCurrent; } public String getInfo() { if (info != null) { return info; } else { return ""; } } public void setInfo(String info) { this.info = info; } public int getWidth() { return width; } public void setWidth(int width) { this.width = width; } public int getHeight() { return height; } public void setHeight(int height) { this.height = height; } public String getHtml() { if (html != null) { return html; } else { return ""; } } public void setHtml(String html) { this.html = html; } public boolean isFinish() { return finish; } public void setFinish(boolean finish) { this.finish = finish; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data/Pagination.java
released/MyBox/src/main/java/mara/mybox/data/Pagination.java
package mara.mybox.data; import mara.mybox.dev.MyBoxLog; /** * @Author Mara * @CreateDate 2025-2-25 * @License Apache License Version 2.0 */ public class Pagination { // 0-based, exclude end public long currentPage, pagesNumber, rowsNumber, startRowOfCurrentPage, endRowOfCurrentPage, objectsNumber, startObjectOfCurrentPage, endObjectOfCurrentPage; public int pageSize, defaultPageSize; public String selection; public ObjectType objectType; public enum ObjectType { Table, Text, Bytes } public Pagination() { init(ObjectType.Table); } public Pagination(ObjectType type) { init(type); } public final void init(ObjectType type) { objectType = type != null ? type : ObjectType.Table; switch (objectType) { case Table: defaultPageSize = 50; break; case Bytes: defaultPageSize = 100000; break; case Text: defaultPageSize = 200; break; } pageSize = defaultPageSize; reset(); } public Pagination init(ObjectType type, int size) { try { init(type); pageSize = size > 0 ? size : defaultPageSize; } catch (Exception e) { MyBoxLog.error(e); } return this; } public final Pagination reset() { rowsNumber = 0; currentPage = 0; pagesNumber = 1; selection = null; startRowOfCurrentPage = 0; endRowOfCurrentPage = 0; startObjectOfCurrentPage = 0; endObjectOfCurrentPage = 0; return this; } public Pagination copyFrom(Pagination p) { if (p == null) { return this; } objectType = p.objectType; pageSize = p.pageSize; defaultPageSize = p.defaultPageSize; rowsNumber = p.rowsNumber; currentPage = p.currentPage; pagesNumber = p.pagesNumber; selection = p.selection; startRowOfCurrentPage = p.startRowOfCurrentPage; endRowOfCurrentPage = p.endRowOfCurrentPage; startObjectOfCurrentPage = p.startObjectOfCurrentPage; endObjectOfCurrentPage = p.endObjectOfCurrentPage; return this; } public Pagination copyTo(Pagination p) { if (p == null) { p = new Pagination(); } p.objectType = objectType; p.pageSize = pageSize; p.defaultPageSize = defaultPageSize; p.rowsNumber = rowsNumber; p.currentPage = currentPage; p.pagesNumber = pagesNumber; p.selection = selection; p.startRowOfCurrentPage = startRowOfCurrentPage; p.endRowOfCurrentPage = endRowOfCurrentPage; p.startObjectOfCurrentPage = startObjectOfCurrentPage; p.endObjectOfCurrentPage = endObjectOfCurrentPage; return p; } public void goPage(long dataSize, long page) { rowsNumber = dataSize < 0 ? 0 : dataSize; if (rowsNumber <= pageSize) { pagesNumber = 1; } else { pagesNumber = rowsNumber / pageSize; if (rowsNumber % pageSize > 0) { pagesNumber++; } } currentPage = fixPage(page); startRowOfCurrentPage = pageSize * currentPage; selection = null; } public void updatePageEnd(long tableSize) { endRowOfCurrentPage = startRowOfCurrentPage + tableSize; } public void updatePageSize(int size) { if (size < 0 || pageSize == size) { return; } pageSize = size; if (rowsNumber <= pageSize) { pagesNumber = 1; } else { pagesNumber = rowsNumber / pageSize; if (rowsNumber % pageSize > 0) { pagesNumber++; } } if (startRowOfCurrentPage <= 0) { startRowOfCurrentPage = 0; currentPage = 0; } else { currentPage = startRowOfCurrentPage / pageSize; if (startRowOfCurrentPage % pageSize > 0) { currentPage++; } if (currentPage >= pagesNumber) { currentPage = pagesNumber - 1; } } } public boolean isValidPage(long page) { return page >= 0 && page <= pagesNumber - 1; } public long fixPage(long page) { if (page >= pagesNumber) { return pagesNumber - 1; } else if (page < 0) { return 0; } else { return page; } } public boolean multipleRows() { return rowsNumber >= 2; } public boolean multiplePages() { return pagesNumber >= 2; } public boolean hasNextPage() { return currentPage < pagesNumber - 1; } public boolean hasPreviousPage() { return currentPage > 0; } public String info() { String s = "rowsNumber:" + rowsNumber + "\n" + "pageSize:" + pageSize + "\n" + "startRowOfCurrentPage:" + startRowOfCurrentPage + "\n" + "endRowOfCurrentPage:" + endRowOfCurrentPage + "\n" + "currentPage:" + currentPage + "\n" + "pagesNumber:" + pagesNumber + "\n" + "startObjectOfCurrentPage:" + startObjectOfCurrentPage + "\n" + "endObjectOfCurrentPage:" + endObjectOfCurrentPage + "\n" + "selection:" + selection; return s; } /* get/set */ public long getRowsNumber() { return rowsNumber; } public Pagination setRowsNumber(long rowsNumber) { this.rowsNumber = rowsNumber; return this; } public long getObjectsNumber() { return objectsNumber; } public Pagination setObjectsNumber(long objectsNumber) { this.objectsNumber = objectsNumber; return this; } public long getCurrentPage() { return currentPage; } public Pagination setCurrentPage(long currentPage) { this.currentPage = currentPage; return this; } public long getPagesNumber() { return pagesNumber; } public Pagination setPagesNumber(long pagesNumber) { this.pagesNumber = pagesNumber; return this; } public long getStartRowOfCurrentPage() { return startRowOfCurrentPage; } public Pagination setStartRowOfCurrentPage(long startRowOfCurrentPage) { this.startRowOfCurrentPage = startRowOfCurrentPage; return this; } public long getEndRowOfCurrentPage() { return endRowOfCurrentPage; } public Pagination setEndRowOfCurrentPage(long endRowOfCurrentPage) { this.endRowOfCurrentPage = endRowOfCurrentPage; return this; } public int getPageSize() { return pageSize; } public Pagination setPageSize(int pageSize) { this.pageSize = pageSize; return this; } public String getSelection() { return selection; } public Pagination setSelection(String selection) { this.selection = selection; return this; } public long getStartObjectOfCurrentPage() { return startObjectOfCurrentPage; } public Pagination setStartObjectOfCurrentPage(long startObjectOfCurrentPage) { this.startObjectOfCurrentPage = startObjectOfCurrentPage; return this; } public long getEndObjectOfCurrentPage() { return endObjectOfCurrentPage; } public Pagination setEndObjectOfCurrentPage(long endObjectOfCurrentPage) { this.endObjectOfCurrentPage = endObjectOfCurrentPage; return this; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data/DoublePathSegment.java
released/MyBox/src/main/java/mara/mybox/data/DoublePathSegment.java
package mara.mybox.data; import javafx.scene.shape.ArcTo; import javafx.scene.shape.ClosePath; import javafx.scene.shape.CubicCurveTo; import javafx.scene.shape.HLineTo; import javafx.scene.shape.LineTo; import javafx.scene.shape.MoveTo; import javafx.scene.shape.PathElement; import javafx.scene.shape.QuadCurveTo; import javafx.scene.shape.VLineTo; import mara.mybox.dev.MyBoxLog; import mara.mybox.tools.DoubleTools; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2023-7-30 * @License Apache License Version 2.0 */ public class DoublePathSegment { protected PathSegmentType type; protected DoublePoint startPoint, controlPoint1, controlPoint2, endPoint, arcRadius; // absoulte coordinate protected DoublePoint controlPoint1Rel, controlPoint2Rel, endPointRel; // relative coordinate protected double value, valueRel; protected boolean isAbsolute, flag1, flag2; protected int index, scale; public static enum PathSegmentType { Move, Line, Quadratic, Cubic, Arc, Close, LineHorizontal, LineVertical, QuadraticSmooth, CubicSmooth } public DoublePathSegment() { index = -1; scale = 3; } public String getTypeName() { if (type == null) { return null; } switch (type) { case Move: return message("Move"); case Line: return message("StraightLine"); case LineHorizontal: return message("LineHorizontal"); case LineVertical: return message("LineVertical"); case Quadratic: return message("QuadraticCurve"); case QuadraticSmooth: return message("QuadraticSmooth"); case Cubic: return message("CubicCurve"); case CubicSmooth: return message("CubicSmooth"); case Arc: return message("ArcCurve"); case Close: return message("Close"); } return null; } public String getCommand() { try { if (type == null) { return null; } if (isAbsolute) { return absCommand(); } else { return relCommand(); } } catch (Exception e) { MyBoxLog.error(e); return null; } } public String getParameters() { try { if (type == null) { return null; } if (isAbsolute) { return absParameters(); } else { return relParameters(); } } catch (Exception e) { MyBoxLog.error(e); return null; } } public String text() { try { if (type == null) { return null; } if (isAbsolute) { return abs(); } else { return rel(); } } catch (Exception e) { MyBoxLog.error(e); return null; } } public String abs() { try { if (type == null) { return null; } return absCommand() + " " + absParameters(); } catch (Exception e) { MyBoxLog.error(e); return null; } } public String rel() { try { if (type == null) { return null; } return relCommand() + " " + relParameters(); } catch (Exception e) { MyBoxLog.error(e); return null; } } public String absCommand() { try { if (type == null) { return null; } switch (type) { case Move: return "M "; case Line: return "L "; case LineHorizontal: return "H "; case LineVertical: return "V "; case Quadratic: return "Q "; case QuadraticSmooth: return "T "; case Cubic: return "C "; case CubicSmooth: return "S "; case Arc: return "A "; case Close: return "Z "; } return null; } catch (Exception e) { MyBoxLog.error(e); return null; } } public String relCommand() { try { if (type == null) { return null; } switch (type) { case Move: return "m "; case Line: return "l "; case LineHorizontal: return "h "; case LineVertical: return "v "; case Quadratic: return "q "; case QuadraticSmooth: return "t "; case Cubic: return "c "; case CubicSmooth: return "s "; case Arc: return "a "; case Close: return "z "; } return null; } catch (Exception e) { MyBoxLog.error(e); return null; } } public String absParameters() { try { if (type == null) { return null; } switch (type) { case Move: case Line: case QuadraticSmooth: return endPoint.text(scale); case LineHorizontal: case LineVertical: return DoubleTools.scaleString(value, scale); case Quadratic: return controlPoint1.text(scale) + " " + endPoint.text(scale); case Cubic: return controlPoint1.text(scale) + " " + controlPoint2.text(scale) + " " + endPoint.text(scale); case CubicSmooth: return controlPoint2.text(scale) + " " + endPoint.text(scale); case Arc: return arcRadius.text(scale) + " " + DoubleTools.scaleString(value, scale) + " " + (flag1 ? 1 : 0) + " " + (flag2 ? 1 : 0) + " " + endPoint.text(scale); case Close: return ""; } return null; } catch (Exception e) { MyBoxLog.error(e); return null; } } public String relParameters() { try { if (type == null) { return null; } switch (type) { case Move: case Line: case QuadraticSmooth: return endPointRel.text(scale); case LineHorizontal: case LineVertical: return DoubleTools.scaleString(valueRel, scale); case Quadratic: return controlPoint1Rel.text(scale) + " " + endPointRel.text(scale); case Cubic: return controlPoint1Rel.text(scale) + " " + controlPoint2Rel.text(scale) + " " + endPointRel.text(scale); case CubicSmooth: return controlPoint2Rel.text(scale) + " " + endPointRel.text(scale); case Arc: return arcRadius.text(scale) + " " + DoubleTools.scaleString(value, scale) + " " + (flag1 ? 1 : 0) + " " + (flag2 ? 1 : 0) + " " + endPointRel.text(scale); case Close: return ""; } return null; } catch (Exception e) { MyBoxLog.error(e); return null; } } public DoublePathSegment copy() { try { DoublePathSegment seg = new DoublePathSegment() .setType(type).setIsAbsolute(isAbsolute) .setValue(value).setValueRel(valueRel) .setFlag1(flag1).setFlag2(flag2) .setScale(scale).setIndex(index); if (startPoint != null) { seg.setStartPoint(startPoint.copy()); } if (controlPoint1 != null) { seg.setControlPoint1(controlPoint1.copy()); } if (controlPoint2 != null) { seg.setControlPoint2(controlPoint2.copy()); } if (endPoint != null) { seg.setEndPoint(endPoint.copy()); } if (arcRadius != null) { seg.setArcRadius(arcRadius.copy()); } if (controlPoint1Rel != null) { seg.setControlPoint1Rel(controlPoint1Rel.copy()); } if (controlPoint2Rel != null) { seg.setControlPoint2Rel(controlPoint2Rel.copy()); } if (endPointRel != null) { seg.setEndPointRel(endPointRel.copy()); } return seg; } catch (Exception e) { MyBoxLog.error(e); return null; } } public DoublePathSegment translate(double offsetX, double offsetY) { try { if (type == null) { return this; } DoublePathSegment seg = copy(); if (startPoint != null) { seg.setStartPoint(startPoint.translate(offsetX, offsetY)); } if (controlPoint1 != null) { seg.setControlPoint1(controlPoint1.translate(offsetX, offsetY)); } if (controlPoint2 != null) { seg.setControlPoint2(controlPoint2.translate(offsetX, offsetY)); } if (endPoint != null) { seg.setEndPoint(endPoint.translate(offsetX, offsetY)); } if (type == PathSegmentType.LineHorizontal) { seg.setValue(value + offsetX); } if (type == PathSegmentType.LineVertical) { seg.setValue(value + offsetY); } return seg; } catch (Exception e) { MyBoxLog.error(e); return null; } } public DoublePathSegment scale(double scaleX, double scaleY) { try { if (type == null) { return this; } DoublePathSegment seg = copy(); if (startPoint != null) { seg.setStartPoint(startPoint.scale(scaleX, scaleY)); } if (controlPoint1 != null) { seg.setControlPoint1(controlPoint1.scale(scaleX, scaleY)); } if (controlPoint2 != null) { seg.setControlPoint2(controlPoint2.scale(scaleX, scaleY)); } if (endPoint != null) { seg.setEndPoint(endPoint.scale(scaleX, scaleY)); } if (arcRadius != null) { seg.setArcRadius(arcRadius.scale(scaleX, scaleY)); } if (controlPoint1Rel != null) { seg.setControlPoint1Rel(controlPoint1Rel.scale(scaleX, scaleY)); } if (controlPoint2Rel != null) { seg.setControlPoint2Rel(controlPoint2Rel.scale(scaleX, scaleY)); } if (endPointRel != null) { seg.setEndPointRel(endPointRel.scale(scaleX, scaleY)); } if (type == PathSegmentType.LineHorizontal) { seg.setValue(value * scaleX); seg.setValueRel(valueRel * scaleX); } if (type == PathSegmentType.LineVertical) { seg.setValue(value * scaleY); seg.setValueRel(valueRel * scaleY); } return seg; } catch (Exception e) { MyBoxLog.error(e); return null; } } /* static */ public static PathElement pathElement(DoublePathSegment segment) { try { if (segment.getType() == null) { return null; } switch (segment.getType()) { case Move: return new MoveTo(segment.endPoint.getX(), segment.endPoint.getY()); case Line: return new LineTo(segment.endPoint.getX(), segment.endPoint.getY()); case LineHorizontal: return new HLineTo(segment.value); case LineVertical: return new VLineTo(segment.value); case Quadratic: case QuadraticSmooth: return new QuadCurveTo( segment.controlPoint1.getX(), segment.controlPoint1.getY(), segment.endPoint.getX(), segment.endPoint.getY()); case Cubic: case CubicSmooth: return new CubicCurveTo( segment.controlPoint1.getX(), segment.controlPoint1.getY(), segment.controlPoint2.getX(), segment.controlPoint2.getY(), segment.endPoint.getX(), segment.endPoint.getY()); case Arc: return new ArcTo( segment.arcRadius.getX(), segment.arcRadius.getY(), segment.value, segment.endPoint.getX(), segment.endPoint.getY(), segment.flag1, segment.flag2); case Close: return new ClosePath(); } return null; } catch (Exception e) { MyBoxLog.error(e); return null; } } /* set */ public DoublePathSegment setType(PathSegmentType type) { this.type = type; return this; } public DoublePathSegment setIsAbsolute(boolean isAbsolute) { this.isAbsolute = isAbsolute; return this; } public DoublePathSegment setValue(double value) { this.value = value; return this; } public DoublePathSegment setFlag1(boolean flag1) { this.flag1 = flag1; return this; } public DoublePathSegment setFlag2(boolean flag2) { this.flag2 = flag2; return this; } public DoublePathSegment setScale(int scale) { this.scale = scale; return this; } public DoublePathSegment setStartPoint(DoublePoint startPoint) { this.startPoint = startPoint; return this; } public DoublePathSegment setControlPoint1(DoublePoint controlPoint1) { this.controlPoint1 = controlPoint1; return this; } public DoublePathSegment setControlPoint2(DoublePoint controlPoint2) { this.controlPoint2 = controlPoint2; return this; } public DoublePathSegment setEndPoint(DoublePoint endPoint) { this.endPoint = endPoint; return this; } public DoublePathSegment setControlPoint1Rel(DoublePoint controlPoint1Rel) { this.controlPoint1Rel = controlPoint1Rel; return this; } public DoublePathSegment setControlPoint2Rel(DoublePoint controlPoint2Rel) { this.controlPoint2Rel = controlPoint2Rel; return this; } public DoublePathSegment setEndPointRel(DoublePoint endPointRel) { this.endPointRel = endPointRel; return this; } public DoublePathSegment setArcRadius(DoublePoint arcRadius) { this.arcRadius = arcRadius; return this; } public DoublePathSegment setValueRel(double valueRel) { this.valueRel = valueRel; return this; } public DoublePathSegment setIndex(int index) { this.index = index; return this; } /* get */ public PathSegmentType getType() { return type; } public DoublePoint getStartPoint() { return startPoint; } public DoublePoint getControlPoint1() { return controlPoint1; } public DoublePoint getControlPoint2() { return controlPoint2; } public DoublePoint getEndPoint() { return endPoint; } public boolean isIsAbsolute() { return isAbsolute; } public double getValue() { return value; } public boolean isFlag1() { return flag1; } public boolean isFlag2() { return flag2; } public int getScale() { return scale; } public DoublePoint getControlPoint1Rel() { return controlPoint1Rel; } public DoublePoint getControlPoint2Rel() { return controlPoint2Rel; } public DoublePoint getEndPointRel() { return endPointRel; } public DoublePoint getArcRadius() { return arcRadius; } public double getValueRel() { return valueRel; } public int getIndex() { return index; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data/DoubleEllipse.java
released/MyBox/src/main/java/mara/mybox/data/DoubleEllipse.java
package mara.mybox.data; import java.awt.geom.Ellipse2D; import static mara.mybox.tools.DoubleTools.imageScale; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2018-11-11 12:29:29 * @License Apache License Version 2.0 */ // https://en.wikipedia.org/wiki/Ellipse public class DoubleEllipse implements DoubleShape { protected double x, y, width, height; public DoubleEllipse() { } public static DoubleEllipse xywh(double x, double y, double width, double height) { DoubleEllipse e = new DoubleEllipse(); e.setX(x); e.setY(y); e.setWidth(width); e.setHeight(height); return e; } public static DoubleEllipse xy12(double x1, double y1, double x2, double y2) { DoubleEllipse e = new DoubleEllipse(); e.setX(Math.min(x1, x2)); e.setY(Math.min(y1, y2)); e.setWidth(Math.abs(x2 - x1)); e.setHeight(Math.abs(y2 - y1)); return e; } public static DoubleEllipse rect(DoubleRectangle rect) { DoubleEllipse e = new DoubleEllipse(); e.setX(rect.getX()); e.setY(rect.getY()); e.setWidth(rect.getWidth()); e.setHeight(rect.getHeight()); return e; } public static DoubleEllipse ellipse(double centerX, double centerY, double radiusX, double radiusY) { DoubleEllipse e = new DoubleEllipse(); e.setX(centerX - radiusX); e.setY(centerY - radiusY); e.setWidth(radiusX * 2); e.setHeight(radiusY * 2); return e; } @Override public String name() { return message("Ellipse"); } public double getCenterX() { return x + width * 0.5; } public double getCenterY() { return y + height * 0.5; } public double getRadiusX() { return width * 0.5; } public double getRadiusY() { return height * 0.5; } // exclude maxX and maxY public double getMaxX() { return x + width; } public double getMaxY() { return y + height; } public void setMaxX(double maxX) { width = Math.abs(maxX - x); } public void setMaxY(double maxY) { height = Math.abs(maxY - y); } public void changeX(double nx) { width = width + x - nx; x = nx; } public void changeY(double ny) { height = height + y - ny; y = ny; } @Override public Ellipse2D.Double getShape() { return new Ellipse2D.Double(x, y, width, height); } @Override public boolean isValid() { return true; } @Override public boolean isEmpty() { return !isValid() || width <= 0 || height <= 0; } @Override public DoubleEllipse copy() { return xywh(x, y, width, height); } @Override public boolean translateRel(double offsetX, double offsetY) { x += offsetX; y += offsetY; return true; } @Override public boolean scale(double scaleX, double scaleY) { width *= scaleX; height *= scaleY; return true; } @Override public String pathAbs() { double sx = imageScale(x); double sy = imageScale(y + height / 2); double rx = imageScale(width / 2); double ry = imageScale(height / 2); return "M " + sx + "," + sy + " \n" + "A " + rx + "," + ry + " 0,0,1 " + imageScale(x + width) + "," + sy + " \n" + "A " + rx + "," + ry + " 0,0,1 " + sx + "," + sy; } @Override public String pathRel() { double sx = imageScale(x); double sy = imageScale(y + height / 2); double rx = imageScale(width / 2); double ry = imageScale(height / 2); double r2 = imageScale(width); return "M " + sx + "," + sy + " \n" + "a " + rx + "," + ry + " 0,0,1 " + r2 + "," + 0 + " \n" + "a " + rx + "," + ry + " 0,0,1 " + (-r2) + "," + 0; } @Override public String elementAbs() { return "<ellipse cx=\"" + imageScale(getCenterX()) + "\"" + " cy=\"" + imageScale(getCenterY()) + "\"" + " rx=\"" + imageScale(getRadiusX()) + "\"" + " ry=\"" + imageScale(getRadiusY()) + "\"> "; } @Override public String elementRel() { return elementAbs(); } /* get */ public double getX() { return x; } public double getY() { return y; } public double getWidth() { return width; } public double getHeight() { return height; } /* set */ public void setX(double x) { this.x = x; } public void setY(double y) { this.y = y; } public void setWidth(double width) { this.width = width; } public void setHeight(double height) { this.height = height; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data/TiffMetaField.java
released/MyBox/src/main/java/mara/mybox/data/TiffMetaField.java
package mara.mybox.data; import java.util.List; /** * @Author Mara * @License Apache License Version 2.0 */ public class TiffMetaField { private String tagNumber, name, type, description; private List<String> values; public static TiffMetaField create() { return new TiffMetaField(); } public String getTagNumber() { return tagNumber; } public void setTagNumber(String tagNumber) { this.tagNumber = tagNumber; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public List<String> getValues() { return values; } public void setValues(List<String> values) { this.values = values; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data/StringTable.java
released/MyBox/src/main/java/mara/mybox/data/StringTable.java
package mara.mybox.data; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import mara.mybox.controller.HtmlTableController; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.style.HtmlStyles; import mara.mybox.tools.HtmlWriteTools; /** * @Author Mara * @CreateDate 2019-8-19 * @License Apache License Version 2.0 */ public class StringTable { protected String title, style = HtmlStyles.TableStyle, comments; protected List<List<String>> data; protected List<String> names; protected static String indent = " "; public StringTable() { } public StringTable(List<String> names) { this.names = names; } public StringTable(String title) { this.title = title; } public StringTable(List<String> names, String title) { this.names = names; this.title = title; data = new ArrayList<>(); } public static StringTable create() { return new StringTable(); } public List<List<String>> add(List<String> row) { if (data == null) { data = new ArrayList<>(); } if (row != null) { data.add(row); } return data; } public List<List<String>> remove(int index) { if (data == null) { data = new ArrayList<>(); } if (index >= 0 && index < data.size()) { data.remove(index); } return data; } public String html() { return tableHtml(this); } public String div() { return tableDiv(this); } public String body() { return body(this); } public void editHtml() { HtmlWriteTools.editHtml(tableHtml(this)); } public void htmlTable() { HtmlTableController.open(tableHtml(this)); } public void newLinkRow(String name, String link) { newNameValueRow(name, "<a href=\"" + link + "\" target=_blank>" + link + "</a>"); } public void newNameValueRow(String name, String value) { List<String> row = new ArrayList<>(); row.addAll(Arrays.asList(name, value)); add(row); } public boolean isEmpty() { return data == null || data.isEmpty(); } public int size() { return data == null ? 0 : data.size(); } /* Static methods */ public static String tableHtml(StringTable table) { if (table == null) { return ""; } return HtmlWriteTools.html(table.getTitle(), "utf-8", table.style, body(table)); } public static String tablePrefix(StringTable table) { try { if (table == null) { return ""; } StringBuilder s = new StringBuilder(); String title = table.getTitle(); if (title != null && !title.isBlank()) { s.append(indent).append(indent).append("<H2 align=\"center\">") .append(HtmlWriteTools.codeToHtml(title)).append("</H2>\n"); } String comments = table.getComments(); if (comments != null && !comments.trim().isEmpty()) { s.append(indent).append(indent) .append(HtmlWriteTools.codeToHtml(comments)).append("\n"); } s.append(indent).append(indent).append("<DIV align=\"center\">\n"); s.append(indent).append(indent).append(indent).append("<TABLE>\n"); List<String> names = table.getNames(); if (names != null) { s.append(indent).append(indent).append(indent).append(indent). append("<TR style=\"font-weight:bold; \">"); for (int i = 0; i < names.size(); ++i) { String name = names.get(i); s.append("<TH>").append(name).append("</TH>"); } s.append("</TR>\n"); } return s.toString(); } catch (Exception e) { MyBoxLog.error(e); return ""; } } public static String tableRow(List<String> row) { try { if (row == null) { return ""; } StringBuilder s = new StringBuilder(); s.append(indent).append(indent).append(indent).append(indent).append("<TR>"); for (int i = 0; i < row.size(); ++i) { String value = row.get(i); s.append("<TD>").append(value == null ? "" : value).append("</TD>"); } s.append("</TR>\n"); return s.toString(); } catch (Exception e) { MyBoxLog.error(e); return ""; } } public static String tableSuffix(StringTable table) { try { if (table == null) { return ""; } StringBuilder s = new StringBuilder(); List<String> names = table.getNames(); if (names != null && (table.getData() != null && table.getData().size() > 15)) { s.append(indent).append(indent).append(indent).append(indent). append("<TR style=\"font-weight:bold; \">"); for (int i = 0; i < names.size(); ++i) { String name = names.get(i); s.append("<TH>").append(name).append("</TH>"); } s.append("</TR>\n"); } s.append(indent).append(indent).append(indent).append("</TABLE>\n"); s.append(indent).append(indent).append("</DIV>\n"); return s.toString(); } catch (Exception e) { MyBoxLog.error(e); return ""; } } public static String tableDiv(StringTable table) { try { if (table == null) { return ""; } StringBuilder s = new StringBuilder(); s.append(tablePrefix(table)); if (table.getData() != null) { for (List<String> row : table.getData()) { s.append(tableRow(row)); } } s.append(tableSuffix(table)); return s.toString(); } catch (Exception e) { MyBoxLog.error(e); return ""; } } public static String body(StringTable table) { try { if (table == null) { return ""; } StringBuilder s = new StringBuilder(); s.append(indent).append("<BODY>\n"); s.append(tableDiv(table)); s.append(indent).append("</BODY>\n"); return s.toString(); } catch (Exception e) { MyBoxLog.error(e); return ""; } } /* get/set */ public String getTitle() { return title; } public StringTable setTitle(String title) { this.title = title; return this; } public List<List<String>> getData() { return data; } public StringTable setData(List<List<String>> data) { this.data = data; return this; } public List<String> getNames() { return names; } public StringTable setNames(List<String> names) { this.names = names; return this; } public String getStyle() { return style; } public StringTable setStyle(String style) { this.style = style; return this; } public String getIndent() { return indent; } public String getComments() { return comments; } public StringTable setComments(String comments) { this.comments = comments; return this; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data/DoubleText.java
released/MyBox/src/main/java/mara/mybox/data/DoubleText.java
package mara.mybox.data; /** * @Author Mara * @CreateDate 2023-7-12 * @License Apache License Version 2.0 */ public class DoubleText extends DoubleRectangle { private String text; public DoubleText() { } public static DoubleText xywh(double x, double y, double width, double height) { DoubleText t = new DoubleText(); t.setX(x); t.setY(y); t.setWidth(width); t.setHeight(height); return t; } @Override public boolean isValid() { return text != null; } @Override public boolean isEmpty() { return !isValid(); } /* get/set */ public String getText() { return text; } public DoubleText setText(String text) { this.text = text; return this; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data/DoublePolygon.java
released/MyBox/src/main/java/mara/mybox/data/DoublePolygon.java
package mara.mybox.data; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static mara.mybox.tools.DoubleTools.imageScale; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2018-11-11 12:29:29 * @Version 1.0 * @Description * @License Apache License Version 2.0 */ public class DoublePolygon implements DoubleShape { private List<DoublePoint> points; public DoublePolygon() { points = new ArrayList<>(); } @Override public String name() { return message("Polygon"); } @Override public java.awt.Polygon getShape() { java.awt.Polygon polygon = new java.awt.Polygon(); for (DoublePoint p : points) { polygon.addPoint((int) p.getX(), (int) p.getY()); } return polygon; } public boolean add(double x, double y) { points.add(new DoublePoint(x, y)); return true; } public boolean addAll(List<DoublePoint> ps) { if (ps == null) { return false; } points.addAll(ps); return true; } public boolean addAll(String values) { return addAll(DoublePoint.parseImageCoordinates(values)); } public boolean setAll(List<DoublePoint> ps) { if (ps == null) { return false; } points.clear(); return addAll(ps); } public boolean set(int index, DoublePoint p) { if (p == null || index < 0 || index >= points.size()) { return false; } points.set(index, p); return true; } public boolean remove(double x, double y) { if (points == null || points.isEmpty()) { return false; } List<Double> d = new ArrayList<>(); for (int i = 0; i < points.size(); ++i) { DoublePoint p = points.get(i); if (p.getX() == x && p.getY() == y) { points.remove(i); break; } } return true; } public boolean remove(int i) { if (points == null || i < 0 || i >= points.size()) { return false; } points.remove(i); return true; } public boolean removeLast() { if (points == null || points.isEmpty()) { return false; } if (remove(points.size() - 1)) { return true; } else { return false; } } @Override public boolean isValid() { return points != null && points.size() > 2; } @Override public boolean isEmpty() { return !isValid() || points.isEmpty(); } public boolean same(DoublePolygon polygon) { if (polygon == null) { return false; } if (points == null || points.isEmpty()) { return polygon.getPoints() == null || polygon.getPoints().isEmpty(); } else { if (polygon.getPoints() == null || points.size() != polygon.getPoints().size()) { return false; } } List<DoublePoint> bPoints = polygon.getPoints(); for (int i = 0; i < points.size(); ++i) { DoublePoint point = points.get(i); if (!point.same(bPoints.get(i))) { return false; } } return true; } @Override public DoublePolygon copy() { DoublePolygon np = new DoublePolygon(); np.addAll(points); return np; } public void clear() { points.clear(); } public List<DoublePoint> getPoints() { return points; } public int getSize() { if (points == null) { return 0; } return points.size(); } public List<Double> getData() { List<Double> d = new ArrayList<>(); for (int i = 0; i < points.size(); ++i) { d.add(points.get(i).getX()); d.add(points.get(i).getY()); } return d; } public Map<String, int[]> getIntXY() { Map<String, int[]> xy = new HashMap<>(); if (points == null || points.isEmpty()) { return xy; } int[] x = new int[points.size()]; int[] y = new int[points.size()]; for (int i = 0; i < points.size(); ++i) { x[i] = (int) Math.round(points.get(i).getX()); y[i] = (int) Math.round(points.get(i).getY()); } xy.put("x", x); xy.put("y", y); return xy; } @Override public boolean translateRel(double offsetX, double offsetY) { List<DoublePoint> moved = new ArrayList<>(); for (int i = 0; i < points.size(); ++i) { DoublePoint p = points.get(i); moved.add(p.translate(offsetX, offsetY)); } points.clear(); points.addAll(moved); return true; } @Override public boolean scale(double scaleX, double scaleY) { List<DoublePoint> scaled = new ArrayList<>(); for (int i = 0; i < points.size(); ++i) { DoublePoint p = points.get(i); scaled.add(p.scale(scaleX, scaleY)); } points.clear(); points.addAll(scaled); return true; } @Override public String pathAbs() { String path = ""; DoublePoint p = points.get(0); path += "M " + imageScale(p.getX()) + "," + imageScale(p.getY()) + "\n"; for (int i = 1; i < points.size(); i++) { p = points.get(i); path += "L " + imageScale(p.getX()) + "," + imageScale(p.getY()) + "\n"; } path += "Z"; return path; } @Override public String pathRel() { String path = ""; DoublePoint p = points.get(0); path += "M " + imageScale(p.getX()) + "," + imageScale(p.getY()) + "\n"; double lastx = p.getX(); double lasty = p.getY(); for (int i = 1; i < points.size(); i++) { p = points.get(i); path += "l " + imageScale(p.getX() - lastx) + "," + imageScale(p.getY() - lasty) + "\n"; lastx = p.getX(); lasty = p.getY(); } path += "z"; return path; } @Override public String elementAbs() { return "<polygon points=\"" + DoublePoint.toText(points, UserConfig.imageScale(), " ") + "\"> "; } @Override public String elementRel() { return elementAbs(); } public DoublePoint get(int i) { if (points == null || points.isEmpty()) { return null; } return points.get(i); } public void setPoints(List<DoublePoint> points) { this.points = points; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data/WeiboSnapParameters.java
released/MyBox/src/main/java/mara/mybox/data/WeiboSnapParameters.java
package mara.mybox.data; import java.io.File; import java.util.Date; import mara.mybox.tools.FileTmpTools; import mara.mybox.tools.PdfTools.PdfImageFormat; import mara.mybox.value.AppVariables; /** * @Author Mara * @CreateDate 2018-9-13 22:17:17 * @License Apache License Version 2.0 */ public class WeiboSnapParameters { private File targetPath = new File(FileTmpTools.generatePath("pdf")); private int webWidth, retry, startPage, loadInterval, snapInterval, likeStartPage, retried, fontSize = 20; private boolean imagePerScreen, isImageSize, addPageNumber, createPDF, createHtml, savePictures, keepPagePdf; private boolean miao, expandComments, expandPicture, fullScreen, openPathWhenStop, useTempFiles, dithering; private String webAddress, author, title, fontFile; private int marginSize, pageWidth, pageHeight, jpegQuality, threshold, maxMergeSize, category, pdfScale, dpi; private Date startMonth, endMonth; private float zoomScale; private File tempdir; private PdfImageFormat format; public static class FileCategoryType { public static int InMonthsPaths = 0; public static int InYearsPaths = 1; public static int InOnePath = 2; } public File getTargetPath() { return targetPath; } public void setTargetPath(File targetPath) { this.targetPath = targetPath; } public boolean isImagePerScreen() { return imagePerScreen; } public void setImagePerScreen(boolean imagePerScreen) { this.imagePerScreen = imagePerScreen; } public boolean isIsImageSize() { return isImageSize; } public void setIsImageSize(boolean isImageSize) { this.isImageSize = isImageSize; } public String getWebAddress() { return webAddress; } public void setWebAddress(String webAddress) { this.webAddress = webAddress; } public Date getStartMonth() { return startMonth; } public void setStartMonth(Date startMonth) { this.startMonth = startMonth; } public Date getEndMonth() { return endMonth; } public void setEndMonth(Date endMonth) { this.endMonth = endMonth; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public int getMarginSize() { return marginSize; } public void setMarginSize(int marginSize) { this.marginSize = marginSize; } public int getPageWidth() { return pageWidth; } public void setPageWidth(int pageWidth) { this.pageWidth = pageWidth; } public int getPageHeight() { return pageHeight; } public void setPageHeight(int pageHeight) { this.pageHeight = pageHeight; } public int getJpegQuality() { return jpegQuality; } public void setJpegQuality(int jpegQuality) { this.jpegQuality = jpegQuality; } public PdfImageFormat getFormat() { return format; } public void setFormat(PdfImageFormat format) { this.format = format; } public int getThreshold() { return threshold; } public void setThreshold(int threshold) { this.threshold = threshold; } public boolean isAddPageNumber() { return addPageNumber; } public void setAddPageNumber(boolean addPageNumber) { this.addPageNumber = addPageNumber; } public boolean isCreatePDF() { return createPDF; } public void setCreatePDF(boolean createPDF) { this.createPDF = createPDF; } public boolean isCreateHtml() { return createHtml; } public void setCreateHtml(boolean createHtml) { this.createHtml = createHtml; } public boolean isKeepPagePdf() { return keepPagePdf; } public void setKeepPagePdf(boolean keepPagePdf) { this.keepPagePdf = keepPagePdf; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public boolean isMiao() { return miao; } public void setMiao(boolean miao) { this.miao = miao; } public int getRetry() { return retry; } public void setRetry(int retry) { this.retry = retry; } public int getMaxMergeSize() { return maxMergeSize; } public void setMaxMergeSize(int maxMergeSize) { this.maxMergeSize = maxMergeSize; } public boolean isExpandComments() { return expandComments; } public void setExpandComments(boolean expandComments) { this.expandComments = expandComments; } public boolean isFullScreen() { return fullScreen; } public void setFullScreen(boolean fullScreen) { this.fullScreen = fullScreen; } public boolean isSavePictures() { return savePictures; } public void setSavePictures(boolean savePictures) { this.savePictures = savePictures; } public boolean isExpandPicture() { return expandPicture; } public void setExpandPicture(boolean expandPicture) { this.expandPicture = expandPicture; } public int getCategory() { return category; } public void setCategory(int category) { this.category = category; } public int getWebWidth() { return webWidth; } public void setWebWidth(int webWidth) { this.webWidth = webWidth; } public float getZoomScale() { return zoomScale; } public void setZoomScale(float zoomScale) { this.zoomScale = zoomScale; } public File getTempdir() { return tempdir; } public void setTempdir(File tempdir) { if (tempdir == null || !tempdir.exists() || !tempdir.isDirectory()) { this.tempdir = AppVariables.MyBoxTempPath; } else { this.tempdir = tempdir; } } public int getPdfScale() { return pdfScale; } public void setPdfScale(int pdfScale) { this.pdfScale = pdfScale; } public boolean isOpenPathWhenStop() { return openPathWhenStop; } public void setOpenPathWhenStop(boolean openPathWhenStop) { this.openPathWhenStop = openPathWhenStop; } public boolean isUseTempFiles() { return useTempFiles; } public void setUseTempFiles(boolean useTempFiles) { this.useTempFiles = useTempFiles; } public String getFontFile() { return fontFile; } public void setFontFile(String fontFile) { this.fontFile = fontFile; } public boolean isDithering() { return dithering; } public void setDithering(boolean dithering) { this.dithering = dithering; } public int getStartPage() { return startPage; } public void setStartPage(int startPage) { this.startPage = startPage; } public int getLoadInterval() { return loadInterval; } public void setLoadInterval(int loadInterval) { this.loadInterval = loadInterval; } public int getSnapInterval() { return snapInterval; } public void setSnapInterval(int snapInterval) { this.snapInterval = snapInterval; } public int getDpi() { return dpi; } public void setDpi(int dpi) { this.dpi = dpi; } public int getLikeStartPage() { return likeStartPage; } public void setLikeStartPage(int likeStartPage) { this.likeStartPage = likeStartPage; } public int getRetried() { return retried; } public void setRetried(int retried) { this.retried = retried; } public int getFontSize() { return fontSize; } public void setFontSize(int fontSize) { this.fontSize = fontSize; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data/SVG.java
released/MyBox/src/main/java/mara/mybox/data/SVG.java
package mara.mybox.data; import java.awt.Rectangle; import java.io.File; import mara.mybox.dev.MyBoxLog; import mara.mybox.tools.SvgTools; import mara.mybox.tools.XmlTools; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; /** * @Author Mara * @CreateDate 2023-6-27 * @License Apache License Version 2.0 */ public class SVG { protected Document doc; protected Element svgNode; protected float width, height, renderedWidth, renderedheight; protected Rectangle viewBox; protected File imageFile; public SVG() { doc = null; svgNode = null; width = -1; height = -1; viewBox = null; imageFile = null; } public SVG(Document doc) { try { this.doc = doc; width = -1; height = -1; viewBox = null; if (doc == null) { return; } svgNode = XmlTools.findName(doc, "svg", 0); NamedNodeMap attrs = svgNode.getAttributes(); if (attrs == null || attrs.getLength() == 0) { return; } for (int i = 0; i < attrs.getLength(); i++) { Node attr = attrs.item(i); String name = attr.getNodeName(); String value = attr.getNodeValue(); if (name == null || value == null) { continue; } try { switch (name.toLowerCase()) { case "width": width = Float.parseFloat(value); break; case "height": height = Float.parseFloat(value); break; case "viewbox": viewBox = SvgTools.viewBox(value); break; } } catch (Exception e) { } } if (viewBox != null) { if (width <= 0) { width = (float) viewBox.getWidth(); } if (height <= 0) { height = (float) viewBox.getHeight(); } } } catch (Exception e) { MyBoxLog.error(e); } } /* get */ public Document getDoc() { return doc; } public Element getSvgNode() { return svgNode; } public float getWidth() { return width; } public float getHeight() { return height; } public Rectangle getViewBox() { return viewBox; } /* set */ public SVG setDoc(Document doc) { this.doc = doc; return this; } public SVG setSvgNode(Element svgNode) { this.svgNode = svgNode; return this; } public SVG setWidth(float width) { this.width = width; return this; } public SVG setHeight(float height) { this.height = height; return this; } public SVG setRenderedWidth(float renderedWidth) { this.renderedWidth = renderedWidth; return this; } public SVG setRenderedheight(float renderedheight) { this.renderedheight = renderedheight; return this; } public SVG setViewBox(Rectangle viewBox) { this.viewBox = viewBox; return this; } public SVG setImageFile(File imageFile) { this.imageFile = imageFile; return this; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data/IntValue.java
released/MyBox/src/main/java/mara/mybox/data/IntValue.java
package mara.mybox.data; /** * @Author Mara * @CreateDate 2019-2-10 12:47:33 * @Version 1.0 * @Description * @License Apache License Version 2.0 */ public class IntValue { private String type, name; private int value; private float percentage; public IntValue() { } public IntValue(int value) { this.type = null; this.name = null; this.value = value; } public IntValue(String name, int value) { this.type = null; this.name = name; this.value = value; } public IntValue(String type, String name, int value) { this.type = type; this.name = name; this.value = value; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getValue() { return value; } public void setValue(int value) { this.value = value; } public float getPercentage() { return percentage; } public void setPercentage(float percentage) { this.percentage = percentage; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data/Link.java
released/MyBox/src/main/java/mara/mybox/data/Link.java
package mara.mybox.data; import java.io.File; import java.net.URL; import java.util.Date; import mara.mybox.dev.MyBoxLog; import mara.mybox.tools.FileNameTools; import mara.mybox.tools.UrlTools; /** * @Author Mara * @CreateDate 2020-10-13 * @License Apache License Version 2.0 */ public class Link { private URL url; private String address, addressOriginal, addressPath, addressFile, title, name, file, fileParent, filename, html; private int index; private Date dlTime; public enum FilenameType { ByLinkName, ByLinkTitle, ByLinkAddress, None } public Link() { } public Link(URL url) { this.url = url; address = url.toString(); } public Link(URL url, String address, String name, String title, int index) { this.url = url; this.address = address; this.name = name; this.title = title; this.index = index; } public String pageName(FilenameType nameType) { String pageName = null; if (nameType == null || nameType == FilenameType.ByLinkName) { pageName = name != null && !name.isBlank() ? name : title; } else if (nameType == FilenameType.ByLinkTitle) { pageName = title != null && !title.isBlank() ? title : name; } if (pageName == null || pageName.isBlank()) { pageName = UrlTools.filePrefix(getUrl()); } return FileNameTools.filter(pageName); } public String filename(File path, FilenameType nameType) { if (url == null || path == null) { return null; } try { String pageName = pageName(nameType); pageName = (pageName == null || pageName.isBlank()) ? "index" : pageName; if (url.getPath().isBlank()) { return path + File.separator + pageName + ".html"; } String suffix = null; if (!getAddress().endsWith("/")) { suffix = UrlTools.fileSuffix(url); } suffix = (suffix == null || suffix.isBlank()) ? ".html" : suffix; return path + File.separator + pageName + suffix; } catch (Exception e) { MyBoxLog.console(e.toString()); return null; } } public static Link create() { return new Link(); } /* customized get/set */ public String getAddress() { if (address == null && url != null) { address = url.toString(); } return address; } public URL getUrl() { if (url == null && address != null) { url = UrlTools.url(address); } return url; } public String getAddressPath() { url = getUrl(); if (url != null) { addressPath = UrlTools.fullPath(url); } return addressPath; } public String getAddressFile() { if (addressFile == null && getUrl() != null) { addressFile = UrlTools.file(url); } return addressFile; } public String getFile() { return file; } public String getFilename() { if (filename == null && file != null) { filename = new File(file).getName(); } return filename; } public String getFileParent() { if (fileParent == null && file != null) { fileParent = new File(file).getParent(); } return fileParent; } /* get/set */ public Link setUrl(URL url) { this.url = url; return this; } public Link setAddress(String address) { this.address = address; return this; } public String getName() { return name; } public Link setName(String name) { this.name = name; return this; } public Link setFile(String file) { this.file = file; return this; } public Link setFileName(String fileName) { this.filename = fileName; return this; } public Link setAddressFile(String addressFile) { this.addressFile = addressFile; return this; } public String getTitle() { return title; } public Link setTitle(String title) { this.title = title; return this; } public int getIndex() { return index; } public Link setIndex(int index) { this.index = index; return this; } public Link setAddressPath(String addressPath) { this.addressPath = addressPath; return this; } public String getAddressOriginal() { return addressOriginal; } public Link setAddressOriginal(String addressOriginal) { this.addressOriginal = addressOriginal; return this; } public Date getDlTime() { return dlTime; } public Link setDlTime(Date dlTime) { this.dlTime = dlTime; return this; } public Link setFilepath(String filepath) { this.fileParent = filepath; return this; } public String getHtml() { return html; } public Link setHtml(String html) { this.html = html; return this; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data/DoubleRectangle.java
released/MyBox/src/main/java/mara/mybox/data/DoubleRectangle.java
package mara.mybox.data; import java.awt.Shape; import java.awt.geom.Rectangle2D; import java.awt.geom.RoundRectangle2D; import java.awt.image.BufferedImage; import javafx.scene.image.Image; import static mara.mybox.tools.DoubleTools.imageScale; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2018-11-11 12:23:40 * @License Apache License Version 2.0 */ public class DoubleRectangle implements DoubleShape { protected double x, y, width, height, roundx, roundy; public DoubleRectangle() { roundx = 0; roundy = 0; } public static DoubleRectangle xywh(double x, double y, double width, double height) { DoubleRectangle rect = new DoubleRectangle(); rect.setX(x); rect.setY(y); rect.setWidth(width); rect.setHeight(height); return rect; } public static DoubleRectangle xy12(double x1, double y1, double x2, double y2) { DoubleRectangle rect = new DoubleRectangle(); rect.setX(Math.min(x1, x2)); rect.setY(Math.min(y1, y2)); rect.setWidth(Math.abs(x2 - x1)); rect.setHeight(Math.abs(y2 - y1)); return rect; } public static DoubleRectangle rect(Rectangle2D.Double rect2D) { if (rect2D == null) { return null; } DoubleRectangle rect = new DoubleRectangle(); rect.setX(rect2D.getX()); rect.setY(rect2D.getY()); rect.setWidth(rect2D.getWidth()); rect.setHeight(rect2D.getHeight()); return rect; } public static DoubleRectangle image(Image image) { if (image == null) { return null; } DoubleRectangle rect = new DoubleRectangle(); rect.setX(0); rect.setY(0); rect.setWidth(image.getWidth()); rect.setHeight(image.getHeight()); return rect; } public static DoubleRectangle image(BufferedImage image) { if (image == null) { return null; } DoubleRectangle rect = new DoubleRectangle(); rect.setX(0); rect.setY(0); rect.setWidth(image.getWidth()); rect.setHeight(image.getHeight()); return rect; } @Override public String name() { return message("Rectangle"); } @Override public Shape getShape() { if (roundx > 0 || roundy > 0) { return new RoundRectangle2D.Double(x, y, width, height, roundx, roundy); } else { return new Rectangle2D.Double(x, y, width, height); } } @Override public DoubleRectangle copy() { DoubleRectangle rect = DoubleRectangle.xywh(x, y, width, height); rect.setRoundx(roundx); rect.setRoundy(roundy); return rect; } @Override public boolean isValid() { return true; } @Override public boolean isEmpty() { return !isValid() || width <= 0 || height <= 0; } public boolean contains(double px, double py) { if (roundx > 0 || roundy > 0) { return DoubleShape.contains(this, px, py); } else { return px >= x && px < x + width && py >= y && py < y + height; } } @Override public boolean translateRel(double offsetX, double offsetY) { x += offsetX; y += offsetY; return true; } @Override public boolean scale(double scaleX, double scaleY) { width *= scaleX; height *= scaleY; return true; } @Override public String pathAbs() { double sx = imageScale(x); double sy = imageScale(y); double sw = imageScale(x + width); double sh = imageScale(y + height); return "M " + sx + "," + sy + " \n" + "H " + sw + " \n" + "V " + sh + " \n" + "H " + sx + " \n" + "V " + sy; } @Override public String pathRel() { double sx = imageScale(x); double sy = imageScale(y); double sw = imageScale(width); double sh = imageScale(height); return "M " + sx + "," + sy + " \n" + "h " + sw + " \n" + "v " + sh + " \n" + "h " + (-sw) + " \n" + "v " + (-sh); } @Override public String elementAbs() { return "<rect x=\"" + imageScale(x) + "\"" + " y=\"" + imageScale(y) + "\"" + " width=\"" + imageScale(width) + "\"" + " height=\"" + imageScale(height) + "\"> "; } @Override public String elementRel() { return elementAbs(); } public boolean same(DoubleRectangle rect) { return rect != null && x == rect.getX() && y == rect.getY() && width == rect.getWidth() && height == rect.getHeight(); } // exclude maxX and maxY public double getMaxX() { return x + width; } public double getMaxY() { return y + height; } public void setMaxX(double maxX) { width = Math.abs(maxX - x); } public void setMaxY(double maxY) { height = Math.abs(maxY - y); } public void changeX(double nx) { width = width + x - nx; x = nx; } public void changeY(double ny) { height = height + y - ny; y = ny; } /* get */ public final double getWidth() { return width; } public void setWidth(double width) { this.width = width; } public final double getHeight() { return height; } public void setHeight(double height) { this.height = height; } public double getX() { return x; } public void setX(double x) { this.x = x; } public double getY() { return y; } public void setY(double y) { this.y = y; } public double getRoundx() { return roundx; } public void setRoundx(double roundx) { this.roundx = roundx; } public double getRoundy() { return roundy; } public void setRoundy(double roundy) { this.roundy = roundy; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data/DoubleShape.java
released/MyBox/src/main/java/mara/mybox/data/DoubleShape.java
package mara.mybox.data; import java.awt.Shape; import java.awt.geom.AffineTransform; import java.awt.geom.Rectangle2D; import java.util.ArrayList; import java.util.List; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.control.MenuItem; import javafx.scene.control.SeparatorMenuItem; import mara.mybox.controller.BaseController; import mara.mybox.controller.BaseShapeController; import mara.mybox.controller.ControlSvgNodeEdit; import mara.mybox.controller.TextEditorController; import mara.mybox.controller.TextPopController; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.style.StyleTools; import static mara.mybox.tools.DoubleTools.imageScale; import static mara.mybox.value.Languages.message; import org.w3c.dom.Element; /** * @Author Mara * @CreateDate 2019-04-02 * @License Apache License Version 2.0 */ public interface DoubleShape { DoubleShape copy(); boolean isValid(); boolean isEmpty(); Shape getShape(); boolean translateRel(double offsetX, double offsetY); boolean scale(double scaleX, double scaleY); String name(); String pathRel(); String pathAbs(); String elementAbs(); String elementRel(); /* static */ public static enum ShapeType { Line, Rectangle, Circle, Ellipse, Polygon, Polyline, Polylines, Cubic, Quadratic, Arc, Path, Text; } public static final double ChangeThreshold = 0.01; public static boolean changed(double offsetX, double offsetY) { return Math.abs(offsetX) > ChangeThreshold || Math.abs(offsetY) > ChangeThreshold; } public static boolean changed(DoublePoint p1, DoublePoint p2) { if (p1 == null || p2 == null) { return false; } return changed(p1.getX() - p2.getX(), p1.getY() - p2.getY()); } public static boolean translateCenterAbs(DoubleShape shapeData, double x, double y) { DoublePoint center = getCenter(shapeData); if (center == null) { return false; } double offsetX = x - center.getX(); double offsetY = y - center.getY(); if (DoubleShape.changed(offsetX, offsetY)) { return shapeData.translateRel(offsetX, offsetY); } return false; } public static boolean translateRel(DoubleShape shapeData, double offsetX, double offsetY) { if (DoubleShape.changed(offsetX, offsetY)) { return shapeData.translateRel(offsetX, offsetY); } return false; } public static boolean scale(DoubleShape shapeData, double scaleX, double scaleY) { try { if (shapeData == null) { return true; } DoublePoint c = getCenter(shapeData); if (shapeData.scale(scaleX, scaleY)) { DoubleShape.translateCenterAbs(shapeData, c.getX(), c.getY()); return true; } else { return false; } } catch (Exception e) { MyBoxLog.error(e); return false; } } public static DoublePath rorate(DoubleShape shapeData, double angle, double x, double y) { try { if (shapeData == null) { return null; } AffineTransform t = AffineTransform.getRotateInstance(Math.toRadians(angle), x, y); Shape shape = t.createTransformedShape(shapeData.getShape()); return DoublePath.shapeToPathData(shape); } catch (Exception e) { MyBoxLog.error(e); return null; } } public static DoublePath shear(DoubleShape shapeData, double x, double y) { try { if (shapeData == null) { return null; } AffineTransform t = AffineTransform.getShearInstance(x, y); Shape shape = t.createTransformedShape(shapeData.getShape()); return DoublePath.shapeToPathData(shape); } catch (Exception e) { MyBoxLog.error(e); return null; } } public static DoublePath pathData(DoubleShape shapeData) { try { if (shapeData == null) { return null; } return DoublePath.shapeToPathData(shapeData.getShape()); } catch (Exception e) { MyBoxLog.error(e); return null; } } // notice bound may truncate values public static Rectangle2D getBound(DoubleShape shapeData) { try { return shapeData.getShape().getBounds2D(); } catch (Exception e) { return null; } } public static boolean contains(DoubleShape shapeData, double x, double y) { return shapeData.isValid() && shapeData.getShape().contains(x, y); } public static DoublePoint getCenter(DoubleShape shapeData) { try { Rectangle2D bound = getBound(shapeData); return new DoublePoint(bound.getCenterX(), bound.getCenterY()); } catch (Exception e) { return null; } } public static String values(DoubleShape shapeData) { try { Rectangle2D bounds = getBound(shapeData); return shapeData.name() + "\n" + message("LeftTop") + ": " + imageScale(bounds.getMinX()) + ", " + imageScale(bounds.getMinY()) + "\n" + message("RightBottom") + ": " + imageScale(bounds.getMaxX()) + ", " + imageScale(bounds.getMaxY()) + "\n" + message("Center") + ": " + imageScale(bounds.getCenterX()) + ", " + imageScale(bounds.getCenterY()) + "\n" + message("Width") + ": " + imageScale(bounds.getWidth()) + " " + message("Height") + ": " + imageScale(bounds.getHeight()); } catch (Exception e) { return ""; } } public static DoubleShape toShape(BaseController controller, Element node) { try { if (node == null) { return null; } switch (node.getNodeName().toLowerCase()) { case "rect": return toRect(node); case "circle": return toCircle(node); case "ellipse": return toEllipse(node); case "line": return toLine(node); case "polyline": return toPolyline(node); case "polygon": return toPolygon(node); case "path": return toPath(controller, node); } } catch (Exception e) { } return null; } public static DoubleRectangle toRect(Element node) { try { float x, y, w, h; try { x = Float.parseFloat(node.getAttribute("x")); } catch (Exception e) { return null; } try { y = Float.parseFloat(node.getAttribute("y")); } catch (Exception e) { return null; } try { w = Float.parseFloat(node.getAttribute("width")); } catch (Exception e) { w = -1f; } if (w <= 0) { return null; } try { h = Float.parseFloat(node.getAttribute("height")); } catch (Exception e) { h = -1f; } if (h <= 0) { return null; } return DoubleRectangle.xywh(x, y, w, h); } catch (Exception e) { MyBoxLog.error(e); return null; } } public static DoubleCircle toCircle(Element node) { try { float x, y, r; try { x = Float.parseFloat(node.getAttribute("cx")); } catch (Exception e) { return null; } try { y = Float.parseFloat(node.getAttribute("cy")); } catch (Exception e) { return null; } try { r = Float.parseFloat(node.getAttribute("r")); } catch (Exception e) { r = -1f; } if (r <= 0) { return null; } return new DoubleCircle(x, y, r); } catch (Exception e) { MyBoxLog.error(e); return null; } } public static DoubleEllipse toEllipse(Element node) { try { float cx, cy, rx, ry; try { cx = Float.parseFloat(node.getAttribute("cx")); } catch (Exception e) { return null; } try { cy = Float.parseFloat(node.getAttribute("cy")); } catch (Exception e) { return null; } try { rx = Float.parseFloat(node.getAttribute("rx")); } catch (Exception e) { rx = -1f; } if (rx <= 0) { return null; } try { ry = Float.parseFloat(node.getAttribute("ry")); } catch (Exception e) { ry = -1f; } if (ry <= 0) { return null; } return DoubleEllipse.ellipse(cx, cy, rx, ry); } catch (Exception e) { MyBoxLog.error(e); return null; } } public static DoubleLine toLine(Element node) { try { float x1, y1, x2, y2; try { x1 = Float.parseFloat(node.getAttribute("x1")); } catch (Exception e) { return null; } try { y1 = Float.parseFloat(node.getAttribute("y1")); } catch (Exception e) { return null; } try { x2 = Float.parseFloat(node.getAttribute("x2")); } catch (Exception e) { return null; } try { y2 = Float.parseFloat(node.getAttribute("y2")); } catch (Exception e) { return null; } return new DoubleLine(x1, y1, x2, y2); } catch (Exception e) { MyBoxLog.error(e); return null; } } public static DoublePolyline toPolyline(Element node) { try { DoublePolyline polyline = new DoublePolyline(); polyline.setAll(DoublePoint.parseImageCoordinates(node.getAttribute("points"))); return polyline; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static DoublePolygon toPolygon(Element node) { try { DoublePolygon polygon = new DoublePolygon(); polygon.setAll(DoublePoint.parseImageCoordinates(node.getAttribute("points"))); return polygon; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static DoublePath toPath(BaseController controller, Element node) { try { String d = node.getAttribute("d"); return new DoublePath(controller, d); } catch (Exception e) { MyBoxLog.error(e); return null; } } public static List<MenuItem> elementMenu(BaseController controller, Element node) { return svgMenu(controller, toShape(controller, node)); } public static List<MenuItem> svgMenu(BaseController controller, DoubleShape shapeData) { if (shapeData == null) { return null; } List<MenuItem> items = new ArrayList<>(); MenuItem menu; if (shapeData instanceof DoublePath) { DoublePath pathData = (DoublePath) shapeData; menu = new MenuItem(message("ConvertToAbsoluteCoordinates"), StyleTools.getIconImageView("iconDelimiter.png")); menu.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent mevent) { if (pathData.toAbs(controller)) { if (controller instanceof BaseShapeController) { ((BaseShapeController) controller).maskShapeDataChanged(); } else if (controller instanceof ControlSvgNodeEdit) { ((ControlSvgNodeEdit) controller).loadPath(pathData.getContent()); } } } }); items.add(menu); menu = new MenuItem(message("ConvertToRelativeCoordinates"), StyleTools.getIconImageView("iconDelimiter.png")); menu.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent mevent) { if (pathData.toRel(controller)) { if (controller instanceof BaseShapeController) { ((BaseShapeController) controller).maskShapeDataChanged(); } else if (controller instanceof ControlSvgNodeEdit) { ((ControlSvgNodeEdit) controller).loadPath(pathData.getContent()); } } } }); items.add(menu); items.add(new SeparatorMenuItem()); } items.addAll(svgInfoMenu(shapeData)); items.add(new SeparatorMenuItem()); return items; } public static List<MenuItem> svgInfoMenu(DoubleShape shapeData) { if (shapeData == null) { return null; } List<MenuItem> items = new ArrayList<>(); MenuItem menu; if (shapeData instanceof DoublePath) { DoublePath pathData = (DoublePath) shapeData; menu = new MenuItem(message("Pop"), StyleTools.getIconImageView("iconPop.png")); menu.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent mevent) { TextPopController.loadText(pathData.getContent()); } }); items.add(menu); menu = new MenuItem(message("TextEditer"), StyleTools.getIconImageView("iconEdit.png")); menu.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent mevent) { TextEditorController.edit(pathData.getContent()); } }); items.add(menu); } if (shapeData instanceof DoublePath || shapeData instanceof DoubleQuadratic || shapeData instanceof DoubleCubic || shapeData instanceof DoubleArc) { menu = new MenuItem(message("DisplaySVGElement") + " - " + message("AbsoluteCoordinate"), StyleTools.getIconImageView("iconView.png")); menu.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent mevent) { TextPopController.loadText(shapeData.elementAbs()); } }); items.add(menu); menu = new MenuItem(message("DisplaySVGElement") + " - " + message("RelativeCoordinate"), StyleTools.getIconImageView("iconMeta.png")); menu.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent mevent) { TextPopController.loadText(shapeData.elementRel()); } }); items.add(menu); } else { menu = new MenuItem(message("DisplaySVGElement"), StyleTools.getIconImageView("iconMeta.png")); menu.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent mevent) { TextPopController.loadText(shapeData.elementAbs()); } }); items.add(menu); menu = new MenuItem(message("DisplaySVGPath") + " - " + message("AbsoluteCoordinate"), StyleTools.getIconImageView("iconMeta.png")); menu.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent mevent) { TextPopController.loadText("<path d=\"\n" + shapeData.pathAbs() + "\n\">"); } }); items.add(menu); menu = new MenuItem(message("DisplaySVGPath") + " - " + message("RelativeCoordinate"), StyleTools.getIconImageView("iconMeta.png")); menu.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent mevent) { TextPopController.loadText("<path d=\"\n" + shapeData.pathRel() + "\n\">"); } }); items.add(menu); } return items; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data/FileInformation.java
released/MyBox/src/main/java/mara/mybox/data/FileInformation.java
package mara.mybox.data; import java.io.File; import javafx.beans.property.BooleanProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.concurrent.Task; import mara.mybox.tools.FileNameTools; import mara.mybox.tools.FileTools; /** * @Author Mara * @CreateDate 2018-6-23 6:44:22 * @Version 1.0 * @Description * @License Apache License Version 2.0 */ public class FileInformation { protected File file; protected long tableIndex, fileSize = -1, createTime, modifyTime, filesNumber = 0; protected String data, handled; protected FileType fileType; protected final BooleanProperty selected = new SimpleBooleanProperty(false); protected long sizeWithSubdir = -1, sizeWithoutSubdir = -1, filesWithSubdir = -1, filesWithoutSubdir = -1; protected long duration; // milliseconds public enum FileType { File, Directory, Link, Socket, Block, Character, FIFO, Root, Digest, NotExist } public enum FileSelectorType { All, ExtensionEuqalAny, ExtensionNotEqualAny, NameIncludeAny, NameIncludeAll, NameNotIncludeAny, NameNotIncludeAll, NameMatchRegularExpression, NameNotMatchRegularExpression, NameIncludeRegularExpression, NameNotIncludeRegularExpression, FileSizeLargerThan, FileSizeSmallerThan, ModifiedTimeEarlierThan, ModifiedTimeLaterThan } public FileInformation() { init(); } public final void init() { file = null; filesNumber = tableIndex = fileSize = createTime = modifyTime = -1; fileType = FileType.NotExist; handled = null; data = null; selected.set(false); sizeWithSubdir = sizeWithoutSubdir = filesWithSubdir = filesWithoutSubdir = -1; duration = 3000; } public FileInformation(File file) { setFileAttributes(file); } public final void setFileAttributes(File file) { init(); this.file = file; if (duration < 0) { duration = 3000; } if (file == null) { return; } if (!file.exists()) { this.fileType = FileType.NotExist; return; } if (file.isFile()) { filesNumber = 1; fileSize = file.length(); fileType = FileType.File; } else if (file.isDirectory()) { // long[] size = FileTools.countDirectorySize(file); // this.filesNumber = size[0]; // this.fileSize = size[1]; sizeWithSubdir = sizeWithoutSubdir = -1; filesWithSubdir = filesWithoutSubdir = -1; fileType = FileType.Directory; } this.createTime = FileTools.createTime(file); this.modifyTime = file.lastModified(); } public void countDirectorySize(Task task, boolean countSubdir, boolean reset) { if (file == null || !file.isDirectory()) { return; } if (countSubdir) { if (reset || sizeWithSubdir < 0 || filesWithSubdir < 0) { long[] size = FileTools.countDirectorySize(file, countSubdir); if (task == null || task.isCancelled()) { return; } filesWithSubdir = size[0]; sizeWithSubdir = size[1]; } fileSize = sizeWithSubdir; filesNumber = filesWithSubdir; } else { if (reset || sizeWithoutSubdir < 0 || filesWithoutSubdir < 0) { long[] size = FileTools.countDirectorySize(file, countSubdir); if (task == null || task.isCancelled()) { return; } filesWithoutSubdir = size[0]; sizeWithoutSubdir = size[1]; } fileSize = sizeWithoutSubdir; filesNumber = filesWithoutSubdir; } } public String getHierarchyNumber() { return hierarchyNumber(file); } public static String hierarchyNumber(File f) { if (f == null) { return ""; } File parent = f.getParentFile(); if (parent == null) { return ""; } String p = hierarchyNumber(parent); String[] children = parent.list(); p = p == null || p.isBlank() ? "" : p + "."; String name = f.getName(); for (int i = 0; i < children.length; i++) { String c = children[i]; if (name.equals(c)) { return p + (i + 1); } } return null; } public static FileInformation clone(FileInformation sourceInfo, FileInformation targetInfo) { if (sourceInfo == null || targetInfo == null) { return null; } targetInfo.file = sourceInfo.file; targetInfo.tableIndex = sourceInfo.tableIndex; targetInfo.fileSize = sourceInfo.fileSize; targetInfo.createTime = sourceInfo.createTime; targetInfo.modifyTime = sourceInfo.modifyTime; targetInfo.filesNumber = sourceInfo.filesNumber; targetInfo.data = sourceInfo.data; targetInfo.handled = sourceInfo.handled; targetInfo.fileType = sourceInfo.fileType; targetInfo.selected.set(sourceInfo.selected.get()); targetInfo.sizeWithSubdir = sourceInfo.sizeWithSubdir; targetInfo.sizeWithoutSubdir = sourceInfo.sizeWithoutSubdir; targetInfo.filesWithSubdir = sourceInfo.filesWithSubdir; targetInfo.filesWithoutSubdir = sourceInfo.filesWithoutSubdir; targetInfo.duration = sourceInfo.duration; return targetInfo; } /* custmized get/set */ public void setFile(File file) { setFileAttributes(file); } public String getSuffix() { if (file != null) { if (file.isDirectory()) { return null; } else { return FileNameTools.ext(file.getName()); } } else if (data != null) { return FileNameTools.ext(data); } else { return null; } } public String getAbsolutePath() { if (file != null) { return file.getAbsolutePath(); } else { return null; } } public String getFullName() { if (file != null) { return file.getAbsolutePath(); } else { return data; } } public String getPath() { if (file != null) { if (file.isDirectory()) { return file.getAbsolutePath() + File.separator; } else { return file.getParent() + File.separator; } } else { return null; } } public String getTfileName() { if (file != null) { if (file.isDirectory()) { return null; } else { return file.getName(); } } else { return null; } } public String getFileName() { if (file != null) { return file.getName(); } else { return null; } } public boolean isSelected() { return selected.get(); } /* get/set */ public File getFile() { return file; } public String getData() { return data; } public void setData(String data) { this.data = data; } public String getHandled() { return handled; } public void setHandled(String handled) { this.handled = handled; } public FileType getFileType() { return fileType; } public void setFileType(FileType fileType) { this.fileType = fileType; } public long getCreateTime() { return createTime; } public void setCreateTime(long createTime) { this.createTime = createTime; } public long getModifyTime() { return modifyTime; } public void setModifyTime(long modifyTime) { this.modifyTime = modifyTime; } public long getFileSize() { return fileSize; } public void setFileSize(long fileSize) { this.fileSize = fileSize; } public long getFilesNumber() { return filesNumber; } public void setFilesNumber(long filesNumber) { this.filesNumber = filesNumber; } public BooleanProperty getSelected() { return selected; } public void setSelected(boolean select) { selected.set(select); } public long getTableIndex() { return tableIndex; } public void setTableIndex(long tableIndex) { this.tableIndex = tableIndex; } public long getDuration() { return duration; } public void setDuration(long duration) { this.duration = duration; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data/LongRange.java
released/MyBox/src/main/java/mara/mybox/data/LongRange.java
package mara.mybox.data; /** * @Author Mara * @CreateDate 2020-10-6 * @License Apache License Version 2.0 */ public class LongRange { protected long start = -1, end = -1, length = -1; public LongRange() { start = -1; end = -1; length = -1; } public LongRange(long start) { this.start = start; } public LongRange(long start, long end) { this.start = start; this.end = end; } public long getLength() { if (length < 0) { length = end - start; } return length; } public long getStart() { return start; } public void setStart(long start) { this.start = start; } public long getEnd() { return end; } public void setEnd(long end) { this.end = end; } public void setLength(long length) { this.length = length; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data/DoublePathParser.java
released/MyBox/src/main/java/mara/mybox/data/DoublePathParser.java
package mara.mybox.data; import java.util.ArrayList; import java.util.List; import mara.mybox.controller.BaseController; import mara.mybox.data.DoublePathSegment.PathSegmentType; import org.apache.batik.parser.PathHandler; import org.apache.batik.parser.PathParser; /** * @Author Mara * @CreateDate 2023-7-30 * @License Apache License Version 2.0 */ public class DoublePathParser implements PathHandler { protected double currentX, currentY; // The point between previous segment and current segment protected double xCenter, yCenter; // for smooth curve protected int index, scale; protected List<DoublePathSegment> segments; public DoublePathParser parse(BaseController controller, String content, int scale) { try { segments = null; this.scale = scale; currentX = 0; currentY = 0; xCenter = 0; yCenter = 0; if (content == null || content.isBlank()) { return null; } PathParser pathParser = new PathParser(); pathParser.setPathHandler(this); pathParser.parse(content); return this; } catch (Exception e) { controller.displayError(e.toString()); return null; } } public List<DoublePathSegment> getSegments() { if (segments == null || segments.isEmpty()) { return null; } List<DoublePathSegment> list = new ArrayList<>(); for (DoublePathSegment seg : segments) { list.add(seg.copy()); } return list; } @Override public void startPath() { segments = new ArrayList<>(); index = 0; } @Override public void endPath() { } @Override public void closePath() { DoublePathSegment segment = new DoublePathSegment() .setType(PathSegmentType.Close) .setIsAbsolute(true) .setStartPoint(new DoublePoint(currentX, currentY)) .setEndPoint(new DoublePoint(currentX, currentY)) .setIndex(index++); segments.add(segment); } @Override public void movetoRel(float x, float y) { xCenter = currentX + x; yCenter = currentY + y; DoublePathSegment segment = new DoublePathSegment() .setType(PathSegmentType.Move) .setIsAbsolute(false) .setScale(scale) .setEndPoint(new DoublePoint(xCenter, yCenter)) .setEndPointRel(new DoublePoint(x, y)) .setStartPoint(new DoublePoint(currentX, currentY)) .setIndex(index++); segments.add(segment); currentX += x; currentY += y; } @Override public void movetoAbs(float x, float y) { xCenter = x; yCenter = y; DoublePathSegment segment = new DoublePathSegment() .setType(PathSegmentType.Move) .setIsAbsolute(true) .setScale(scale) .setEndPoint(new DoublePoint(x, y)) .setEndPointRel(new DoublePoint(x - currentX, y - currentY)) .setStartPoint(new DoublePoint(currentX, currentY)) .setIndex(index++); segments.add(segment); currentX = x; currentY = y; } @Override public void linetoRel(float x, float y) { xCenter = currentX + x; yCenter = currentY + y; DoublePathSegment segment = new DoublePathSegment() .setType(PathSegmentType.Line) .setIsAbsolute(false) .setScale(scale) .setEndPoint(new DoublePoint(xCenter, yCenter)) .setEndPointRel(new DoublePoint(x, y)) .setStartPoint(new DoublePoint(currentX, currentY)) .setIndex(index++); segments.add(segment); currentX += x; currentY += y; } @Override public void linetoAbs(float x, float y) { xCenter = x; yCenter = y; DoublePathSegment segment = new DoublePathSegment() .setType(PathSegmentType.Line) .setIsAbsolute(true) .setScale(scale) .setEndPoint(new DoublePoint(x, y)) .setEndPointRel(new DoublePoint(x - currentX, y - currentY)) .setStartPoint(new DoublePoint(currentX, currentY)) .setIndex(index++); segments.add(segment); currentX = x; currentY = y; } @Override public void linetoHorizontalRel(float x) { xCenter = currentX + x; DoublePathSegment segment = new DoublePathSegment() .setType(PathSegmentType.LineHorizontal) .setIsAbsolute(false) .setScale(scale) .setValue(xCenter) .setValueRel(x) .setEndPoint(new DoublePoint(xCenter, currentY)) .setEndPointRel(new DoublePoint(x, 0)) .setStartPoint(new DoublePoint(currentX, currentY)) .setIndex(index++); segments.add(segment); currentX += x; } @Override public void linetoHorizontalAbs(float x) { xCenter = x; DoublePathSegment segment = new DoublePathSegment() .setType(PathSegmentType.LineVertical) .setIsAbsolute(true) .setScale(scale) .setValue(x) .setEndPoint(new DoublePoint(x, currentY)) .setEndPointRel(new DoublePoint(x - currentX, 0)) .setStartPoint(new DoublePoint(currentX, currentY)) .setIndex(index++); segments.add(segment); currentX = x; } @Override public void linetoVerticalRel(float y) { yCenter = currentY + y; DoublePathSegment segment = new DoublePathSegment() .setType(PathSegmentType.LineVertical) .setIsAbsolute(false) .setScale(scale) .setValue(yCenter) .setValueRel(y) .setEndPoint(new DoublePoint(currentX, yCenter)) .setEndPointRel(new DoublePoint(0, y)) .setStartPoint(new DoublePoint(currentX, currentY)) .setIndex(index++); segments.add(segment); currentY += y; } @Override public void linetoVerticalAbs(float y) { yCenter = y; DoublePathSegment segment = new DoublePathSegment() .setType(PathSegmentType.LineVertical) .setIsAbsolute(true) .setScale(scale) .setValue(y) .setEndPoint(new DoublePoint(currentX, y)) .setEndPointRel(new DoublePoint(0, y - currentY)) .setStartPoint(new DoublePoint(currentX, currentY)) .setIndex(index++); segments.add(segment); currentY = y; } @Override public void curvetoCubicRel(float x1, float y1, float x2, float y2, float x, float y) { xCenter = currentX + x2; yCenter = currentY + y2; DoublePoint p = new DoublePoint(x, y); DoublePathSegment segment = new DoublePathSegment() .setType(PathSegmentType.Cubic) .setIsAbsolute(false) .setScale(scale) .setControlPoint1(new DoublePoint(currentX + x1, currentY + y1)) .setControlPoint1Rel(new DoublePoint(x1, y1)) .setControlPoint2(new DoublePoint(xCenter, yCenter)) .setControlPoint2Rel(new DoublePoint(x2, y2)) .setEndPoint(new DoublePoint(currentX + x, currentY + y)) .setEndPointRel(p) .setStartPoint(new DoublePoint(currentX, currentY)) .setIndex(index++); segments.add(segment); currentX += x; currentY += y; } @Override public void curvetoCubicAbs(float x1, float y1, float x2, float y2, float x, float y) { xCenter = x2; yCenter = y2; DoublePathSegment segment = new DoublePathSegment() .setType(PathSegmentType.Cubic) .setIsAbsolute(true) .setScale(scale) .setControlPoint1(new DoublePoint(x1, y1)) .setControlPoint1Rel(new DoublePoint(x1 - currentX, y1 - currentY)) .setControlPoint2(new DoublePoint(x2, y2)) .setControlPoint2Rel(new DoublePoint(x2 - currentX, y2 - currentY)) .setEndPoint(new DoublePoint(x, y)) .setEndPointRel(new DoublePoint(x - currentX, y - currentY)) .setStartPoint(new DoublePoint(currentX, currentY)) .setIndex(index++); segments.add(segment); currentX = x; currentY = y; } // refer to "org.apache.batik.parser.curvetoCubicSmoothRel" @Override public void curvetoCubicSmoothRel(float x2, float y2, float x, float y) { xCenter = currentX + x2; yCenter = currentY + y2; DoublePathSegment segment = new DoublePathSegment() .setType(PathSegmentType.CubicSmooth) .setIsAbsolute(false) .setScale(scale) .setControlPoint1(new DoublePoint(currentX * 2 - xCenter, currentY * 2 - yCenter)) .setControlPoint1Rel(new DoublePoint(currentX - xCenter, currentY - yCenter)) .setControlPoint2(new DoublePoint(xCenter, yCenter)) .setControlPoint2Rel(new DoublePoint(x2, y2)) .setEndPoint(new DoublePoint(currentX + x, currentY + y)) .setEndPointRel(new DoublePoint(x, y)) .setStartPoint(new DoublePoint(currentX, currentY)) .setIndex(index++); segments.add(segment); currentX += x; currentY += y; } // refer to "org.apache.batik.parser.curvetoCubicSmoothAbs" @Override public void curvetoCubicSmoothAbs(float x2, float y2, float x, float y) { xCenter = x2; yCenter = y2; DoublePathSegment segment = new DoublePathSegment() .setType(PathSegmentType.CubicSmooth) .setIsAbsolute(true) .setScale(scale) .setControlPoint1(new DoublePoint(currentX * 2 - xCenter, currentY * 2 - yCenter)) .setControlPoint1Rel(new DoublePoint(currentX - xCenter, currentY - yCenter)) .setControlPoint2(new DoublePoint(x2, y2)) .setControlPoint2Rel(new DoublePoint(x2 - currentX, y2 - currentY)) .setEndPoint(new DoublePoint(x, y)) .setEndPointRel(new DoublePoint(x - currentX, y - currentY)) .setStartPoint(new DoublePoint(currentX, currentY)) .setIndex(index++); segments.add(segment); currentX = x; currentY = y; } @Override public void curvetoQuadraticRel(float x1, float y1, float x, float y) { xCenter = currentX + x1; yCenter = currentY + y1; DoublePathSegment segment = new DoublePathSegment() .setType(PathSegmentType.Quadratic) .setIsAbsolute(false) .setScale(scale) .setControlPoint1(new DoublePoint(xCenter, yCenter)) .setControlPoint1Rel(new DoublePoint(x1, y1)) .setEndPoint(new DoublePoint(currentX + x, currentY + y)) .setEndPointRel(new DoublePoint(x, y)) .setStartPoint(new DoublePoint(currentX, currentY)) .setIndex(index++); segments.add(segment); currentX += x; currentY += y; } @Override public void curvetoQuadraticAbs(float x1, float y1, float x, float y) { xCenter = x1; yCenter = y1; DoublePathSegment segment = new DoublePathSegment() .setType(PathSegmentType.Quadratic) .setIsAbsolute(true) .setScale(scale) .setControlPoint1(new DoublePoint(x1, y1)) .setControlPoint1Rel(new DoublePoint(x1 - currentX, y1 - currentY)) .setEndPoint(new DoublePoint(x, y)) .setEndPointRel(new DoublePoint(x - currentX, y - currentY)) .setStartPoint(new DoublePoint(currentX, currentY)) .setIndex(index++); segments.add(segment); currentX = x; currentY = y; } // refer to "org.apache.batik.parser.curvetoQuadraticSmoothRel" @Override public void curvetoQuadraticSmoothRel(float x, float y) { xCenter = currentX * 2 - xCenter; yCenter = currentY * 2 - yCenter; DoublePathSegment segment = new DoublePathSegment() .setType(PathSegmentType.QuadraticSmooth) .setIsAbsolute(false) .setScale(scale) .setControlPoint1(new DoublePoint(xCenter, yCenter)) .setControlPoint1Rel(new DoublePoint(xCenter - currentX, yCenter - currentY)) .setEndPoint(new DoublePoint(currentX + x, currentY + y)) .setEndPointRel(new DoublePoint(x, y)) .setStartPoint(new DoublePoint(currentX, currentY)) .setIndex(index++); segments.add(segment); currentX += x; currentY += y; } // refer to "org.apache.batik.parser.curvetoQuadraticSmoothAbs" @Override public void curvetoQuadraticSmoothAbs(float x, float y) { xCenter = currentX * 2 - xCenter; yCenter = currentY * 2 - yCenter; DoublePathSegment segment = new DoublePathSegment() .setType(PathSegmentType.QuadraticSmooth) .setIsAbsolute(true) .setScale(scale) .setControlPoint1(new DoublePoint(xCenter, yCenter)) .setControlPoint1Rel(new DoublePoint(xCenter - currentX, yCenter - currentY)) .setEndPoint(new DoublePoint(x, y)) .setEndPointRel(new DoublePoint(x - currentX, y - currentY)) .setStartPoint(new DoublePoint(currentX, currentY)) .setIndex(index++); segments.add(segment); currentX = x; currentY = y; } @Override public void arcRel(float rx, float ry, float xAxisRotation, boolean largeArcFlag, boolean sweepFlag, float x, float y) { xCenter = currentX + x; yCenter = currentY + y; DoublePathSegment segment = new DoublePathSegment() .setType(PathSegmentType.Arc) .setIsAbsolute(false) .setScale(scale) .setArcRadius(new DoublePoint(rx, ry)) .setEndPoint(new DoublePoint(xCenter, yCenter)) .setEndPointRel(new DoublePoint(x, y)) .setValue(xAxisRotation) .setFlag1(largeArcFlag) .setFlag2(sweepFlag) .setStartPoint(new DoublePoint(currentX, currentY)) .setIndex(index++); segments.add(segment); currentX += x; currentY += y; } @Override public void arcAbs(float rx, float ry, float xAxisRotation, boolean largeArcFlag, boolean sweepFlag, float x, float y) { xCenter = x; yCenter = y; DoublePathSegment segment = new DoublePathSegment() .setType(PathSegmentType.Arc) .setIsAbsolute(true) .setScale(scale) .setArcRadius(new DoublePoint(rx, ry)) .setEndPoint(new DoublePoint(x, y)) .setEndPointRel(new DoublePoint(x - currentX, y - currentY)) .setValue(xAxisRotation) .setFlag1(largeArcFlag) .setFlag2(sweepFlag) .setStartPoint(new DoublePoint(currentX, currentY)) .setIndex(index++); segments.add(segment); currentX = x; currentY = y; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data/ShortCut.java
released/MyBox/src/main/java/mara/mybox/data/ShortCut.java
package mara.mybox.data; import javafx.scene.image.ImageView; import mara.mybox.fxml.style.StyleTools; /** * @Author Mara * @CreateDate 2022-3-1 * @License Apache License Version 2.0 */ public class ShortCut { protected String functionKey, action, possibleAlternative; protected ImageView icon; public ShortCut(String key, String combine, String action, String alt, String iconName) { functionKey = key; if (combine != null && !combine.isBlank()) { functionKey += "+" + combine; } this.action = action; this.possibleAlternative = alt; if (iconName != null && !iconName.isBlank()) { icon = StyleTools.getIconImageView(iconName); } } /* get/set */ public String getFunctionKey() { return functionKey; } public void setFunctionKey(String functionKey) { this.functionKey = functionKey; } public String getAction() { return action; } public void setAction(String action) { this.action = action; } public String getPossibleAlternative() { return possibleAlternative; } public void setPossibleAlternative(String possibleAlternative) { this.possibleAlternative = possibleAlternative; } public ImageView getIcon() { return icon; } public void setIcon(ImageView icon) { this.icon = icon; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data/DoublePoint.java
released/MyBox/src/main/java/mara/mybox/data/DoublePoint.java
package mara.mybox.data; import java.awt.geom.Point2D; import java.util.ArrayList; import java.util.List; import mara.mybox.tools.DoubleTools; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2018-11-11 12:23:02 * @License Apache License Version 2.0 */ public class DoublePoint { public final static String Separator = "\\s+|\\,"; private double x, y; public DoublePoint() { x = Double.NaN; y = Double.NaN; } public DoublePoint(double x, double y) { this.x = x; this.y = y; } public DoublePoint(Point2D p) { this.x = p.getX(); this.y = p.getY(); } public boolean same(DoublePoint p) { if (p == null || !p.valid()) { return !this.valid(); } else if (!this.valid()) { return false; } else { return x == p.getX() && y == p.getY(); } } public boolean valid() { return !DoubleTools.invalidDouble(x) && !DoubleTools.invalidDouble(y); } public DoublePoint translate(double offsetX, double offsetY) { return new DoublePoint(x + offsetX, y + offsetY); } public DoublePoint scale(double scaleX, double scaleY) { return new DoublePoint(x * scaleX, y * scaleY); } public String text(int scale) { return DoubleTools.scale(x, scale) + "," + DoubleTools.scale(y, scale); } public DoublePoint copy() { return new DoublePoint(x, y); } /* static */ public static DoublePoint create() { return new DoublePoint(); } public static DoublePoint imageCoordinate(double x, double y) { int scale = UserConfig.imageScale(); return new DoublePoint(DoubleTools.scale(x, scale), DoubleTools.scale(y, scale)); } public static double distanceSquare(double x1, double y1, double x2, double y2) { double distanceX = x1 - x2; double distanceY = y1 - y2; return distanceX * distanceX + distanceY * distanceY; } public static double distance(double x1, double y1, double x2, double y2) { return Math.sqrt(DoublePoint.distanceSquare(x1, y1, x2, y2)); } public static double distanceSquare(DoublePoint A, DoublePoint B) { double distanceX = A.getX() - B.getX(); double distanceY = A.getY() - B.getY(); return distanceX * distanceX + distanceY * distanceY; } public static double distance(DoublePoint A, DoublePoint B) { return Math.sqrt(distanceSquare(A, B)); } public static int compare(String string1, String string2, String separator, boolean desc) { return compare(parse(string1, separator), parse(string2, separator), desc); } public static int compare(DoublePoint p1, DoublePoint p2, boolean desc) { try { if (p1 == null || !p1.valid()) { if (p2 == null || !p2.valid()) { return 0; } else { return desc ? 1 : -1; } } else { if (p2 == null || !p2.valid()) { return desc ? -1 : 1; } else { int p1c = DoubleTools.compare(p1.x, p2.x, desc); if (p1c == 0) { return DoubleTools.compare(p1.y, p2.y, desc); } else { return p1c; } } } } catch (Exception e) { return 1; } } public static List<DoublePoint> parseImageCoordinates(String string) { return DoublePoint.parseList(string, DoublePoint.Separator, UserConfig.imageScale()); } public static List<DoublePoint> parseList(String string, int scale) { return DoublePoint.parseList(string, DoublePoint.Separator, scale); } public static List<DoublePoint> parseList(String string, String separator, int scale) { try { if (string == null || string.isBlank()) { return null; } String[] vs = string.split(separator); if (vs == null || vs.length < 2) { return null; } List<DoublePoint> list = new ArrayList<>(); for (int i = 0; i < vs.length - 1; i += 2) { list.add(new DoublePoint( DoubleTools.scale(Double.parseDouble(vs[i]), scale), DoubleTools.scale(Double.parseDouble(vs[i + 1]), scale))); } return list; } catch (Exception e) { return null; } } public static DoublePoint parse(String string, String separator) { try { if (string == null || string.isBlank()) { return null; } String[] vs = string.split(separator); if (vs == null || vs.length < 2) { return null; } return new DoublePoint(Double.parseDouble(vs[0]), Double.parseDouble(vs[1])); } catch (Exception e) { return null; } } public static String imageCoordinatesToText(List<DoublePoint> points, String separator) { return toText(points, UserConfig.imageScale(), separator); } public static String toText(List<DoublePoint> points, int scale, String separator) { if (points == null || points.isEmpty()) { return null; } String s = null; for (DoublePoint p : points) { if (s != null) { s += separator; } else { s = ""; } s += DoubleTools.scale(p.getX(), scale) + "," + DoubleTools.scale(p.getY(), scale); } return s; } public static DoublePoint scale(DoublePoint p, int scale) { try { if (p == null || scale < 0) { return p; } return new DoublePoint(DoubleTools.scale(p.getX(), scale), DoubleTools.scale(p.getY(), scale)); } catch (Exception e) { return p; } } public static List<DoublePoint> scaleImageCoordinates(List<DoublePoint> points) { return scaleList(points, UserConfig.imageScale()); } public static List<DoublePoint> scaleList(List<DoublePoint> points, int scale) { if (points == null || points.isEmpty()) { return points; } List<DoublePoint> scaled = new ArrayList<>(); for (DoublePoint p : points) { scaled.add(scale(p, scale)); } return scaled; } public static List<List<DoublePoint>> scaleLists(List<List<DoublePoint>> list, int scale) { if (list == null || list.isEmpty()) { return list; } List<List<DoublePoint>> scaled = new ArrayList<>(); for (List<DoublePoint> points : list) { scaled.add(scaleList(points, scale)); } return scaled; } /* get/set */ public double getX() { return x; } public DoublePoint setX(double x) { this.x = x; return this; } public double getY() { return y; } public DoublePoint setY(double y) { this.y = y; return this; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data/HtmlNode.java
released/MyBox/src/main/java/mara/mybox/data/HtmlNode.java
package mara.mybox.data; import javafx.beans.property.BooleanProperty; import javafx.beans.property.SimpleBooleanProperty; import org.jsoup.nodes.Attributes; import org.jsoup.nodes.Element; /** * @Author Mara * @CreateDate 2023-2-13 * @License Apache License Version 2.0 */ public class HtmlNode { protected Element element; protected final BooleanProperty selected = new SimpleBooleanProperty(false); public HtmlNode() { element = null; } public HtmlNode(String tag) { setElement(new Element(tag)); } public HtmlNode(Element element) { setElement(element); } public boolean equal(HtmlNode node) { Element nodeElement = node.getElement(); if (element == null || nodeElement == null) { return false; } return element.equals(nodeElement); } /* set */ final public void setElement(Element element) { this.element = element; } /* get */ public Element getElement() { return element; } public String getTitle() { return getTag(); } public String getValue() { return getWholeText(); } public String getTag() { return element == null ? null : element.tagName(); } public String getId() { return element == null ? null : element.id(); } public String getName() { return element == null ? null : element.nodeName(); } public String getWholeOwnText() { return element == null ? null : element.wholeOwnText(); } public String getWholeText() { return element == null ? null : element.wholeText(); } public String getText() { return element == null ? null : element.text(); } public String getElementValue() { return element == null ? null : element.val(); } public String getData() { return element == null ? null : element.data(); } public String getInnerHtml() { return element == null ? null : element.html(); } public String getOuterHtml() { return element == null ? null : element.outerHtml(); } public String getClassname() { return element == null ? null : element.className(); } public Attributes getAttributes() { return element == null ? null : element.attributes(); } public BooleanProperty getSelected() { return selected; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data/ProcessParameters.java
released/MyBox/src/main/java/mara/mybox/data/ProcessParameters.java
package mara.mybox.data; import java.io.File; import mara.mybox.dev.MyBoxLog; /** * @Author Mara * @CreateDate 2019-4-11 10:54:30 * @Version 1.0 * @Description * @License Apache License Version 2.0 */ public class ProcessParameters implements Cloneable { public FileInformation currentSourceFile; public File currentTargetPath; public String status, targetPath, targetRootPath; public boolean targetSubDir, isBatch; public int fromPage, toPage, startPage; // 0-based, exclude end public String password; @Override public Object clone() throws CloneNotSupportedException { try { ProcessParameters newCode = (ProcessParameters) super.clone(); if (currentSourceFile != null) { newCode.currentSourceFile = currentSourceFile; } if (currentTargetPath != null) { newCode.currentTargetPath = new File(currentTargetPath.getAbsolutePath()); } return newCode; } catch (Exception e) { MyBoxLog.debug(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data/KeyValue.java
released/MyBox/src/main/java/mara/mybox/data/KeyValue.java
package mara.mybox.data; /** * @Author Mara * @CreateDate 2020-7-30 * @License Apache License Version 2.0 */ public class KeyValue { protected String key; protected String value; public KeyValue(String key, String value) { this.key = key; this.value = value; } /* get/set */ public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data/ListKMeans.java
released/MyBox/src/main/java/mara/mybox/data/ListKMeans.java
package mara.mybox.data; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; /** * @Author Mara * @CreateDate 2019-10-7 * @License Apache License Version 2.0 */ public class ListKMeans<T> { protected List<T> centers; protected List<Integer>[] clusters; protected int k, maxIteration, loopCount; protected long cost; protected Map<T, T> dataMap; protected FxTask task; public ListKMeans() { k = 1; maxIteration = 10000; } public static ListKMeans create() { return new ListKMeans(); } public void initData() { } public boolean isDataEmpty() { return true; } public int dataSize() { return 0; } public T getData(int index) { return null; } public List<T> allData() { return null; } public int centerSize() { return centers != null ? centers.size() : 0; } public void initCenters() { try { centers = new ArrayList<>(); int dataSize = dataSize(); if (dataSize < k) { centers.addAll(allData()); return; } int mod = dataSize / k; for (int i = 0; i < dataSize; i = i + mod) { if (task != null && !task.isWorking()) { return; } centers.add(getData(i)); if (centers.size() == k) { return; } } Random random = new Random(); while (centers.size() < k) { if (task != null && !task.isWorking()) { return; } int index = random.nextInt(dataSize); T d = getData(index); if (!centers.contains(d)) { centers.add(d); } } } catch (Exception e) { MyBoxLog.debug(e); } } public double distance(T p1, T p2) { return 0; } public boolean equal(T p1, T p2) { return true; } public T calculateCenters(List<Integer> ps) { return null; } public boolean run() { loopCount = 0; if (k <= 0) { return false; } if (isDataEmpty()) { initData(); if (isDataEmpty()) { return false; } } if (centers == null || centers.isEmpty()) { initCenters(); if (centers == null || centers.isEmpty()) { return false; } } int dataSize = dataSize(); if (dataSize < k) { clusters = new ArrayList[dataSize]; for (int i = 0; i < dataSize; ++i) { clusters[i] = new ArrayList<>(); clusters[i].add(i); } return true; } clusters = new ArrayList[k]; try { if (task != null) { task.setInfo("data: " + dataSize() + " k:" + k + " maxIteration:" + maxIteration + " loopCount:" + loopCount); } while (true) { if (task != null && !task.isWorking()) { return false; } for (int i = 0; i < k; ++i) { clusters[i] = new ArrayList<>(); } for (int i = 0; i < dataSize; ++i) { if (task != null && !task.isWorking()) { return false; } T p = getData(i); double min = Double.MAX_VALUE; int index = 0; for (int j = 0; j < centers.size(); ++j) { if (task != null && !task.isWorking()) { return false; } T center = centers.get(j); double distance = distance(center, p); if (distance < min) { min = distance; index = j; } } clusters[index].add(i); } boolean centerchange = false; for (int i = 0; i < k; ++i) { if (task != null && !task.isWorking()) { return false; } T newCenter = calculateCenters(clusters[i]); T oldCenter = centers.get(i); if (!equal(newCenter, oldCenter)) { centerchange = true; centers.set(i, newCenter); } } loopCount++; if (!centerchange || loopCount >= maxIteration) { break; } if (task != null && (loopCount % 100 == 0)) { task.setInfo("loopCount:" + loopCount); } } if (task != null) { task.setInfo("loopCount:" + loopCount); task.setInfo("centers: " + centers.size() + " clusters: " + clusters.length); } return true; } catch (Exception e) { MyBoxLog.debug(e); return false; } } public boolean makeMap() { if (isDataEmpty() || centers == null || clusters == null) { return false; } dataMap = new HashMap<>(); for (int i = 0; i < clusters.length; ++i) { if (task != null && !task.isWorking()) { return false; } List<Integer> cluster = clusters[i]; T centerData = centers.get(i); for (Integer index : cluster) { if (task != null && !task.isWorking()) { return false; } dataMap.put(getData(index), centerData); } } // MyBoxLog.debug("dataMap: " + dataMap.size()); return true; } public T belongCenter(T value) { if (isDataEmpty() || value == null || clusters == null) { return value; } for (int i = 0; i < clusters.length; ++i) { if (task != null && !task.isWorking()) { return null; } List<Integer> cluster = clusters[i]; T centerData = centers.get(i); for (Integer index : cluster) { if (task != null && !task.isWorking()) { return null; } if (getData(index) == value) { return centerData; } } } return null; } public T preProcess(T value) { return value; } public T nearestCenter(T value) { try { if (value == null) { return value; } T targetValue = value; double minDistance = Double.MAX_VALUE; for (int i = 0; i < centers.size(); ++i) { if (task != null && !task.isWorking()) { return null; } T centerValue = centers.get(i); double distance = distance(value, centerValue); if (distance < minDistance) { minDistance = distance; targetValue = centerValue; } } return targetValue; } catch (Exception e) { MyBoxLog.debug(e); return null; } } public T map(T value) { try { if (value == null) { return value; } T targetValue = preProcess(value); T mappedValue; if (dataMap == null) { mappedValue = belongCenter(value); } else { mappedValue = dataMap.get(targetValue); } // Some new colors maybe generated outside regions due to dithering again if (mappedValue == null) { mappedValue = nearestCenter(targetValue); // dataMap.put(targetValue, mappedValue); } return mappedValue; } catch (Exception e) { MyBoxLog.debug(e); return null; } } /* get/set */ public List<T> getCenters() { return centers; } public ListKMeans setCenters(List<T> centers) { this.centers = centers; return this; } public int getK() { return k; } public ListKMeans setK(int k) { this.k = k; return this; } public int getMaxIteration() { return maxIteration; } public ListKMeans setMaxIteration(int maxIteration) { this.maxIteration = maxIteration; return this; } public int getLoopCount() { return loopCount; } public void setLoopCount(int loopCount) { this.loopCount = loopCount; } public long getCost() { return cost; } public void setCost(long cost) { this.cost = cost; } public List<Integer>[] getClusters() { return clusters; } public void setClusters(List<Integer>[] clusters) { this.clusters = clusters; } public Map<T, T> getDataMap() { return dataMap; } public void setDataMap(Map<T, T> dataMap) { this.dataMap = dataMap; } public FxTask getTask() { return task; } public ListKMeans setTask(FxTask task) { this.task = task; return this; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data/DoublePolyline.java
released/MyBox/src/main/java/mara/mybox/data/DoublePolyline.java
package mara.mybox.data; import java.awt.Shape; import java.awt.geom.Path2D; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static mara.mybox.tools.DoubleTools.imageScale; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2018-11-11 12:29:29 * @License Apache License Version 2.0 */ public class DoublePolyline implements DoubleShape { private final List<DoublePoint> points; public DoublePolyline() { points = new ArrayList<>(); } @Override public String name() { return message("Polyline"); } @Override public Shape getShape() { Path2D.Double path = new Path2D.Double(); DoublePoint p = points.get(0); path.moveTo(p.getX(), p.getY()); for (int i = 1; i < points.size(); i++) { p = points.get(i); path.lineTo(p.getX(), p.getY()); } return path; } public boolean add(double x, double y) { return add(new DoublePoint(x, y)); } public boolean add(DoublePoint p) { if (p == null) { return false; } points.add(p); return true; } public boolean addAll(List<DoublePoint> ps) { if (ps == null) { return false; } points.addAll(ps); return true; } public boolean addAll(String values) { return addAll(DoublePoint.parseImageCoordinates(values)); } public boolean setAll(List<DoublePoint> ps) { points.clear(); return addAll(ps); } public boolean set(int index, DoublePoint p) { if (p == null || index < 0 || index >= points.size()) { return false; } points.set(index, p); return true; } public boolean remove(double x, double y) { if (points == null || points.isEmpty()) { return false; } for (int i = 0; i < points.size(); ++i) { DoublePoint p = points.get(i); if (p.getX() == x && p.getY() == y) { remove(i); break; } } return true; } public boolean remove(int i) { if (points == null || i < 0 || i >= points.size()) { return false; } points.remove(i); return true; } public boolean removeLast() { if (points == null || points.isEmpty()) { return false; } return remove(points.size() - 1); } @Override public boolean isValid() { return points != null; } @Override public boolean isEmpty() { return !isValid() || points.isEmpty(); } @Override public DoublePolyline copy() { DoublePolyline np = new DoublePolyline(); np.addAll(points); return np; } public boolean same(DoublePolyline polyline) { if (polyline == null) { return false; } if (points == null || points.isEmpty()) { return polyline.getPoints() == null || polyline.getPoints().isEmpty(); } else { if (polyline.getPoints() == null || points.size() != polyline.getPoints().size()) { return false; } } List<DoublePoint> bPoints = polyline.getPoints(); for (int i = 0; i < points.size(); ++i) { DoublePoint point = points.get(i); if (!point.same(bPoints.get(i))) { return false; } } return true; } public void clear() { points.clear(); } public List<DoublePoint> getPoints() { return points; } public int getSize() { if (points == null) { return 0; } return points.size(); } public List<Double> getData() { List<Double> d = new ArrayList<>(); for (int i = 0; i < points.size(); ++i) { d.add(points.get(i).getX()); d.add(points.get(i).getY()); } return d; } public Map<String, int[]> getIntXY() { Map<String, int[]> xy = new HashMap<>(); if (points == null || points.isEmpty()) { return xy; } int[] x = new int[points.size()]; int[] y = new int[points.size()]; for (int i = 0; i < points.size(); ++i) { x[i] = (int) Math.round(points.get(i).getX()); y[i] = (int) Math.round(points.get(i).getY()); } xy.put("x", x); xy.put("y", y); return xy; } @Override public boolean translateRel(double offsetX, double offsetY) { List<DoublePoint> moved = new ArrayList<>(); for (int i = 0; i < points.size(); ++i) { DoublePoint p = points.get(i); moved.add(p.translate(offsetX, offsetY)); } points.clear(); points.addAll(moved); return true; } @Override public boolean scale(double scaleX, double scaleY) { List<DoublePoint> scaled = new ArrayList<>(); for (int i = 0; i < points.size(); ++i) { DoublePoint p = points.get(i); scaled.add(p.scale(scaleX, scaleY)); } points.clear(); points.addAll(scaled); return true; } @Override public String pathAbs() { String path = ""; DoublePoint p = points.get(0); path += "M " + imageScale(p.getX()) + "," + imageScale(p.getY()) + "\n"; for (int i = 1; i < points.size(); i++) { p = points.get(i); path += "L " + imageScale(p.getX()) + "," + imageScale(p.getY()) + "\n"; } return path; } @Override public String pathRel() { String path = ""; DoublePoint p = points.get(0); path += "M " + imageScale(p.getX()) + "," + imageScale(p.getY()) + "\n"; double lastx = p.getX(); double lasty = p.getY(); for (int i = 1; i < points.size(); i++) { p = points.get(i); path += "l " + imageScale(p.getX() - lastx) + "," + imageScale(p.getY() - lasty) + "\n"; lastx = p.getX(); lasty = p.getY(); } return path; } @Override public String elementAbs() { return "<polygon points=\"" + DoublePoint.toText(points, UserConfig.imageScale(), " ") + "\"> "; } @Override public String elementRel() { return elementAbs(); } public DoublePoint get(int i) { if (points == null || points.isEmpty()) { return null; } return points.get(i); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data/TextEditInformation.java
released/MyBox/src/main/java/mara/mybox/data/TextEditInformation.java
package mara.mybox.data; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.OutputStreamWriter; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.tools.FileTmpTools; import mara.mybox.tools.FileTools; import mara.mybox.tools.StringTools; import static mara.mybox.tools.TextTools.bomBytes; import static mara.mybox.tools.TextTools.bomSize; /** * @Author Mara * @CreateDate 2018-12-10 13:06:33 * @License Apache License Version 2.0 */ public class TextEditInformation extends FileEditInformation { public TextEditInformation() { editType = Edit_Type.Text; } public TextEditInformation(File file) { super(file); editType = Edit_Type.Text; initValues(); } @Override public boolean readTotalNumbers(FxTask currentTask) { if (file == null || pagination.pageSize <= 0 || lineBreakValue == null) { return false; } pagination.objectsNumber = 0; pagination.rowsNumber = 0; pagination.pagesNumber = 1; long lineIndex = 0, charIndex = 0; try (BufferedReader reader = new BufferedReader(new FileReader(file, charset))) { String line; while ((line = reader.readLine()) != null) { if (currentTask != null && !currentTask.isWorking()) { return false; } charIndex += line.length(); lineIndex++; } } catch (Exception e) { MyBoxLog.debug(e); return false; } pagination.rowsNumber = lineIndex; pagination.pagesNumber = pagination.rowsNumber / pagination.pageSize; if (pagination.rowsNumber % pagination.pageSize > 0) { pagination.pagesNumber++; } pagination.objectsNumber = charIndex + (pagination.rowsNumber > 0 ? pagination.rowsNumber - 1 : 0); totalNumberRead = true; return true; } @Override public String readPage(FxTask currentTask, long pageNumber) { return readLines(currentTask, pageNumber * pagination.pageSize, pagination.pageSize); } @Override public String readLines(FxTask currentTask, long from, long number) { if (file == null || from < 0 || number <= 0 || (pagination.rowsNumber > 0 && from >= pagination.rowsNumber)) { return null; } long lineIndex = 0, charIndex = 0, lineStart = 0; StringBuilder pageText = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new FileReader(file, charset))) { lineStart = (from / pagination.pageSize) * pagination.pageSize; long lineEnd = Math.max(from + number, lineStart + pagination.pageSize); String line, fixedLine; boolean moreLine = false; while ((line = reader.readLine()) != null) { if (currentTask != null && !currentTask.isWorking()) { return null; } if (lineIndex > 0) { fixedLine = "\n" + line; } else { fixedLine = line; } charIndex += fixedLine.length(); if (lineIndex++ < lineStart) { continue; } if (moreLine) { pageText.append(fixedLine); } else { pageText.append(line); moreLine = true; } if (lineIndex >= lineEnd) { break; } } } catch (Exception e) { MyBoxLog.debug(e); return null; } pagination.currentPage = lineStart / pagination.pageSize; pagination.startObjectOfCurrentPage = charIndex - pageText.length(); pagination.endObjectOfCurrentPage = charIndex; pagination.startRowOfCurrentPage = lineStart; pagination.endRowOfCurrentPage = lineIndex; return pageText.toString(); } @Override public String readObjects(FxTask currentTask, long from, long number) { if (file == null || from < 0 || number <= 0 || (pagination.objectsNumber > 0 && from >= pagination.objectsNumber)) { return null; } long charIndex = 0, lineIndex = 0, lineStart = 0; StringBuilder pageText = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new FileReader(file, charset))) { long to = from + number; boolean moreLine = false; String line, fixedLine; while ((line = reader.readLine()) != null) { if (currentTask != null && !currentTask.isWorking()) { return null; } if (lineIndex > 0) { fixedLine = "\n" + line; } else { fixedLine = line; } if (moreLine) { pageText.append(fixedLine); } else { pageText.append(line); moreLine = true; } charIndex += fixedLine.length(); if (++lineIndex == lineStart + pagination.pageSize && charIndex < from) { lineStart = lineIndex; pageText = new StringBuilder(); moreLine = false; } if (charIndex >= to && lineIndex >= lineStart + pagination.pageSize) { break; } } } catch (Exception e) { MyBoxLog.debug(e); return null; } pagination.currentPage = lineStart / pagination.pageSize; pagination.startObjectOfCurrentPage = charIndex - pageText.length(); pagination.endObjectOfCurrentPage = charIndex; pagination.startRowOfCurrentPage = lineStart; pagination.endRowOfCurrentPage = lineIndex; return pageText.toString(); } @Override public File filter(FxTask currentTask, boolean recordLineNumbers) { try { if (file == null || filterStrings == null || filterStrings.length == 0) { return file; } File targetFile = FileTmpTools.getTempFile(); long lineIndex = 0; try (BufferedReader reader = new BufferedReader(new FileReader(file, charset)); BufferedWriter writer = new BufferedWriter(new FileWriter(targetFile, charset, false))) { String line; while ((line = reader.readLine()) != null) { if (currentTask != null && !currentTask.isWorking()) { return null; } if (isMatchFilters(line)) { if (recordLineNumbers) { line = StringTools.fillRightBlank(lineIndex, 15) + line; } writer.write(line + lineBreakValue); } lineIndex++; } writer.flush(); } return targetFile; } catch (Exception e) { MyBoxLog.debug(e); return null; } } @Override public boolean writeObject(FxTask currentTask, String text) { if (file == null || charset == null || text == null || text.isEmpty()) { return false; } try (BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(file)); OutputStreamWriter writer = new OutputStreamWriter(outputStream, charset)) { if (withBom) { byte[] bytes = bomBytes(charset.name()); outputStream.write(bytes); } if (currentTask != null && !currentTask.isWorking()) { return false; } if (lineBreak != Line_Break.LF) { writer.write(text.replaceAll("\n", lineBreakValue)); } else { writer.write(text); } writer.flush(); } catch (Exception e) { MyBoxLog.debug(e); return false; } return true; } @Override public boolean writePage(FxTask currentTask, FileEditInformation sourceInfo, String pageText) { try { if (sourceInfo.getFile() == null || sourceInfo.getCharset() == null || sourceInfo.pagination.pageSize <= 0 || pageText == null || file == null || charset == null || lineBreakValue == null) { return false; } File targetFile = file; if (sourceInfo.getFile().equals(file)) { targetFile = FileTmpTools.getTempFile(); } try (BufferedReader reader = new BufferedReader(new FileReader(sourceInfo.getFile(), sourceInfo.charset)); BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(targetFile)); OutputStreamWriter writer = new OutputStreamWriter(outputStream, charset)) { if (sourceInfo.isWithBom()) { reader.skip(bomSize(sourceInfo.getCharset().name())); } if (withBom) { byte[] bytes = bomBytes(charset.name()); outputStream.write(bytes); } if (currentTask != null && !currentTask.isWorking()) { return false; } String line, text; long lineIndex = 0, pageLineStart = sourceInfo.pagination.startRowOfCurrentPage, pageLineEnd = sourceInfo.pagination.endRowOfCurrentPage; while ((line = reader.readLine()) != null) { if (currentTask != null && !currentTask.isWorking()) { return false; } text = null; if (lineIndex < pageLineStart || lineIndex >= pageLineEnd) { text = line; } else if (lineIndex == pageLineStart) { if (lineBreak != Line_Break.LF) { text = pageText.replaceAll("\n", lineBreakValue); } else { text = pageText; } } if (text != null) { if (lineIndex > 0) { text = lineBreakValue + text; } writer.write(text); } lineIndex++; } writer.flush(); } catch (Exception e) { MyBoxLog.debug(e); return false; } if (currentTask != null && !currentTask.isWorking()) { return false; } if (sourceInfo.getFile().equals(file)) { FileTools.override(targetFile, file); } return true; } catch (Exception e) { MyBoxLog.debug(e); return false; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data/FindReplaceFile.java
released/MyBox/src/main/java/mara/mybox/data/FindReplaceFile.java
package mara.mybox.data; import java.io.File; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import mara.mybox.controller.BaseController; import mara.mybox.data.FileEditInformation.Edit_Type; import static mara.mybox.data.FindReplaceString.Operation.FindAll; import static mara.mybox.data.FindReplaceString.Operation.ReplaceAll; import mara.mybox.data2d.DataFileCSV; import mara.mybox.db.data.ColumnDefinition; import mara.mybox.db.data.Data2DColumn; import mara.mybox.fxml.FxTask; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2020-11-9 * @License Apache License Version 2.0 */ public class FindReplaceFile extends FindReplaceString { protected BaseController controller; protected FileEditInformation fileInfo; protected long position; protected LongRange fileRange; // location in whole file protected DataFileCSV matchesData; public FindReplaceFile() { } @Override public FindReplaceString reset() { super.reset(); fileRange = null; matchesData = null; return this; } public FindReplaceString findReplaceString() { FindReplaceString findReplaceString = new FindReplaceString() .setOperation(operation) .setInputString(inputString) .setFindString(findString) .setAnchor(anchor) .setUnit(unit) .setReplaceString(replaceString) .setIsRegex(isRegex) .setCaseInsensitive(caseInsensitive) .setMultiline(multiline) .setDotAll(dotAll) .setWrap(wrap); return findReplaceString; } public boolean shouldHandleAsString() { return fileInfo.pagination.pagesNumber < 2 && inputString != null && !inputString.isEmpty(); } public boolean handlePage(FxTask currentTask) { reset(); if (operation == null || fileInfo == null || findString == null || findString.isEmpty()) { return false; } fileInfo.setFindReplace(this); // MyBoxLog.debug("operation:" + operation + " unit:" + unit // + " anchor:" + anchor + " position:" + position + " page:" + fileInfo.getCurrentPage()); if (shouldHandleAsString()) { return handleString(currentTask); } // try current page at first if (operation == Operation.FindNext || operation == Operation.ReplaceFirst || operation == Operation.FindPrevious) { FindReplaceString findReplaceString = findReplaceString().setWrap(false); findReplaceString.handleString(currentTask); if (currentTask != null && !currentTask.isWorking()) { return false; } if (findReplaceString.getStringRange() != null) { stringRange = findReplaceString.getStringRange(); lastMatch = findReplaceString.getLastMatch(); outputString = findReplaceString.getOutputString(); lastReplacedLength = findReplaceString.getLastReplacedLength(); matches = findReplaceString.getMatches(); // MyBoxLog.debug("stringRange:" + stringRange.getStart() + " " + stringRange.getEnd()); fileRange = FindReplaceTextFile.fileRange(this); // MyBoxLog.debug("fileRange:" + fileRange.getStart() + " " + fileRange.getEnd()); return true; } } return false; } public boolean handleFile(FxTask currentTask) { // MyBoxLog.console(operation); reset(); if (operation == null || fileInfo == null || findString == null || findString.isEmpty()) { return false; } fileInfo.setFindReplace(this); // MyBoxLog.debug("operation:" + operation + " unit:" + unit // + " anchor:" + anchor + " position:" + position + " page:" + fileInfo.getCurrentPage()); if (shouldHandleAsString()) { return handleString(currentTask); } // MyBoxLog.debug("findString.length():" + findString.length()); // MyBoxLog.debug(fileInfo.getEditType()); if (fileInfo.getEditType() != Edit_Type.Bytes) { // MyBoxLog.debug("fileFindString.length():" + fileFindString.length()); switch (operation) { case Count: return FindReplaceTextFile.countText(currentTask, fileInfo, this); case FindNext: return FindReplaceTextFile.findNextText(currentTask, fileInfo, this); case FindPrevious: return FindReplaceTextFile.findPreviousText(currentTask, fileInfo, this); case ReplaceFirst: return FindReplaceTextFile.replaceFirstText(currentTask, fileInfo, this); case ReplaceAll: return FindReplaceTextFile.replaceAllText(currentTask, fileInfo, this); case FindAll: return FindReplaceTextFile.findAllText(currentTask, fileInfo, this); default: break; } } else { switch (operation) { case Count: return FindReplaceBytesFile.countBytes(currentTask, fileInfo, this); case FindNext: return FindReplaceBytesFile.findNextBytes(currentTask, fileInfo, this); case FindPrevious: return FindReplaceBytesFile.findPreviousBytes(currentTask, fileInfo, this); case ReplaceFirst: return FindReplaceBytesFile.replaceFirstBytes(currentTask, fileInfo, this); case ReplaceAll: return FindReplaceBytesFile.replaceAllBytes(currentTask, fileInfo, this); case FindAll: return FindReplaceBytesFile.findAllBytes(currentTask, fileInfo, this); default: break; } } return currentTask == null || currentTask.isWorking(); } public void backup(FxTask currentTask, File file) { if (controller == null) { return; } if (file != null && UserConfig.getBoolean(controller.getBaseName() + "BackupWhenSave", true)) { controller.addBackup(currentTask, file); } } public boolean isMultiplePages() { return fileInfo != null && fileInfo.pagination.pagesNumber > 1; } public DataFileCSV initMatchesData(File sourceFile) { String dname = sourceFile == null ? "" : (sourceFile.getName() + "_") + message("Find"); matchesData = new DataFileCSV(); File matchesFile = matchesData.tmpFile(dname, null, "csv"); matchesData.setFile(matchesFile) .setDataName(dname) .setCharset(Charset.forName("UTF-8")) .setDelimiter(",").setHasHeader(true) .setColsNumber(3) .setComments(sourceFile == null ? "" : (message("SourceFile") + ": " + sourceFile + "\n") + message("Find") + ": " + findString); List<Data2DColumn> columns = new ArrayList<>(); if (sourceFile == null) { columns.add(new Data2DColumn(message("File"), ColumnDefinition.ColumnType.String)); } columns.add(new Data2DColumn(message("Start"), ColumnDefinition.ColumnType.Long)); columns.add(new Data2DColumn(message("End"), ColumnDefinition.ColumnType.Long)); columns.add(new Data2DColumn(message("String") + "1", ColumnDefinition.ColumnType.String)); matchesData.setColumns(columns); return matchesData; } /* get/set */ public FileEditInformation getFileInfo() { return fileInfo; } public FindReplaceFile setFileInfo(FileEditInformation fileInfo) { this.fileInfo = fileInfo; return this; } public LongRange getFileRange() { return fileRange; } public FindReplaceFile setFileRange(LongRange lastFound) { this.fileRange = lastFound; return this; } public long getPosition() { return position; } public FindReplaceFile setPosition(long position) { this.position = position; return this; } public DataFileCSV getMatchesData() { return matchesData; } public FindReplaceFile setMatchesData(DataFileCSV matchesData) { this.matchesData = matchesData; return this; } public BaseController getController() { return controller; } public FindReplaceFile setController(BaseController controller) { this.controller = controller; return this; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data/CertificateEntry.java
released/MyBox/src/main/java/mara/mybox/data/CertificateEntry.java
package mara.mybox.data; import java.security.cert.Certificate; /** * @Author Mara * @CreateDate 2019-12-1 * @License Apache License Version 2.0 */ public class CertificateEntry { protected String alias; protected long createTime; protected Certificate[] certificateChain; public static CertificateEntry create() { return new CertificateEntry(); } public String getCertificates() { if (certificateChain == null) { return ""; } String s = ""; for (Certificate cert : certificateChain) { s += cert + "\n\n"; } return s; } public String getAlias() { return alias; } public CertificateEntry setAlias(String alias) { this.alias = alias; return this; } public long getCreateTime() { return createTime; } public CertificateEntry setCreateTime(long createTime) { this.createTime = createTime; return this; } public Certificate[] getCertificateChain() { return certificateChain; } public CertificateEntry setCertificateChain(Certificate[] certificateChain) { this.certificateChain = certificateChain; return this; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data/DoubleValue.java
released/MyBox/src/main/java/mara/mybox/data/DoubleValue.java
package mara.mybox.data; /** * @Author Mara * @CreateDate 2019-2-10 12:47:33 * @Version 1.0 * @Description * @License Apache License Version 2.0 */ public class DoubleValue { private String type, name; private double value; private double percentage; public DoubleValue() { } public DoubleValue(double value) { this.type = null; this.name = null; this.value = value; } public DoubleValue(String name, double value) { this.type = null; this.name = name; this.value = value; } public DoubleValue(String type, String name, double value) { this.type = type; this.name = name; this.value = value; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getValue() { return value; } public void setValue(double value) { this.value = value; } public double getPercentage() { return percentage; } public void setPercentage(double percentage) { this.percentage = percentage; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data/PdfInformation.java
released/MyBox/src/main/java/mara/mybox/data/PdfInformation.java
package mara.mybox.data; import java.awt.image.BufferedImage; import java.io.File; import java.util.Optional; import javafx.application.Platform; import javafx.scene.control.TextInputDialog; import javafx.stage.Stage; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.tools.PdfTools; import static mara.mybox.value.Languages.message; import org.apache.pdfbox.Loader; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDDocumentInformation; import org.apache.pdfbox.pdmodel.PDPage; import org.apache.pdfbox.pdmodel.common.PDRectangle; import org.apache.pdfbox.pdmodel.encryption.AccessPermission; import org.apache.pdfbox.pdmodel.encryption.InvalidPasswordException; import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDDocumentOutline; import org.apache.pdfbox.rendering.ImageType; import org.apache.pdfbox.rendering.PDFRenderer; /** * @Author Mara * @CreateDate 2018-6-9 12:18:38 * @License Apache License Version 2.0 */ public class PdfInformation extends FileInformation { protected String userPassword, ownerPassword, title, subject, author, creator, producer, keywords; protected float version; protected int numberOfPages, fromPage, toPage; // 0-based, exclude end protected String firstPageSize, firstPageSize2, error; protected PDDocument doc; protected PDDocumentOutline outline; protected AccessPermission access; protected boolean infoLoaded; public PdfInformation() { } public PdfInformation(File file) { super(file); fromPage = 0; toPage = 0; doc = null; } public void openDocument(String password) { try { this.userPassword = password; if (doc == null) { doc = Loader.loadPDF(file, password); } infoLoaded = false; } catch (Exception e) { MyBoxLog.error(e); } } public void closeDocument() { try { if (doc != null) { doc.close(); } doc = null; infoLoaded = false; } catch (Exception e) { MyBoxLog.error(e); } } public void loadInformation(FxTask task) { try { if (doc == null) { return; } if (task != null) { task.setInfo(message("ReadingData")); } PDDocumentInformation docInfo = doc.getDocumentInformation(); if (docInfo.getCreationDate() != null) { createTime = docInfo.getCreationDate().getTimeInMillis(); } if (docInfo.getModificationDate() != null) { modifyTime = docInfo.getModificationDate().getTimeInMillis(); } creator = docInfo.getCreator(); producer = docInfo.getProducer(); title = docInfo.getTitle(); subject = docInfo.getSubject(); author = docInfo.getAuthor(); numberOfPages = doc.getNumberOfPages(); keywords = docInfo.getKeywords(); version = doc.getVersion(); access = doc.getCurrentAccessPermission(); if (task != null) { task.setInfo(message("NumberOfPages") + ": " + numberOfPages); } PDPage page = doc.getPage(0); String size = ""; PDRectangle box = page.getMediaBox(); if (box != null) { size += "MediaBox: " + PdfTools.pixels2mm(box.getWidth()) + "mm * " + PdfTools.pixels2mm(box.getHeight()) + "mm"; } box = page.getTrimBox(); if (box != null) { size += " TrimBox: " + PdfTools.pixels2mm(box.getWidth()) + "mm * " + PdfTools.pixels2mm(box.getHeight()) + "mm"; } firstPageSize = size; size = ""; box = page.getCropBox(); if (box != null) { size += "CropBox: " + +PdfTools.pixels2mm(box.getWidth()) + "mm * " + PdfTools.pixels2mm(box.getHeight()) + "mm"; } box = page.getBleedBox(); if (box != null) { size += " BleedBox: " + +PdfTools.pixels2mm(box.getWidth()) + "mm * " + PdfTools.pixels2mm(box.getHeight()) + "mm"; } firstPageSize2 = size; if (task != null) { task.setInfo(message("Size") + ": " + firstPageSize); } outline = doc.getDocumentCatalog().getDocumentOutline(); infoLoaded = true; } catch (Exception e) { MyBoxLog.error(e); } } public void loadInfo(FxTask task, String password) { try { openDocument(password); if (doc == null) { return; } loadInformation(task); closeDocument(); } catch (Exception e) { MyBoxLog.error(e); } } public void readInfo(FxTask task, PDDocument doc) { this.doc = doc; loadInformation(task); } public BufferedImage readPageAsImage(int page) { return readPageAsImage(page, ImageType.ARGB); } public BufferedImage readPageAsImage(int page, ImageType imageType) { try { if (doc == null) { return null; } PDFRenderer renderer = new PDFRenderer(doc); BufferedImage image = renderer.renderImage(page, 1, imageType); return image; } catch (Exception e) { return null; } } public static boolean readPDF(FxTask task, PdfInformation info) { if (info == null) { return false; } if (task != null) { task.setInfo(message("LoadingFileInfo")); } try (PDDocument doc = Loader.loadPDF(info.getFile(), info.getUserPassword())) { info.readInfo(task, doc); doc.close(); return true; } catch (InvalidPasswordException e) { try { Platform.runLater(() -> { TextInputDialog dialog = new TextInputDialog(); dialog.setContentText(message("UserPassword")); Stage stage = (Stage) dialog.getDialogPane().getScene().getWindow(); stage.setAlwaysOnTop(true); stage.toFront(); Optional<String> result = dialog.showAndWait(); if (result.isPresent()) { info.setUserPassword(result.get()); } synchronized (info) { info.notifyAll(); } }); synchronized (info) { info.wait(); } Platform.requestNextPulse(); try (PDDocument doc = Loader.loadPDF(info.getFile(), info.getUserPassword())) { info.readInfo(task, doc); doc.close(); return true; } catch (Exception ee) { info.setError(ee.toString()); return false; } } catch (Exception eee) { info.setError(eee.toString()); return false; } } catch (Exception eeee) { info.setError(eeee.toString()); return false; } } // cell values public int getFrom() { return fromPage + 1; } public int getTo() { return toPage; } /* get/set */ public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public float getVersion() { return version; } public void setVersion(float version) { this.version = version; } public int getNumberOfPages() { return numberOfPages; } public void setNumberOfPages(int numberOfPages) { this.numberOfPages = numberOfPages; } public String getCreator() { return creator; } public void setCreator(String creator) { this.creator = creator; } public String getProducer() { return producer; } public void setProducer(String producer) { this.producer = producer; } public String getFirstPageSize() { return firstPageSize; } public void setFirstPageSize(String firstPageSize) { this.firstPageSize = firstPageSize; } public String getFirstPageSize2() { return firstPageSize2; } public void setFirstPageSize2(String firstPageSize2) { this.firstPageSize2 = firstPageSize2; } public PDDocument getDoc() { return doc; } public void setDoc(PDDocument doc) { this.doc = doc; } public boolean isInfoLoaded() { return infoLoaded; } public void setInfoLoaded(boolean infoLoaded) { this.infoLoaded = infoLoaded; } public PDDocumentOutline getOutline() { return outline; } public void setOutline(PDDocumentOutline outline) { this.outline = outline; } public String getKeywords() { return keywords; } public void setKeywords(String keywords) { this.keywords = keywords; } public String getUserPassword() { return userPassword; } public void setUserPassword(String userPassword) { this.userPassword = userPassword; } public AccessPermission getAccess() { return access; } public void setAccess(AccessPermission access) { this.access = access; } public String getOwnerPassword() { return ownerPassword; } public void setOwnerPassword(String ownerPassword) { this.ownerPassword = ownerPassword; } public int getFromPage() { return fromPage; } public void setFromPage(int fromPage) { this.fromPage = fromPage; } public int getToPage() { return toPage; } public void setToPage(int toPage) { this.toPage = toPage; } public String getError() { return error; } public void setError(String error) { this.error = error; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data/JShellSnippet.java
released/MyBox/src/main/java/mara/mybox/data/JShellSnippet.java
package mara.mybox.data; import jdk.jshell.ErroneousSnippet; import jdk.jshell.ExpressionSnippet; import jdk.jshell.ImportSnippet; import jdk.jshell.JShell; import jdk.jshell.MethodSnippet; import jdk.jshell.Snippet; import jdk.jshell.VarSnippet; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2022-3-5 * @License Apache License Version 2.0 */ public class JShellSnippet { protected Snippet snippet; protected String id, name, type, subType, status, source, value, some1, some2; public JShellSnippet(JShell jShell, Snippet snippet) { if (jShell == null || snippet == null) { return; } this.snippet = snippet; id = snippet.id(); type = snippet.kind().name(); subType = snippet.subKind().name(); switch (jShell.status(snippet)) { case DROPPED: status = message("Dropped"); break; case NONEXISTENT: status = message("Nonexistent"); break; case OVERWRITTEN: status = message("Overwritten"); break; case RECOVERABLE_DEFINED: case RECOVERABLE_NOT_DEFINED: status = message("RecoverableUnresolved"); break; case REJECTED: status = message("Rejected"); break; case VALID: status = message("Valid"); break; } source = snippet.source(); if (snippet instanceof VarSnippet) { makeVar(jShell, (VarSnippet) snippet); } else if (snippet instanceof ExpressionSnippet) { makeExpression((ExpressionSnippet) snippet); } else if (snippet instanceof MethodSnippet) { makeMethod((MethodSnippet) snippet); } else if (snippet instanceof ImportSnippet) { makeImport((ImportSnippet) snippet); } else if (snippet instanceof ErroneousSnippet) { makeError((ErroneousSnippet) snippet); } } private void makeVar(JShell jShell, VarSnippet varSnippet) { if (jShell == null || varSnippet == null) { return; } name = varSnippet.name(); some1 = varSnippet.typeName(); value = jShell.varValue(varSnippet); } private void makeExpression(ExpressionSnippet expSnippet) { if (expSnippet == null) { return; } name = expSnippet.name(); some1 = expSnippet.typeName(); } private void makeMethod(MethodSnippet methodSnippet) { if (methodSnippet == null) { return; } name = methodSnippet.name(); some1 = methodSnippet.parameterTypes(); some2 = methodSnippet.signature(); } private void makeImport(ImportSnippet importSnippet) { if (importSnippet == null) { return; } name = importSnippet.name(); some1 = importSnippet.fullname(); some2 = importSnippet.isStatic() ? "Static" : ""; } private void makeError(ErroneousSnippet errorSnippet) { if (errorSnippet == null) { return; } some1 = errorSnippet.probableKind().name(); } /* get/set */ public Snippet getSnippet() { return snippet; } public void setSnippet(Snippet snippet) { this.snippet = snippet; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getSubType() { return subType; } public void setSubType(String subType) { this.subType = subType; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getSource() { return source; } public void setSource(String source) { this.source = source; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSome1() { return some1; } public void setSome1(String some1) { this.some1 = some1; } public String getSome2() { return some2; } public void setSome2(String some2) { this.some2 = some2; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data/ImageItem.java
released/MyBox/src/main/java/mara/mybox/data/ImageItem.java
package mara.mybox.data; import java.awt.image.BufferedImage; import java.io.File; import javafx.beans.property.SimpleBooleanProperty; import javafx.embed.swing.SwingFXUtils; import javafx.scene.Node; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import javax.imageio.ImageIO; import mara.mybox.fxml.FxFileTools; import mara.mybox.tools.FileNameTools; /** * @Author Mara * @CreateDate 2020-1-5 * @License Apache License Version 2.0 */ public class ImageItem { protected String name, address, comments; protected int index, width; protected SimpleBooleanProperty selected = new SimpleBooleanProperty(false); public ImageItem() { init(); } public ImageItem(String address) { init(); this.address = address; } private void init() { name = null; address = null; comments = null; selected = new SimpleBooleanProperty(false); } public boolean isInternal() { return address != null && (address.startsWith("img/") || address.startsWith("buttons/")); } public int getWidth() { if (width > 0) { return width; } if (name != null && name.startsWith("icon")) { return 100; } return address != null && address.startsWith("buttons/") ? 100 : 500; } public boolean isColor() { return address != null && address.startsWith("color:"); } public boolean isFile() { return address != null && new File(address).exists(); } public Image readImage() { Image image = null; try { if (address == null || isColor()) { return null; } if (isInternal()) { image = new Image(address); } else if (isFile()) { File file = new File(address); if (file.exists()) { BufferedImage bf = ImageIO.read(file); image = SwingFXUtils.toFXImage(bf, null); } } } catch (Exception e) { } if (image != null) { width = (int) image.getWidth(); } return image; } public Node makeNode(int size, boolean checkSize) { try { if (isColor()) { Rectangle rect = new Rectangle(); rect.setFill(Color.web(address.substring(6))); rect.setWidth(size); rect.setHeight(size); rect.setStyle("-fx-padding: 10 10 10 10;-fx-background-radius: 10;"); rect.setUserData(index); return rect; } else { Image image = readImage(); if (image == null) { return null; } int w = size; if (checkSize && w > image.getWidth()) { w = (int) image.getWidth(); } ImageView view = new ImageView(image); view.setPreserveRatio(false); view.setFitWidth(w); view.setFitHeight(w); view.setUserData(index); return view; } } catch (Exception e) { return null; } } public File getFile() { try { File file = null; if (isInternal()) { file = FxFileTools.getInternalFile("/" + address, "image", name != null ? name : FileNameTools.name(address, "/")); } else if (isFile()) { file = new File(address); } if (file != null && file.exists()) { return file; } else { return null; } } catch (Exception e) { return null; } } /* static */ /* get/set */ public String getAddress() { return address; } public ImageItem setAddress(String address) { this.address = address; return this; } public String getComments() { return comments; } public ImageItem setComments(String comments) { this.comments = comments; return this; } public boolean isSelected() { return selected.get(); } public SimpleBooleanProperty getSelected() { return selected; } public ImageItem setSelected(SimpleBooleanProperty selected) { this.selected = selected; return this; } public ImageItem setSelected(boolean selected) { this.selected.set(selected); return this; } public int getIndex() { return index; } public void setIndex(int index) { this.index = index; } public String getName() { return name; } public ImageItem setName(String name) { this.name = name; return this; } public ImageItem setWidth(int width) { this.width = width; return this; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data/DownloadItem.java
released/MyBox/src/main/java/mara/mybox/data/DownloadItem.java
/* * Apache License Version 2.0 */ package mara.mybox.data; import java.io.File; import java.util.Date; import mara.mybox.fxml.DownloadTask; import mara.mybox.tools.FileTools; /** * * @author mara */ public class DownloadItem { protected String address; protected File targetFile; protected long totalSize, currentSize, startTime, endTime, cost; protected String status, progress, speed; protected DownloadTask task; public static DownloadItem create() { return new DownloadItem(); } public String getAddress() { return address; } public DownloadItem setAddress(String address) { this.address = address; return this; } public File getTargetFile() { return targetFile; } public DownloadItem setTargetFile(File targetFile) { this.targetFile = targetFile; return this; } public long getTotalSize() { return totalSize; } public DownloadItem setTotalSize(long totalSize) { this.totalSize = totalSize; return this; } public long getCurrentSize() { return currentSize; } public DownloadItem setCurrentSize(long currentSize) { this.currentSize = currentSize; return this; } public String getStatus() { return status; } public DownloadItem setStatus(String status) { this.status = status; return this; } public long getStartTime() { return startTime; } public DownloadItem setStartTime(long startTime) { this.startTime = startTime; return this; } public String getProgress() { if (totalSize == 0) { return "0%"; } else { int v = (int) (currentSize * 100 / totalSize); v = Math.max(0, Math.min(100, v)); return v + "%"; } } public long getEndTime() { return endTime; } public void setEndTime(long endTime) { this.endTime = endTime; } public long getCost() { if (endTime > startTime) { return endTime - startTime; } else { long v = new Date().getTime() - startTime; return v > 0 ? v : 0; } } public void setCost(long cost) { this.cost = cost; } public String getSpeed() { if (currentSize <= 0 || getCost() <= 0) { return "0"; } else { return FileTools.showFileSize(currentSize / getCost()) + "/s"; } } public DownloadTask getTask() { return task; } public DownloadItem setTask(DownloadTask task) { this.task = task; return this; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data/ValueRange.java
released/MyBox/src/main/java/mara/mybox/data/ValueRange.java
package mara.mybox.data; /** * @Author Mara * @CreateDate 2022-11-22 * @License Apache License Version 2.0 */ public class ValueRange { protected Object start, end; protected boolean includeStart, includeEnd; public static enum SplitType { Size, Number, List } public ValueRange() { start = null; end = null; includeStart = false; includeEnd = false; } @Override public String toString() { return (includeStart ? "[" : "(") + start + "," + end + (includeEnd ? "]" : ")"); } /* get/set */ public Object getStart() { return start; } public ValueRange setStart(Object start) { this.start = start; return this; } public Object getEnd() { return end; } public ValueRange setEnd(Object end) { this.end = end; return this; } public boolean isIncludeStart() { return includeStart; } public ValueRange setIncludeStart(boolean includeStart) { this.includeStart = includeStart; return this; } public boolean isIncludeEnd() { return includeEnd; } public ValueRange setIncludeEnd(boolean includeEnd) { this.includeEnd = includeEnd; return this; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data/DoublePolylines.java
released/MyBox/src/main/java/mara/mybox/data/DoublePolylines.java
package mara.mybox.data; import java.awt.geom.Path2D; import java.util.ArrayList; import java.util.List; import javafx.geometry.Point2D; import javafx.scene.shape.Line; import static mara.mybox.tools.DoubleTools.imageScale; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2018-11-11 12:29:29 * @License Apache License Version 2.0 */ public class DoublePolylines implements DoubleShape { private List<List<DoublePoint>> lines; public DoublePolylines() { lines = new ArrayList<>(); } @Override public String name() { return message("Polylines"); } @Override public Path2D.Double getShape() { if (lines == null) { return null; } Path2D.Double path = new Path2D.Double(); for (List<DoublePoint> line : lines) { DoublePoint p = line.get(0); path.moveTo(p.getX(), p.getY()); for (int i = 1; i < line.size(); i++) { p = line.get(i); path.lineTo(p.getX(), p.getY()); } } return path; } public boolean addLine(List<DoublePoint> line) { if (line == null) { return false; } lines.add(line); return true; } public boolean setLine(int index, List<DoublePoint> line) { if (line == null || index < 0 || index >= lines.size()) { return false; } lines.set(index, line); return true; } public boolean removeLine(int index) { if (lines == null || index < 0 || index >= lines.size()) { return false; } lines.remove(index); return true; } @Override public boolean isValid() { return lines != null; } @Override public boolean isEmpty() { return !isValid() || lines.isEmpty(); } @Override public DoublePolylines copy() { DoublePolylines np = new DoublePolylines(); for (List<DoublePoint> line : lines) { List<DoublePoint> newline = new ArrayList<>(); newline.addAll(line); np.addLine(newline); } return np; } public List<Line> getLineList() { List<Line> dlines = new ArrayList<>(); int lastx, lasty = -1, thisx, thisy; for (List<DoublePoint> lineData : lines) { if (lineData.size() == 1) { DoublePoint linePoint = lineData.get(0); thisx = (int) Math.round(linePoint.getX()); thisy = (int) Math.round(linePoint.getY()); Line line = new Line(thisx, thisy, thisx, thisy); dlines.add(line); } else { lastx = Integer.MAX_VALUE; for (DoublePoint linePoint : lineData) { thisx = (int) Math.round(linePoint.getX()); thisy = (int) Math.round(linePoint.getY()); if (lastx != Integer.MAX_VALUE) { Line line = new Line(lastx, lasty, thisx, thisy); dlines.add(line); } lastx = thisx; lasty = thisy; } } } return dlines; } public boolean contains(double x, double y) { if (!isValid()) { return false; } Point2D point = new Point2D(x, y); for (Line line : getLineList()) { if (line.contains(point)) { return true; } } return false; } public void clear() { lines.clear(); } @Override public boolean translateRel(double offsetX, double offsetY) { List<List<DoublePoint>> npoints = new ArrayList<>(); for (List<DoublePoint> line : lines) { List<DoublePoint> newline = new ArrayList<>(); for (DoublePoint p : line) { newline.add(new DoublePoint(p.getX() + offsetX, p.getY() + offsetY)); } npoints.add(newline); } lines.clear(); lines.addAll(npoints); return true; } public void translateLineRel(int index, double offsetX, double offsetY) { if (index < 0 || index >= lines.size()) { return; } List<DoublePoint> newline = new ArrayList<>(); List<DoublePoint> line = lines.get(index); for (int i = 0; i < line.size(); i++) { DoublePoint p = line.get(i); newline.add(p.translate(offsetX, offsetY)); } lines.set(index, newline); } @Override public boolean scale(double scaleX, double scaleY) { List<List<DoublePoint>> npoints = new ArrayList<>(); for (List<DoublePoint> line : lines) { List<DoublePoint> newline = new ArrayList<>(); for (DoublePoint p : line) { newline.add(p.scale(scaleX, scaleY)); } npoints.add(newline); } lines.clear(); lines.addAll(npoints); return true; } public void scale(int index, double scaleX, double scaleY) { if (index < 0 || index >= lines.size()) { return; } List<DoublePoint> newline = new ArrayList<>(); List<DoublePoint> line = lines.get(index); for (int i = 0; i < line.size(); i++) { DoublePoint p = line.get(i); newline.add(p.scale(scaleX, scaleY)); } lines.set(index, newline); } @Override public String pathAbs() { String path = ""; for (List<DoublePoint> line : lines) { DoublePoint p = line.get(0); path += "M " + imageScale(p.getX()) + "," + imageScale(p.getY()) + "\n"; for (int i = 1; i < line.size(); i++) { p = line.get(i); path += "L " + imageScale(p.getX()) + "," + imageScale(p.getY()) + "\n"; } } return path; } @Override public String pathRel() { String path = ""; double lastx = 0, lasty = 0; for (List<DoublePoint> line : lines) { DoublePoint p = line.get(0); path += "M " + imageScale(p.getX() - lastx) + "," + imageScale(p.getY() - lasty) + "\n"; lastx = p.getX(); lasty = p.getY(); for (int i = 1; i < line.size(); i++) { p = line.get(i); path += "l " + imageScale(p.getX() - lastx) + "," + imageScale(p.getY() - lasty) + "\n"; lastx = p.getX(); lasty = p.getY(); } } return path; } @Override public String elementAbs() { String e = ""; int scale = UserConfig.imageScale(); for (List<DoublePoint> line : lines) { e += "<polygon points=\"" + DoublePoint.toText(line, scale, " ") + "\">\n"; } return e; } @Override public String elementRel() { return elementAbs(); } public int getLinesSize() { return lines.size(); } public List<List<DoublePoint>> getLines() { return lines; } public List<Path2D.Double> getPaths() { if (lines == null) { return null; } List<Path2D.Double> paths = new ArrayList<>(); for (List<DoublePoint> line : lines) { Path2D.Double path = new Path2D.Double(); DoublePoint p = line.get(0); path.moveTo(p.getX(), p.getY()); for (int i = 1; i < line.size(); i++) { p = line.get(i); path.lineTo(p.getX(), p.getY()); } paths.add(path); } return paths; } public void setLines(List<List<DoublePoint>> linePoints) { this.lines = linePoints; } public boolean removeLastLine() { if (lines.isEmpty()) { return false; } lines.remove(lines.size() - 1); return true; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data/GeographyCode.java
released/MyBox/src/main/java/mara/mybox/data/GeographyCode.java
package mara.mybox.data; import mara.mybox.dev.MyBoxLog; import mara.mybox.value.AppValues; import mara.mybox.value.Languages; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2020-1-20 * @License Apache License Version 2.0 */ public class GeographyCode implements Cloneable { protected double area; protected long population; protected AddressLevel level; protected String name, fullName, chineseName, englishName, levelName, code1, code2, code3, code4, code5, alias1, alias2, alias3, alias4, alias5, continent, country, province, city, county, town, village, building, poi, title, info, description; protected double longitude, latitude, altitude, precision; protected CoordinateSystem coordinateSystem; protected int markSize; public static CoordinateSystem defaultCoordinateSystem = CoordinateSystem.CGCS2000; public static AddressLevel defaultAddressLevel = AddressLevel.Other; public static enum AddressLevel { Global, Continent, Country, Province, City, County, Town, Village, Building, PointOfInterest, Other } public static enum CoordinateSystem { CGCS2000, GCJ_02, WGS_84, BD_09, Mapbar, Other } public GeographyCode() { area = -1; population = -1; level = defaultAddressLevel; coordinateSystem = defaultCoordinateSystem; longitude = latitude = -200; altitude = precision = AppValues.InvalidDouble; markSize = -1; } @Override public Object clone() throws CloneNotSupportedException { try { GeographyCode newCode = (GeographyCode) super.clone(); newCode.setLevel(level); newCode.setCoordinateSystem(coordinateSystem); return newCode; } catch (Exception e) { MyBoxLog.debug(e); return null; } } /* custmized get/set */ public String getName() { if (Languages.isChinese()) { name = chineseName != null ? chineseName : englishName; } else { name = englishName != null ? englishName : chineseName; } if (name == null) { return message(level.name()); } return name; } public String getFullName() { getName(); if (level == null || level.ordinal() <= 3) { fullName = name; } else { if (Languages.isChinese()) { if (country != null) { fullName = country; } else { fullName = ""; } if (province != null && !province.isBlank()) { fullName = fullName.isBlank() ? province : fullName + "-" + province; } if (city != null && !city.isBlank()) { fullName = fullName.isBlank() ? city : fullName + "-" + city; } if (county != null && !county.isBlank()) { fullName = fullName.isBlank() ? county : fullName + "-" + county; } if (town != null && !town.isBlank()) { fullName = fullName.isBlank() ? town : fullName + "-" + town; } if (village != null && !village.isBlank()) { fullName = fullName.isBlank() ? village : fullName + "-" + village; } if (building != null && !building.isBlank()) { fullName = fullName.isBlank() ? building : fullName + "-" + building; } if (name != null && !name.isBlank()) { fullName = fullName.isBlank() ? name : fullName + "-" + name; } } else { if (name != null) { fullName = name; } else { fullName = ""; } if (building != null && !building.isBlank()) { fullName = fullName.isBlank() ? building : fullName + "," + building; } if (village != null && !village.isBlank()) { fullName = fullName.isBlank() ? village : fullName + "," + village; } if (town != null && !town.isBlank()) { fullName = fullName.isBlank() ? town : fullName + "," + town; } if (county != null && !county.isBlank()) { fullName = fullName.isBlank() ? county : fullName + "," + county; } if (city != null && !city.isBlank()) { fullName = fullName.isBlank() ? city : fullName + "," + city; } if (province != null && !province.isBlank()) { fullName = fullName.isBlank() ? province : fullName + "," + province; } if (country != null && !country.isBlank()) { fullName = fullName.isBlank() ? country : fullName + "," + country; } } } return fullName; } public AddressLevel getLevel() { if (level == null) { level = defaultAddressLevel; } return level; } public String getLevelName() { levelName = message(getLevel().name()); return levelName; } public CoordinateSystem getCoordinateSystem() { if (coordinateSystem == null) { coordinateSystem = defaultCoordinateSystem; } return coordinateSystem; } public String getTitle() { return title != null ? title : getName(); } /* get/set */ public String getChineseName() { return chineseName; } public void setChineseName(String chineseName) { this.chineseName = chineseName; } public String getEnglishName() { return englishName; } public void setEnglishName(String englishName) { this.englishName = englishName; } public String getCode1() { return code1; } public void setCode1(String code1) { this.code1 = code1; } public String getCode2() { return code2; } public void setCode2(String code2) { this.code2 = code2; } public String getCode3() { return code3; } public void setCode3(String code3) { this.code3 = code3; } public String getAlias1() { return alias1; } public void setAlias1(String alias1) { this.alias1 = alias1; } public String getAlias2() { return alias2; } public void setAlias2(String alias2) { this.alias2 = alias2; } public String getAlias3() { return alias3; } public void setAlias3(String alias3) { this.alias3 = alias3; } public double getLongitude() { return longitude; } public GeographyCode setLongitude(double longitude) { this.longitude = longitude; return this; } public double getLatitude() { return latitude; } public GeographyCode setLatitude(double latitude) { this.latitude = latitude; return this; } public String getContinent() { return continent; } public String getCountry() { return country; } public String getProvince() { return province; } public String getCity() { return city; } public String getCounty() { return county; } public String getTown() { return town; } public String getVillage() { return village; } public String getBuilding() { return building; } public String getPoi() { return poi; } public void setCountry(String country) { this.country = country; } public void setProvince(String province) { this.province = province; } public void setCity(String city) { this.city = city; } public void setCounty(String county) { this.county = county; } public void setVillage(String village) { this.village = village; } public void setTown(String town) { this.town = town; } public void setBuilding(String building) { this.building = building; } public String getCode4() { return code4; } public void setCode4(String code4) { this.code4 = code4; } public String getCode5() { return code5; } public void setCode5(String code5) { this.code5 = code5; } public String getAlias4() { return alias4; } public void setAlias4(String alias4) { this.alias4 = alias4; } public String getAlias5() { return alias5; } public void setAlias5(String alias5) { this.alias5 = alias5; } public void setPoi(String poi) { this.poi = poi; } public void setName(String name) { this.name = name; } public void setFullName(String fullName) { this.fullName = fullName; } public void setContinent(String continent) { this.continent = continent; } public void setLevel(AddressLevel level) { this.level = level; } public double getArea() { return area; } public void setArea(double area) { this.area = area; } public long getPopulation() { return population; } public void setPopulation(long population) { this.population = population; } public void setLevelName(String levelName) { this.levelName = levelName; } public double getAltitude() { return altitude; } public GeographyCode setAltitude(double altitude) { this.altitude = altitude; return this; } public double getPrecision() { return precision; } public void setPrecision(double precision) { this.precision = precision; } public GeographyCode setCoordinateSystem(CoordinateSystem coordinateSystem) { this.coordinateSystem = coordinateSystem; return this; } public String getInfo() { return info; } public GeographyCode setInfo(String info) { this.info = info; return this; } public GeographyCode setTitle(String label) { this.title = label; return this; } public int getMarkSize() { return markSize; } public GeographyCode setMarkSize(int markSize) { this.markSize = markSize; return this; } public String getDescription() { return description; } public GeographyCode setDescription(String description) { this.description = description; return this; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data/TesseractOptions.java
released/MyBox/src/main/java/mara/mybox/data/TesseractOptions.java
package mara.mybox.data; import java.awt.Rectangle; import java.awt.image.BufferedImage; import java.io.BufferedReader; import java.io.File; import java.nio.charset.Charset; import java.sql.Connection; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import javafx.embed.swing.SwingFXUtils; import javafx.scene.image.Image; import mara.mybox.db.DerbyBase; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.image.tools.AlphaTools; import mara.mybox.tools.FileCopyTools; import mara.mybox.tools.FileDeleteTools; import mara.mybox.tools.FileTmpTools; import mara.mybox.tools.SystemTools; import mara.mybox.tools.TextFileTools; import static mara.mybox.value.AppVariables.MyboxDataPath; import mara.mybox.value.Languages; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; import net.sourceforge.tess4j.ITessAPI; import net.sourceforge.tess4j.ITesseract; import net.sourceforge.tess4j.Tesseract; import net.sourceforge.tess4j.Word; /** * @Author Mara * @CreateDate 2025-6-30 * @License Apache License Version 2.0 */ public class TesseractOptions { // https://github.com/nguyenq/tess4j/blob/master/src/test/java/net/sourceforge/tess4j/Tesseract1Test.java#L177 public static final double MINIMUM_DESKEW_THRESHOLD = 0.05d; protected File tesseract, dataPath; protected String os, selectedLanguages, regionLevel, wordLevel, more, texts, html; protected List<Rectangle> rectangles; protected List<Word> words; protected int psm, tesseractVersion; protected boolean embed, setFormats, setLevels, isVersion3, outHtml, outPdf; protected File configFile; protected Tesseract tessInstance; public TesseractOptions() { initValues(); } final public void initValues() { os = SystemTools.os(); readValues(); configFile = null; tessInstance = null; clearResults(); } public void readValues() { try (Connection conn = DerbyBase.getConnection()) { tesseract = new File(UserConfig.getString(conn, "TesseractPath", "win".equals(os) ? "D:\\Programs\\Tesseract-OCR\\tesseract.exe" : "/bin/tesseract")); dataPath = new File(UserConfig.getString(conn, "TesseractData", "win".equals(os) ? "D:\\Programs\\Tesseract-OCR\\tessdata" : "/usr/local/share/tessdata/")); embed = UserConfig.getBoolean(conn, "TesseracEmbed", true); selectedLanguages = UserConfig.getString(conn, "ImageOCRLanguages", null); psm = UserConfig.getInt(conn, "TesseractPSM", 6); regionLevel = UserConfig.getString(conn, "TesseractRegionLevel", message("Symbol")); wordLevel = UserConfig.getString(conn, "TesseractWordLevel", message("Symbol")); outHtml = UserConfig.getBoolean(conn, "TesseractOutHtml", false); outPdf = UserConfig.getBoolean(conn, "TesseractOutPdf", false); more = UserConfig.getString(conn, "TesseractMore", null); } catch (Exception e) { MyBoxLog.error(e); } } public void writeValues() { try (Connection conn = DerbyBase.getConnection()) { UserConfig.setString(conn, "TesseractPath", tesseract.getAbsolutePath()); UserConfig.setString(conn, "TesseractData", dataPath.getAbsolutePath()); UserConfig.setBoolean(conn, "ImageOCREmbed", embed); UserConfig.setString(conn, "ImageOCRLanguages", selectedLanguages); UserConfig.setInt(conn, "TesseractPSM", psm); UserConfig.setString(conn, "TesseractRegionLevel", regionLevel); UserConfig.setString(conn, "TesseractWordLevel", wordLevel); UserConfig.setBoolean(conn, "TesseractOutHtml", outHtml); UserConfig.setBoolean(conn, "TesseractOutPdf", outPdf); UserConfig.setString(conn, "TesseractMore", more); } catch (Exception e) { MyBoxLog.error(e); } } public void clearResults() { texts = null; html = null; rectangles = null; words = null; } public boolean isWin() { return "win".equals(os); } public int level(String name) { if (name == null || name.isBlank()) { return -1; } else if (Languages.matchIgnoreCase("Block", name)) { return ITessAPI.TessPageIteratorLevel.RIL_BLOCK; } else if (Languages.matchIgnoreCase("Paragraph", name)) { return ITessAPI.TessPageIteratorLevel.RIL_PARA; } else if (Languages.matchIgnoreCase("Textline", name)) { return ITessAPI.TessPageIteratorLevel.RIL_TEXTLINE; } else if (Languages.matchIgnoreCase("Word", name)) { return ITessAPI.TessPageIteratorLevel.RIL_WORD; } else if (Languages.matchIgnoreCase("Symbol", name)) { return ITessAPI.TessPageIteratorLevel.RIL_SYMBOL; } else { return -1; } } public int wordLevel() { return level(wordLevel); } public int regionLevel() { return level(regionLevel); } public Map<String, String> moreOptions() { if (more == null || more.isBlank()) { return null; } Map<String, String> p = new HashMap<>(); String[] lines = more.split("\n"); for (String line : lines) { String[] fields = line.split("\t"); if (fields.length < 2) { continue; } p.put(fields[0].trim(), fields[1].trim()); } return p; } // Make sure supported language files are under defined data path public boolean initDataFiles() { try { if (dataPath == null || !dataPath.exists() || !dataPath.isDirectory()) { dataPath = new File(MyboxDataPath + File.separator + "tessdata"); } dataPath.mkdirs(); File chi_sim = new File(dataPath.getAbsolutePath() + File.separator + "chi_sim.traineddata"); if (!chi_sim.exists()) { File tmp = mara.mybox.fxml.FxFileTools.getInternalFile("/data/tessdata/chi_sim.traineddata"); FileCopyTools.copyFile(tmp, chi_sim); } File chi_sim_vert = new File(dataPath.getAbsolutePath() + File.separator + "chi_sim_vert.traineddata"); if (!chi_sim_vert.exists()) { File tmp = mara.mybox.fxml.FxFileTools.getInternalFile("/data/tessdata/chi_sim_vert.traineddata"); FileCopyTools.copyFile(tmp, chi_sim_vert); } File chi_tra = new File(dataPath.getAbsolutePath() + File.separator + "chi_tra.traineddata"); if (!chi_tra.exists()) { File tmp = mara.mybox.fxml.FxFileTools.getInternalFile("/data/tessdata/chi_tra.traineddata"); FileCopyTools.copyFile(tmp, chi_tra); } File chi_tra_vert = new File(dataPath.getAbsolutePath() + File.separator + "chi_tra_vert.traineddata"); if (!chi_tra_vert.exists()) { File tmp = mara.mybox.fxml.FxFileTools.getInternalFile("/data/tessdata/chi_tra_vert.traineddata"); FileCopyTools.copyFile(tmp, chi_tra_vert); } File equ = new File(dataPath.getAbsolutePath() + File.separator + "equ.traineddata"); if (!equ.exists()) { File tmp = mara.mybox.fxml.FxFileTools.getInternalFile("/data/tessdata/equ.traineddata"); FileCopyTools.copyFile(tmp, equ); } File eng = new File(dataPath.getAbsolutePath() + File.separator + "eng.traineddata"); if (!eng.exists()) { File tmp = mara.mybox.fxml.FxFileTools.getInternalFile("/data/tessdata/eng.traineddata"); FileCopyTools.copyFile(tmp, eng); } File osd = new File(dataPath.getAbsolutePath() + File.separator + "osd.traineddata"); if (!osd.exists()) { File tmp = mara.mybox.fxml.FxFileTools.getInternalFile("/tessdata/osd.traineddata"); FileCopyTools.copyFile(tmp, osd); } return true; } catch (Exception e) { MyBoxLog.debug(e); return false; } } public List<String> namesList() { return namesList(tesseractVersion > 3); } public List<String> namesList(boolean copyFiles) { List<String> data = new ArrayList<>(); try { if (copyFiles) { initDataFiles(); } data.addAll(names()); List<String> codes = codes(); File[] files = dataPath.listFiles(); if (files != null) { for (File f : files) { String name = f.getName(); if (!f.isFile() || !name.endsWith(".traineddata")) { continue; } String code = name.substring(0, name.length() - ".traineddata".length()); if (codes.contains(code)) { continue; } data.add(code); } } } catch (Exception e) { MyBoxLog.debug(e); } return data; } public Tesseract makeInstance() { try { tessInstance = new Tesseract(); // https://stackoverflow.com/questions/58286373/tess4j-pdf-to-tiff-to-tesseract-warning-invalid-resolution-0-dpi-using-70/58296472#58296472 tessInstance.setVariable("user_defined_dpi", "96"); tessInstance.setVariable("debug_file", "/dev/null"); tessInstance.setPageSegMode(psm); Map<String, String> moreOptions = moreOptions(); if (moreOptions != null && !moreOptions.isEmpty()) { for (String key : moreOptions.keySet()) { tessInstance.setVariable(key, moreOptions.get(key)); } } tessInstance.setDatapath(dataPath.getAbsolutePath()); if (selectedLanguages != null) { tessInstance.setLanguage(selectedLanguages); } return tessInstance; } catch (Exception e) { MyBoxLog.debug(e); return null; } } public int tesseractVersion() { try { if (tesseract == null || !tesseract.exists()) { return -1; } List<String> parameters = new ArrayList<>(); parameters.addAll(Arrays.asList(tesseract.getAbsolutePath(), "--version")); ProcessBuilder pb = new ProcessBuilder(parameters).redirectErrorStream(true); Process process = pb.start(); try (BufferedReader inReader = process.inputReader(Charset.defaultCharset())) { String line; while ((line = inReader.readLine()) != null) { if (line.contains("tesseract v4.") || line.contains("tesseract 4.")) { return 4; } if (line.contains("tesseract v5.") || line.contains("tesseract 5.")) { return 5; } if (line.contains("tesseract v3.") || line.contains("tesseract 3.")) { return 3; } if (line.contains("tesseract v2.") || line.contains("tesseract 2.")) { return 2; } } } catch (Exception e) { MyBoxLog.debug(e); } process.waitFor(); } catch (Exception e) { MyBoxLog.debug(e); } return -1; } public void makeConfigFile() { try { configFile = FileTmpTools.getTempFile(); String s = "tessedit_create_txt 1\n"; if (setFormats) { if (outHtml) { s += "tessedit_create_hocr 1\n"; } if (outPdf) { s += "tessedit_create_pdf 1\n"; } } Map<String, String> moreOptions = moreOptions(); if (moreOptions != null) { for (String key : moreOptions.keySet()) { s += key + "\t" + moreOptions.get(key) + "\n"; } } TextFileTools.writeFile(configFile, s, Charset.forName("utf-8")); } catch (Exception e) { MyBoxLog.error(e); configFile = null; } } public boolean imageOCR(FxTask currentTask, Image image, boolean allData) { BufferedImage bufferedImage = SwingFXUtils.fromFXImage(image, null); bufferedImage = AlphaTools.removeAlpha(currentTask, bufferedImage); return bufferedImageOCR(currentTask, bufferedImage, allData); } public boolean bufferedImageOCR(FxTask currentTask, BufferedImage bufferedImage, boolean allData) { try { clearResults(); if (bufferedImage == null || (currentTask != null && !currentTask.isWorking())) { return false; } if (tessInstance == null) { tessInstance = makeInstance(); } List<ITesseract.RenderedFormat> formats = new ArrayList<>(); formats.add(ITesseract.RenderedFormat.TEXT); if (allData) { formats.add(ITesseract.RenderedFormat.HOCR); } File tmpFile = File.createTempFile("MyboxOCR", ""); String tmp = tmpFile.getAbsolutePath(); FileDeleteTools.delete(tmpFile); tessInstance.createDocumentsWithResults​(bufferedImage, tmp, tmp, formats, ITessAPI.TessPageIteratorLevel.RIL_SYMBOL); File txtFile = new File(tmp + ".txt"); texts = TextFileTools.readTexts(currentTask, txtFile); FileDeleteTools.delete(txtFile); if (texts == null || (currentTask != null && !currentTask.isWorking())) { return false; } if (allData) { File htmlFile = new File(tmp + ".hocr"); html = TextFileTools.readTexts(currentTask, htmlFile); FileDeleteTools.delete(htmlFile); if (html == null || (currentTask != null && !currentTask.isWorking())) { return false; } int wl = wordLevel(); if (wl >= 0) { words = tessInstance.getWords(bufferedImage, wl); } int rl = regionLevel(); if (rl >= 0) { rectangles = tessInstance.getSegmentedRegions(bufferedImage, rl); } } return texts != null; } catch (Exception e) { MyBoxLog.debug(e); return false; } } public Process process(File file, String prefix) { try { if (file == null || configFile == null || dataPath == null) { return null; } List<String> parameters = new ArrayList<>(); parameters.addAll(Arrays.asList( tesseract.getAbsolutePath(), file.getAbsolutePath(), prefix, "--tessdata-dir", dataPath.getAbsolutePath(), tesseractVersion > 3 ? "--psm" : "-psm", psm + "" )); if (selectedLanguages != null) { parameters.addAll(Arrays.asList("-l", selectedLanguages)); } parameters.add(configFile.getAbsolutePath()); ProcessBuilder pb = new ProcessBuilder(parameters).redirectErrorStream(true); return pb.start(); } catch (Exception e) { MyBoxLog.error(e); return null; } } /* static */ // Generate each time because user may change the interface language. public static Map<String, String> codeName() { // if (CodeName != null) { // return CodeName; // } Map<String, String> named = new HashMap<>(); named.put("chi_sim", Languages.message("SimplifiedChinese")); named.put("chi_sim_vert", Languages.message("SimplifiedChineseVert")); named.put("chi_tra", Languages.message("TraditionalChinese")); named.put("chi_tra_vert", Languages.message("TraditionalChineseVert")); named.put("eng", Languages.message("English")); named.put("equ", Languages.message("MathEquation")); named.put("osd", Languages.message("OrientationScript")); return named; } public static Map<String, String> nameCode() { // if (NameCode != null) { // return NameCode; // } Map<String, String> codes = codeName(); Map<String, String> names = new HashMap<>(); for (String code : codes.keySet()) { names.put(codes.get(code), code); } return names; } public static List<String> codes() { // if (Codes != null) { // return Codes; // } List<String> Codes = new ArrayList<>(); Codes.add("chi_sim"); Codes.add("chi_sim_vert"); Codes.add("chi_tra"); Codes.add("chi_tra_vert"); Codes.add("eng"); Codes.add("equ"); Codes.add("osd"); return Codes; } public static List<String> names() { // if (Names != null) { // return Names; // } List<String> Names = new ArrayList<>(); Map<String, String> codes = codeName(); for (String code : codes()) { Names.add(codes.get(code)); } return Names; } public static String name(String code) { Map<String, String> codes = codeName(); return codes.get(code); } public static String code(String name) { Map<String, String> names = nameCode(); return names.get(name); } /* get/set */ public boolean isEmbed() { return embed; } public void setEmbed(boolean embed) { this.embed = embed; } public File getTesseract() { return tesseract; } public void setTesseract(File tesseract) { this.tesseract = tesseract; } public File getDataPath() { return dataPath; } public void setDataPath(File dataPath) { this.dataPath = dataPath; } public String getSelectedLanguages() { return selectedLanguages; } public void setSelectedLanguages(String selectedLanguages) { this.selectedLanguages = selectedLanguages; } public String getTexts() { return texts; } public TesseractOptions setTexts(String texts) { this.texts = texts; return this; } public String getHtml() { return html; } public TesseractOptions setHtml(String html) { this.html = html; return this; } public List<Rectangle> getRectangles() { return rectangles; } public TesseractOptions setRectangles(List<Rectangle> rectangles) { this.rectangles = rectangles; return this; } public List<Word> getWords() { return words; } public TesseractOptions setWords(List<Word> words) { this.words = words; return this; } public int getPsm() { return psm; } public TesseractOptions setPsm(int psm) { this.psm = psm; return this; } public String getRegionLevel() { return regionLevel; } public TesseractOptions setRegionLevel(String regionLevel) { this.regionLevel = regionLevel; return this; } public String getWordLevel() { return wordLevel; } public TesseractOptions setWordLevel(String wordLevel) { this.wordLevel = wordLevel; return this; } public int getTesseractVersion() { return tesseractVersion; } public TesseractOptions setTesseractVersion(int tesseractVersion) { this.tesseractVersion = tesseractVersion; return this; } public boolean isSetFormats() { return setFormats; } public TesseractOptions setSetFormats(boolean setFormats) { this.setFormats = setFormats; return this; } public boolean isSetLevels() { return setLevels; } public TesseractOptions setSetLevels(boolean setLevels) { this.setLevels = setLevels; return this; } public boolean isIsVersion3() { return isVersion3; } public TesseractOptions setIsVersion3(boolean isVersion3) { this.isVersion3 = isVersion3; return this; } public File getConfigFile() { return configFile; } public TesseractOptions setConfigFile(File configFile) { this.configFile = configFile; return this; } public String getOs() { return os; } public TesseractOptions setOs(String os) { this.os = os; return this; } public boolean isOutHtml() { return outHtml; } public TesseractOptions setOutHtml(boolean outHtml) { this.outHtml = outHtml; return this; } public boolean isOutPdf() { return outPdf; } public TesseractOptions setOutPdf(boolean outPdf) { this.outPdf = outPdf; return this; } public String getMore() { return more; } public TesseractOptions setMore(String more) { this.more = more; return this; } public Tesseract getTessInstance() { return tessInstance; } public void setTessInstance(Tesseract tessInstance) { this.tessInstance = tessInstance; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data/SetValue.java
released/MyBox/src/main/java/mara/mybox/data/SetValue.java
package mara.mybox.data; import java.util.List; import java.util.Random; import mara.mybox.data2d.Data2D; import static mara.mybox.db.data.ColumnDefinition.DefaultInvalidAs; import mara.mybox.db.data.ColumnDefinition.InvalidAs; import static mara.mybox.db.data.ColumnDefinition.InvalidAs.Empty; import static mara.mybox.db.data.ColumnDefinition.InvalidAs.Null; import static mara.mybox.db.data.ColumnDefinition.InvalidAs.Skip; import static mara.mybox.db.data.ColumnDefinition.InvalidAs.Use; import static mara.mybox.db.data.ColumnDefinition.InvalidAs.Zero; import mara.mybox.db.data.Data2DColumn; import mara.mybox.tools.DoubleTools; import mara.mybox.tools.StringTools; /** * @Author Mara * @CreateDate 2022-8-13 * @License Apache License Version 2.0 */ public class SetValue { public ValueType type; public String parameter, error; public int start, digit, scale; public boolean fillZero, aotoDigit, valueInvalid; public InvalidAs invalidAs; final public static ValueType DefaultValueType = ValueType.Zero; public static enum ValueType { Value, Zero, One, Empty, Null, Random, RandomNonNegative, Scale, Prefix, Suffix, NumberSuffix, NumberPrefix, NumberReplace, NumberSuffixString, NumberPrefixString, Expression, GaussianDistribution, Identify, UpperTriangle, LowerTriangle } public SetValue() { init(); } public final void init() { type = DefaultValueType; parameter = null; start = 0; digit = 0; scale = 5; fillZero = true; aotoDigit = true; invalidAs = DefaultInvalidAs; } public int countFinalDigit(long dataSize) { int finalDigit = digit; if (isFillZero()) { if (isAotoDigit()) { finalDigit = (dataSize + "").length(); } } else { finalDigit = 0; } return finalDigit; } public String scale(String value) { double d = DoubleTools.toDouble(value, invalidAs); if (DoubleTools.invalidDouble(d)) { if (null == invalidAs) { return value; } else { switch (invalidAs) { case Zero: return "0"; case Empty: return ""; case Null: return null; case Skip: return null; case Use: return value; default: return value; } } } else { return DoubleTools.scaleString(d, scale); } } public String dummyValue(Data2D data2D, Data2DColumn column) { return makeValue(data2D, column, column.dummyValue(), data2D.dummyRow(), 1, start, countFinalDigit(data2D.getRowsNumber()), new Random()); } public String makeValue(Data2D data2D, Data2DColumn column, String currentValue, List<String> dataRow, long rowIndex, int dataIndex, int ddigit, Random random) { try { error = null; valueInvalid = false; switch (type) { case Zero: return "0"; case One: return "1"; case Empty: return ""; case Null: return null; case Random: return data2D.random(random, column, false); case RandomNonNegative: return data2D.random(random, column, true); case Scale: return scale(currentValue); case Prefix: return currentValue == null ? parameter : (parameter + currentValue); case Suffix: return currentValue == null ? parameter : (currentValue + parameter); case NumberSuffix: String suffix = StringTools.fillLeftZero(dataIndex, ddigit); return currentValue == null ? suffix : (currentValue + suffix); case NumberPrefix: String prefix = StringTools.fillLeftZero(dataIndex, ddigit); return currentValue == null ? prefix : (prefix + currentValue); case NumberReplace: return StringTools.fillLeftZero(dataIndex, ddigit); case NumberSuffixString: String ssuffix = StringTools.fillLeftZero(dataIndex, ddigit); return parameter == null ? ssuffix : (parameter + ssuffix); case NumberPrefixString: String sprefix = StringTools.fillLeftZero(dataIndex, ddigit); return parameter == null ? sprefix : (sprefix + parameter); case Expression: if (data2D.calculateDataRowExpression(parameter, dataRow, rowIndex)) { return data2D.expressionResult(); } else { valueInvalid = true; error = data2D.expressionError(); return currentValue; } case Value: return parameter; } valueInvalid = true; error = "InvalidData"; return currentValue; } catch (Exception e) { error = e.toString(); return currentValue; } } public String majorParameter() { try { switch (type) { case Scale: return scale + ""; case Suffix: case Prefix: case NumberSuffixString: case NumberPrefixString: case Expression: case Value: return parameter; case NumberSuffix: case NumberPrefix: return start + ""; } } catch (Exception e) { } return null; } /* set */ public SetValue setType(ValueType type) { this.type = type; return this; } public SetValue setParameter(String value) { this.parameter = value; return this; } public SetValue setStart(int start) { this.start = start; return this; } public SetValue setDigit(int digit) { this.digit = digit; return this; } public SetValue setFillZero(boolean fillZero) { this.fillZero = fillZero; return this; } public SetValue setAotoDigit(boolean aotoDigit) { this.aotoDigit = aotoDigit; return this; } public SetValue setScale(int scale) { this.scale = scale; return this; } public SetValue setInvalidAs(InvalidAs invalidAs) { this.invalidAs = invalidAs; return this; } public SetValue setError(String error) { this.error = error; return this; } /* get */ public ValueType getType() { return type; } public String getParameter() { return parameter; } public int getStart() { return start; } public int getDigit() { return digit; } public boolean isFillZero() { return fillZero; } public boolean isAotoDigit() { return aotoDigit; } public int getScale() { return scale; } public InvalidAs getInvalidAs() { return invalidAs; } public String getError() { return error; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data/DoubleCubic.java
released/MyBox/src/main/java/mara/mybox/data/DoubleCubic.java
package mara.mybox.data; import java.awt.geom.CubicCurve2D; import static mara.mybox.tools.DoubleTools.imageScale; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2023-7-31 * @License Apache License Version 2.0 */ public class DoubleCubic implements DoubleShape { private double startX, startY, controlX1, controlY1, controlX2, controlY2, endX, endY; public DoubleCubic() { } public DoubleCubic(double startX, double startY, double control1X, double control1Y, double control2X, double control2Y, double endX, double endY) { this.startX = startX; this.startY = startY; this.controlX1 = control1X; this.controlY1 = control1Y; this.controlX2 = control2X; this.controlY2 = control2Y; this.endX = endX; this.endY = endY; } @Override public String name() { return message("CubicCurve"); } @Override public CubicCurve2D.Double getShape() { return new CubicCurve2D.Double(startX, startY, controlX1, controlY1, controlX2, controlY2, endX, endY); } @Override public DoubleCubic copy() { return new DoubleCubic(startX, startY, controlX1, controlY1, controlX2, controlY2, endX, endY); } @Override public boolean isValid() { return true; } @Override public boolean isEmpty() { return !isValid(); } @Override public boolean translateRel(double offsetX, double offsetY) { startX += offsetX; startY += offsetY; controlX1 += offsetX; controlY1 += offsetY; controlX2 += offsetX; controlY2 += offsetY; endX += offsetX; endY += offsetY; return true; } @Override public boolean scale(double scaleX, double scaleY) { startX *= scaleX; startY *= scaleY; controlX1 *= scaleX; controlY1 *= scaleY; controlX2 *= scaleX; controlY2 *= scaleY; endX *= scaleX; endY *= scaleY; return true; } @Override public String pathAbs() { return "M " + imageScale(startX) + "," + imageScale(startY) + " \n" + "C " + imageScale(controlX1) + "," + imageScale(controlY1) + " " + imageScale(controlX2) + "," + imageScale(controlY2) + " " + imageScale(endX) + "," + imageScale(endY) + " \n"; } @Override public String pathRel() { return "M " + imageScale(startX) + "," + imageScale(startY) + " \n" + "c " + imageScale(controlX1 - startX) + "," + imageScale(controlY1 - startY) + " " + imageScale(controlX2 - startX) + "," + imageScale(controlY2 - startY) + " " + imageScale(endX - startX) + "," + imageScale(endY - startY); } @Override public String elementAbs() { return "<path d=\"\n" + pathAbs() + "\n\"> "; } @Override public String elementRel() { return "<path d=\"\n" + pathRel() + "\n\"> "; } public double getStartX() { return startX; } public void setStartX(double startX) { this.startX = startX; } public double getStartY() { return startY; } public void setStartY(double startY) { this.startY = startY; } public double getEndX() { return endX; } public void setEndX(double endX) { this.endX = endX; } public double getEndY() { return endY; } public void setEndY(double endY) { this.endY = endY; } public double getControlX1() { return controlX1; } public void setControlX1(double controlX1) { this.controlX1 = controlX1; } public double getControlY1() { return controlY1; } public void setControlY1(double controlY1) { this.controlY1 = controlY1; } public double getControlX2() { return controlX2; } public void setControlX2(double controlX2) { this.controlX2 = controlX2; } public double getControlY2() { return controlY2; } public void setControlY2(double controlY2) { this.controlY2 = controlY2; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data/FindReplaceString.java
released/MyBox/src/main/java/mara/mybox/data/FindReplaceString.java
package mara.mybox.data; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import javafx.scene.control.IndexRange; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2020-11-5 * @License Apache License Version 2.0 */ public class FindReplaceString { protected Operation operation; protected boolean isRegex, caseInsensitive, multiline, dotAll, appendTail, wrap; protected String inputString, findString, replaceString, outputString; protected int anchor, count, lastStart, lastEnd, lastReplacedLength, unit; protected IndexRange stringRange; // location in string protected String lastMatch, error; protected List<FindReplaceMatch> matches; public enum Operation { ReplaceAll, ReplaceFirst, FindNext, FindPrevious, Count, FindAll } public FindReplaceString() { isRegex = caseInsensitive = false; multiline = wrap = true; unit = 1; } public FindReplaceString reset() { count = 0; stringRange = null; lastMatch = null; outputString = inputString; error = null; lastStart = lastEnd = -1; matches = operation == Operation.FindAll ? new ArrayList<>() : null; return this; } public void initMatches() { matches = operation == Operation.FindAll ? new ArrayList<>() : null; } public boolean handleString(FxTask currentTask) { reset(); if (operation == null) { return false; } if (inputString == null || inputString.isEmpty()) { if (findString == null || findString.isEmpty()) { if (operation == Operation.ReplaceAll || operation == Operation.ReplaceFirst) { lastReplacedLength = 0; outputString = replaceString == null ? "" : replaceString; return true; } return false; } return false; } int start, end = inputString.length(); switch (operation) { case FindNext: case ReplaceFirst: if (anchor >= 0 && anchor <= inputString.length() - 1) { start = anchor; } else if (!wrap) { return true; } else { start = 0; } break; case FindPrevious: start = 0; if (anchor > 0 && anchor <= inputString.length()) { end = anchor; } else if (!wrap) { return true; } break; default: start = 0; break; } handleString(currentTask, start, end); if (currentTask != null && !currentTask.isWorking()) { return false; } if (lastMatch != null || !wrap) { return true; } // MyBoxLog.debug(operation + " " + wrap); switch (operation) { case FindNext: case ReplaceFirst: if (start <= 0) { return true; } if (isRegex) { end = inputString.length(); start = 0; } else { end = start + findString.length(); start = 0; } return handleString(currentTask, start, end); case FindPrevious: if (end > inputString.length()) { return true; } if (isRegex) { end = inputString.length(); start = unit; } else { start = Math.max(unit, end - findString.length() + unit); end = inputString.length(); } handleString(currentTask, start, end); return currentTask == null || currentTask.isWorking(); default: return true; } } public boolean handleString(FxTask currentTask, int start, int end) { try { // MyBoxLog.debug(operation + " start:" + start + " end:" + end + " findString:>>" + findString + "<< unit:" + unit); // MyBoxLog.debug("findString.length():" + findString.length()); // MyBoxLog.debug("replaceString:>>" + replaceString + "<<"); // MyBoxLog.debug("\n------\n" + inputString + "\n-----"); reset(); int mode = (isRegex ? 0x00 : Pattern.LITERAL) | (caseInsensitive ? Pattern.CASE_INSENSITIVE : 0x00) | (dotAll ? Pattern.DOTALL : 0x00) | (multiline ? Pattern.MULTILINE : 0x00); Pattern pattern = Pattern.compile(findString, mode); Matcher matcher = pattern.matcher(inputString); int finalEnd = Math.min(inputString.length(), end); matcher.region(Math.max(0, start), finalEnd); StringBuffer s = new StringBuffer(); String finalReplace = replaceString == null ? "" : replaceString; if (!finalReplace.isBlank()) { finalReplace = Matcher.quoteReplacement(finalReplace); } OUTER: while (matcher.find()) { count++; lastMatch = matcher.group(); lastStart = matcher.start(); lastEnd = matcher.end(); if (null == operation) { if (matcher.start() >= finalEnd) { break OUTER; } matcher.region(lastStart + unit, finalEnd); } else { // MyBoxLog.debug(count + " " + matcher.start() + " " + matcher.end() + " " + lastMatch); // MyBoxLog.debug(inputString.substring(0, matcher.start()) + "\n----------------"); switch (operation) { case FindNext: break OUTER; case ReplaceFirst: matcher.appendReplacement(s, finalReplace); break OUTER; case ReplaceAll: matcher.appendReplacement(s, finalReplace); // MyBoxLog.debug("\n---" + count + "---\n" + s.toString() + "\n-----"); break; case FindAll: FindReplaceMatch m = new FindReplaceMatch() .setStart(lastStart).setEnd(lastEnd) .setMatchedPrefix(lastMatch); matches.add(m); default: int newStart = lastStart + unit; if (newStart >= finalEnd) { break; } matcher.region(newStart, finalEnd); } } } // MyBoxLog.debug("count:" + count); if (lastMatch != null) { stringRange = new IndexRange(lastStart, lastEnd); if (operation == Operation.ReplaceAll || operation == Operation.ReplaceFirst) { String replacedPart = s.toString(); lastReplacedLength = replacedPart.length(); // MyBoxLog.debug("lastReplacedLength:" + lastReplacedLength); matcher.appendTail(s); outputString = s.toString(); // MyBoxLog.debug("\n---outputString---\n" + outputString + "\n-----"); // MyBoxLog.debug("inputString:" + inputString.length() + " outputString:" + outputString.length()); } // MyBoxLog.debug(operation + " stringRange:" + stringRange.getStart() + " " + stringRange.getEnd() + " len:" + stringRange.getLength() // + " findString:>>" + findString + "<< lastMatch:>>" + lastMatch + "<<"); } else { outputString = inputString + ""; } return true; } catch (Exception e) { MyBoxLog.debug(e); error = e.toString(); return false; } } public String replace(FxTask currentTask, String string, String find, String replace) { setInputString(string).setFindString(find) .setReplaceString(replace == null ? "" : replace) .setAnchor(0) .handleString(currentTask); if (currentTask != null && !currentTask.isWorking()) { return message("Canceled"); } return outputString; } /* static methods */ public static FindReplaceString create() { return new FindReplaceString(); } public static FindReplaceString finder(boolean isRegex, boolean isCaseInsensitive) { return create().setOperation(FindReplaceString.Operation.FindNext) .setAnchor(0).setIsRegex(isRegex).setCaseInsensitive(isCaseInsensitive).setMultiline(true); } public static FindReplaceString counter(boolean isRegex, boolean isCaseInsensitive) { return create().setOperation(FindReplaceString.Operation.Count) .setAnchor(0).setIsRegex(isRegex).setCaseInsensitive(isCaseInsensitive).setMultiline(true); } public static int count(FxTask currentTask, String string, String find) { return count(currentTask, string, find, 0, false, false, true); } public static int count(FxTask currentTask, String string, String find, int from, boolean isRegex, boolean caseInsensitive, boolean multiline) { FindReplaceString stringFind = create() .setOperation(Operation.Count) .setInputString(string).setFindString(find).setAnchor(from) .setIsRegex(isRegex).setCaseInsensitive(caseInsensitive).setMultiline(multiline); stringFind.handleString(currentTask); if (currentTask != null && !currentTask.isWorking()) { return -1; } return stringFind.getCount(); } public static IndexRange next(FxTask currentTask, String string, String find, int from, boolean isRegex, boolean caseInsensitive, boolean multiline) { FindReplaceString stringFind = create() .setOperation(Operation.FindNext) .setInputString(string).setFindString(find).setAnchor(from) .setIsRegex(isRegex).setCaseInsensitive(caseInsensitive).setMultiline(multiline); stringFind.handleString(currentTask); if (currentTask != null && !currentTask.isWorking()) { return null; } return stringFind.getStringRange(); } public static IndexRange previous(FxTask currentTask, String string, String find, int from, boolean isRegex, boolean caseInsensitive, boolean multiline) { FindReplaceString stringFind = create() .setOperation(Operation.FindPrevious) .setInputString(string).setFindString(find).setAnchor(from) .setIsRegex(isRegex).setCaseInsensitive(caseInsensitive).setMultiline(multiline); stringFind.handleString(currentTask); if (currentTask != null && !currentTask.isWorking()) { return null; } return stringFind.getStringRange(); } public static String replaceAll(FxTask currentTask, String string, String find, String replace) { return replaceAll(currentTask, string, find, replace, 0, false, false, true); } public static String replaceAll(FxTask currentTask, String string, String find, String replace, int from, boolean isRegex, boolean caseInsensitive, boolean multiline) { FindReplaceString stringFind = create() .setOperation(Operation.ReplaceAll) .setInputString(string).setFindString(find).setReplaceString(replace).setAnchor(from) .setIsRegex(isRegex).setCaseInsensitive(caseInsensitive).setMultiline(multiline); stringFind.handleString(currentTask); if (currentTask != null && !currentTask.isWorking()) { return null; } return stringFind.getOutputString(); } public static String replaceAll(FxTask currentTask, FindReplaceString findReplace, String string, String find, String replace) { findReplace.setInputString(string).setFindString(find).setReplaceString(replace) .setAnchor(0).handleString(currentTask); if (currentTask != null && !currentTask.isWorking()) { return null; } return findReplace.getOutputString(); } public static String replaceFirst(FxTask currentTask, String string, String find, String replace) { return replaceFirst(currentTask, string, find, replace, 0, false, false, true); } public static String replaceFirst(FxTask currentTask, String string, String find, String replace, int from, boolean isRegex, boolean caseInsensitive, boolean multiline) { FindReplaceString stringFind = create() .setOperation(Operation.ReplaceFirst) .setInputString(string).setFindString(find).setReplaceString(replace).setAnchor(from) .setIsRegex(isRegex).setCaseInsensitive(caseInsensitive).setMultiline(multiline); stringFind.handleString(currentTask); if (currentTask != null && !currentTask.isWorking()) { return null; } return stringFind.getOutputString(); } /* get/set */ public boolean isIsRegex() { return isRegex; } public FindReplaceString setIsRegex(boolean isRegex) { this.isRegex = isRegex; return this; } public boolean isCaseInsensitive() { return caseInsensitive; } public FindReplaceString setCaseInsensitive(boolean caseInsensitive) { this.caseInsensitive = caseInsensitive; return this; } public boolean isMultiline() { return multiline; } public FindReplaceString setMultiline(boolean multiline) { this.multiline = multiline; return this; } public String getInputString() { return inputString; } public boolean isDotAll() { return dotAll; } public FindReplaceString setDotAll(boolean dotAll) { this.dotAll = dotAll; return this; } public int getLastEnd() { return lastEnd; } public void setLastEnd(int lastEnd) { this.lastEnd = lastEnd; } public FindReplaceString setInputString(String inputString) { this.inputString = inputString; return this; } public String getFindString() { return findString; } public FindReplaceString setFindString(String findString) { this.findString = findString; return this; } public String getReplaceString() { return replaceString; } public FindReplaceString setReplaceString(String replaceString) { this.replaceString = replaceString; return this; } public String getOutputString() { return outputString; } public FindReplaceString setOuputString(String outputString) { this.outputString = outputString; return this; } public int getCount() { return count; } public FindReplaceString setCount(int count) { this.count = count; return this; } public IndexRange getStringRange() { return stringRange; } public FindReplaceString setStringRange(IndexRange lastRange) { this.stringRange = lastRange; return this; } public String getLastMatch() { return lastMatch; } public FindReplaceString setLastMatch(String lastMatch) { this.lastMatch = lastMatch; return this; } public FindReplaceString setAnchor(int anchor) { this.anchor = anchor; return this; } public int getAnchor() { return anchor; } public Operation getOperation() { return operation; } public FindReplaceString setOperation(Operation operation) { this.operation = operation; return this; } public boolean isAppendTail() { return appendTail; } public FindReplaceString setAppendTail(boolean appendTail) { this.appendTail = appendTail; return this; } public int getLastStart() { return lastStart; } public FindReplaceString setLastStart(int lastStart) { this.lastStart = lastStart; return this; } public int getLastReplacedLength() { return lastReplacedLength; } public FindReplaceString setLastReplacedLength(int lastReplacedLength) { this.lastReplacedLength = lastReplacedLength; return this; } public boolean isWrap() { return wrap; } public FindReplaceString setWrap(boolean wrap) { this.wrap = wrap; return this; } public int getUnit() { return unit; } public FindReplaceString setUnit(int step) { this.unit = step; return this; } public String getError() { return error; } public FindReplaceString setError(String error) { this.error = error; return this; } public List<FindReplaceMatch> getMatches() { return matches; } public FindReplaceString setMatches(List<FindReplaceMatch> matches) { this.matches = matches; return this; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data/IntPoint.java
released/MyBox/src/main/java/mara/mybox/data/IntPoint.java
package mara.mybox.data; /** * @Author Mara * @CreateDate 2018-11-11 12:23:02 * @Version 1.0 * @Description * @License Apache License Version 2.0 */ public class IntPoint { private int x, y; public IntPoint(int x, int y) { this.x = x; this.y = y; } public static int distance2(int x1, int y1, int x2, int y2) { int distanceX = x1 - x2; int distanceY = y1 - y2; return distanceX * distanceX + distanceY * distanceY; } public static int distance(int x1, int y1, int x2, int y2) { return (int) Math.sqrt(distance2(x1, y1, x2, y2)); } public static int distance2(IntPoint A, IntPoint B) { int distanceX = A.getX() - B.getX(); int distanceY = A.getY() - B.getY(); return distanceX * distanceX + distanceY * distanceY; } public static int distance(IntPoint A, IntPoint B) { return (int) Math.sqrt(distance2(A, B)); } public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data/DataSort.java
released/MyBox/src/main/java/mara/mybox/data/DataSort.java
package mara.mybox.data; import java.util.ArrayList; import java.util.List; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2022-12-1 * @License Apache License Version 2.0 */ public class DataSort { protected String name; protected boolean ascending; public DataSort() { this.name = null; this.ascending = true; } public DataSort(String name, boolean ascending) { this.name = name; this.ascending = ascending; } /* static */ public static List<DataSort> parse(List<String> orders) { if (orders == null || orders.isEmpty()) { return null; } List<DataSort> sorts = new ArrayList<>(); String descString = "-" + message("Descending"); String ascString = "-" + message("Ascending"); int desclen = descString.length(); int asclen = ascString.length(); String sname; boolean asc; for (String order : orders) { if (order.endsWith(descString)) { sname = order.substring(0, order.length() - desclen); asc = false; } else if (order.endsWith(ascString)) { sname = order.substring(0, order.length() - asclen); asc = true; } else { continue; } sorts.add(new DataSort(sname, asc)); } return sorts; } public static List<String> parseNames(List<String> orders) { if (orders == null || orders.isEmpty()) { return null; } List<String> names = new ArrayList<>(); String descString = "-" + message("Descending"); String ascString = "-" + message("Ascending"); int desclen = descString.length(); int asclen = ascString.length(); String sname; for (String order : orders) { if (order.endsWith(descString)) { sname = order.substring(0, order.length() - desclen); } else if (order.endsWith(ascString)) { sname = order.substring(0, order.length() - asclen); } else { continue; } if (!names.contains(sname)) { names.add(sname); } } return names; } public static String toString(List<DataSort> sorts) { if (sorts == null || sorts.isEmpty()) { return null; } String orderBy = null, piece; for (DataSort sort : sorts) { piece = sort.getName() + (sort.isAscending() ? " ASC" : " DESC"); if (orderBy == null) { orderBy = piece; } else { orderBy += ", " + piece; } } return orderBy; } public static String parseToString(List<String> orders) { return toString(parse(orders)); } /* get/set */ public String getName() { return name; } public DataSort setName(String name) { this.name = name; return this; } public boolean isAscending() { return ascending; } public DataSort setAscending(boolean ascending) { this.ascending = ascending; return this; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data/DoubleQuadratic.java
released/MyBox/src/main/java/mara/mybox/data/DoubleQuadratic.java
package mara.mybox.data; import java.awt.geom.QuadCurve2D; import static mara.mybox.tools.DoubleTools.imageScale; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2023-7-31 * @License Apache License Version 2.0 */ public class DoubleQuadratic implements DoubleShape { private double startX, startY, controlX, controlY, endX, endY; public DoubleQuadratic() { } public DoubleQuadratic(double startX, double startY, double controlX, double controlY, double endX, double endY) { this.startX = startX; this.startY = startY; this.controlX = controlX; this.controlY = controlY; this.endX = endX; this.endY = endY; } @Override public String name() { return message("QuadraticCurve"); } @Override public QuadCurve2D.Double getShape() { return new QuadCurve2D.Double(startX, startY, controlX, controlY, endX, endY); } @Override public DoubleQuadratic copy() { return new DoubleQuadratic(startX, startY, controlX, controlY, endX, endY); } @Override public boolean isValid() { return true; } @Override public boolean isEmpty() { return !isValid(); } @Override public boolean translateRel(double offsetX, double offsetY) { startX += offsetX; startY += offsetY; controlX += offsetX; controlY += offsetY; endX += offsetX; endY += offsetY; return true; } @Override public boolean scale(double scaleX, double scaleY) { startX *= scaleX; startY *= scaleY; controlX *= scaleX; controlY *= scaleY; endX *= scaleX; endY *= scaleY; return true; } @Override public String pathAbs() { return "M " + imageScale(startX) + "," + imageScale(startY) + " \n" + "Q " + imageScale(controlX) + "," + imageScale(controlY) + " " + imageScale(endX) + "," + imageScale(endY); } @Override public String pathRel() { return "M " + imageScale(startX) + "," + imageScale(startY) + " \n" + "q " + imageScale(controlX - startX) + "," + imageScale(controlY - startY) + " " + imageScale(endX - startX) + "," + imageScale(endY - startY); } @Override public String elementAbs() { return "<path d=\"\n" + pathAbs() + "\n\"> "; } @Override public String elementRel() { return "<path d=\"\n" + pathRel() + "\n\"> "; } /* get */ public double getStartX() { return startX; } public void setStartX(double startX) { this.startX = startX; } public double getStartY() { return startY; } public void setStartY(double startY) { this.startY = startY; } public double getEndX() { return endX; } public void setEndX(double endX) { this.endX = endX; } public double getEndY() { return endY; } public void setEndY(double endY) { this.endY = endY; } public double getControlX() { return controlX; } public void setControlX(double controlX) { this.controlX = controlX; } public double getControlY() { return controlY; } public void setControlY(double controlY) { this.controlY = controlY; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/data/RemoteFile.java
released/MyBox/src/main/java/mara/mybox/data/RemoteFile.java
package mara.mybox.data; import com.jcraft.jsch.SftpATTRS; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2023-03-18 * @License Apache License Version 2.0 */ public class RemoteFile extends FileNode { public RemoteFile() { separator = "/"; } public RemoteFile(SftpATTRS attrs) { try { if (attrs == null) { isExisted = false; return; } isExisted = true; if (attrs.isDir()) { setFileType(FileInformation.FileType.Directory); } else if (attrs.isBlk()) { setFileType(FileInformation.FileType.Block); } else if (attrs.isChr()) { setFileType(FileInformation.FileType.Character); } else if (attrs.isFifo()) { setFileType(FileInformation.FileType.FIFO); } else if (attrs.isLink()) { setFileType(FileInformation.FileType.Link); } else if (attrs.isSock()) { setFileType(FileInformation.FileType.Socket); } else { setFileType(FileInformation.FileType.File); } setFileSize(attrs.getSize()); setModifyTime(attrs.getMTime() * 1000l); setAccessTime(attrs.getATime() * 1000l); setUid(attrs.getUId()); setGid(attrs.getGId()); setPermission(attrs.getPermissionsString()); } catch (Exception e) { } } @Override public String getFullName() { return nodeFullName(); } @Override public String getSuffix() { return fileType != null ? message(fileType.name()) : null; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false