text
stringlengths
10
2.72M
package test; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class TestThread { public static void main(String args[]) throws InterruptedException, ExecutionException { ExecutorService service = Executors.newFixedThreadPool(100); List<CompletableFuture<?>> completableFutures = new ArrayList<>(); for (int i = 0; i < 100; ++i) { CompletableFuture<?> completableFuture = CompletableFuture.runAsync(() -> { System.out.println("running " + Thread.currentThread().getName()); try { Thread.sleep(600000000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } }, service); completableFutures.add(completableFuture); } for (CompletableFuture<?> future : completableFutures) { future.get(); } service.shutdown(); } }
package br.com.mbreno.atividades; public class CPricipal { public static void main(String[] args) { Carro c = new Carro(); c.nome = "honda"; c.ano = 2012; c.modelo = "Ret"; System.out.println("Carro: " + c.nome); c = null; Carro c1 = new Carro (); c1.nome = "Ford"; System.out.println(c1.nome); } }
import java.util.Scanner; import javax.swing.JOptionPane; public class computePie2 { public static void main(String[] args) { boolean plusMinus = true; String termInput = JOptionPane.showInputDialog (null, "Please enter the number of terms you wish to view of PI( or type exit) "); Scanner inputScanner = new Scanner (termInput); if (inputScanner.hasNextInt()) { double computationNumber1 = 2; double computationNumber2 = 3; double computationNumber3 = 4; int inputTerms = inputScanner.nextInt(); inputScanner.close() ; int terms = inputTerms ; double PI = 0.00; while (terms!= 0 ) { PI =3.00; double multiplier = computationNumber1*computationNumber2*computationNumber3; double division = 4/multiplier; if (plusMinus = true) { PI = PI + division ; plusMinus = false; } else if (plusMinus = false) { PI = PI - division; plusMinus = true; } computationNumber1 +=2; computationNumber2 +=2; computationNumber3 +=2; terms --; } JOptionPane.showMessageDialog (null,"PI to "+ inputTerms +" terms is " + PI); } else { JOptionPane.showMessageDialog (null,"No valid numbers provided", "Error",JOptionPane.ERROR_MESSAGE); } } }
package pl.cwanix.opensun.agentserver.packets.s2c.character; import org.apache.commons.lang3.ArrayUtils; import pl.cwanix.opensun.commonserver.packets.Packet; import pl.cwanix.opensun.utils.datatypes.FixedLengthField; @SuppressWarnings("checkstyle:MagicNumber") //@OutgoingPacket(category = PacketCategory.CHARACTER, type = 0x71) public class S2CErrDeleteCharPacket implements Packet { private final FixedLengthField errorCode; public S2CErrDeleteCharPacket(final int errorCode) { this.errorCode = new FixedLengthField(4, errorCode); } @Override public Object[] getOrderedFields() { return ArrayUtils.toArray(errorCode); } }
package com.isystk.sample.domain.dto; import java.util.List; import java.time.LocalDate; import java.time.LocalDateTime; import lombok.Getter; import lombok.Setter; /** * 自動生成のため原則修正禁止!! */ @Getter @Setter public class TPostTagCriteria { Integer postIdEq; Integer postIdNe; Integer postIdLt; Integer postIdLe; Integer postIdGt; Integer postIdGe; boolean postIdIsNull; boolean postIdIsNotNull; List<Integer> postIdIn; List<Integer> postIdNotIn; Integer postTagIdEq; Integer postTagIdNe; Integer postTagIdLt; Integer postTagIdLe; Integer postTagIdGt; Integer postTagIdGe; boolean postTagIdIsNull; boolean postTagIdIsNotNull; List<Integer> postTagIdIn; List<Integer> postTagIdNotIn; String orderBy; }
package org.study.core.operators; public class BitwiseOperators { private static void makeOperations(final int seed) { System.out.println("== Start with " + seed + " (" + Integer.toBinaryString(seed) + ")"); System.out.println(">> 1 is " + (seed >> 1) + " (" + Integer.toBinaryString(seed >> 1) + ")"); System.out.println("<< 1 is " + (seed << 1) + " (" + Integer.toBinaryString(seed << 1) + ")"); } public static void main(String[] args) { makeOperations(4); makeOperations(100); makeOperations(11); } }
/* Java Power Info utility, (C)2022 IC Book Labs Main class of the project Use JDK8 from v0.81. Previous versions use JDK7 mode. ---------- How design Linux version, variant 1 --------------------------------- --- Step 1, learn Linux power management --- User interface design: Screen 1 = Power status brief info, get text data, Screen 2 = Battery details full info, get text data, Screen 3 = Charging monitor, get numeric data, Screen 4 = OS information, get text data, Screen 5 = Java cross-platform information, no changes, Plus ennumeration path get array of text strings. --- Step 2, formalization with existed API architecture --- Build classes: TableModelBatteryDetailsLinux = override TableModelBatteryDetails, TableModelPowerStatusLinux = override TableModelPowerStatus, TableModelLinux = override TableModelWindows. Native methods not required, use "/proc" filesystem under Linux. tmbd = f(OS type) tmps = f(OS type) tmos = f(OS type) --- Step 3, optimization --- Remove Windows-centric assymetry, make abstract class or interface for this classes, instantiation or implementation = f(OS type), replace model: Primary=Windows , Override=Linux to model: Primary=Abstract , Override = Windows or Linux, f(OS type). ---------- How design Linux version, variant 2 --------------------------------- Linux features effect maximized Screen 1 = Power Status, tree and table based on "/sys" filesystem subtree. Screen 2 = Battery details, tree and table based on "/sys" filesystem subtree. Screen 3 = Charging monitor, fast get one parameter by "/sys/ ... fixed ...". Screen 4 = Linux (instead Windows), full tree of "/sys" filesystem. Screen 5 = Java, not changed because cross-platform. */ package powerinfo; import java.util.ArrayList; import java.util.Timer; import java.util.TimerTask; import java.awt.*; import java.awt.event.*; import java.util.Vector; import javax.swing.*; import javax.swing.table.*; import javax.swing.tree.*; import static javax.swing.JFrame.EXIT_ON_CLOSE; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import powerinfo.supportwindows.*; import powerinfo.supportlinux.*; import powerinfo.supportcpu.*; // Main class declaration start public class PowerInfo { // Main class fields private static final int X_SIZE = 580, Y_SIZE = 488+40; // window size public static PAL pal; // platform abstraction layer, native calls private static int jniStatus; // status of java native interface call private static Timer timer1; // timer for revisualization private static boolean ctoggle; // draw mode active flag private static int nativeID; // 0=Win32, 1=Win64, 2=Linux32, 3=Linux64 private static DataModelChargingMonitor bcm1, bcm2; // drawings mod. private static GraphIcon gic1, gic2; // drawings ics. private static TableModelPowerStatus atmAC; // AC power table model private static TableModelBatteryDetails atmBAT; // Battery power table model private static GUIbox guiBox; // window class private static JButton b1, b2, b3, b4; // down buttons private static JTabbedPane rootMenu; // root menu private static JPanel downButtons; // buttons panel private static JPanel[] rootPanels; // panels for tabs private static JTable rvt1, rvt2; // timer revisualized table private static JPanel rvp1; // timer revisualized panel private static JCheckBox[] drawChecks; // enable drawings for bats private static boolean[] drawFlags; // flags for checkboxes private static final String[] NAMES_WINDOWS = // tabs names for Windows { "Power status" , "Battery details" , "Charging monitor" , "Windows" , "Java" }; private static final String[] NAMES_LINUX = // tabs names for Linux { "AC power" , "Battery" , "Charging monitor" , "/sys" , "/proc" , "Java" }; private static final String[] NAMES_COMMON = // tabs names for both w/l { "CPU" }; private static String[] panelsNames; // result names array=f(OS) private static final String AC_ENUM = "AC source path"; // jcombo names private static final String BAT_ENUM = "Battery path"; private static AbstractTableModel[] reportTables1, reportTables2; // reports // Application entry point public static void main(String[] args) { // Setup variables and GUI options ctoggle = false; // charging monitor drawings enable nativeID = -1; // 0=Win32, 1=Win64, 2=Linux32, 3=Linux64, -1=Unknown JFrame.setDefaultLookAndFeelDecorated( true ); // Decorate main window JDialog.setDefaultLookAndFeelDecorated( true ); // Decorate dialog windows // Load native library pal = new PAL(); // Initializing Platform Abstraction Layer jniStatus = pal.loadUserModeLibrary(); // Load OS-specific library nativeID = pal.getNativeType(); // This actual after load try if ( ! ( ( nativeID == 2 ) | ( nativeID == 3 ) ) ) // Linux mode w/o native lib { if ( ( jniStatus < 0 ) | ( pal.getNativeValid() == false ) ) JOptionPane.showMessageDialog ( null, "Native library load failed" , About.getShortName() , JOptionPane.ERROR_MESSAGE ); } // --- Start common branch (WINDOWS, LINUX) --- // Initializing Processor support JPanel rp10 = new JPanel(); ViewerTree vp10 = new ViewerTree( X_SIZE, Y_SIZE , null , null , null ); if ( ( nativeID >= 0 ) & ( pal.getNativeValid() ) ) { TreeModelCPU trmc = new TreeModelCPU(); // includes TSC measure TreeMonitorCPU tmcp = new TreeMonitorCPU(); // monitor node expand ArrayList<DefaultMutableTreeNode> list10 = trmc.getCpuList(); DefaultTreeModel dtm10 = new DefaultTreeModel( list10.get(0) , true ); AbstractTableModel atm10 = new TableModelCPU(); TreeNodeExpander cputnx1 = new CPUTNX1( dtm10 , list10 ); vp10 = new ViewerTree( X_SIZE, Y_SIZE , dtm10 , atm10 , cputnx1 ); cputnx1.setViewer( vp10 ); // expander must have access to table cputnx1.setMonitor( tmcp ); // expander must call tree monitor double clk; clk = trmc.getTscClkHz(); // measure and return clk TableModelClk tclk = new TableModelClk( clk ); // create model replacer tmcp.setModel( tclk ); // assign table model for tree monitor rp10 = vp10.getP(); } // --- WINDOWS BRANCH --- if ( ( nativeID == 0 ) | ( nativeID == 1 ) ) { int n1 = NAMES_WINDOWS.length; // n1 = Number of Windows-specific panels int n2 = NAMES_COMMON.length; // n2 = Number of Common panels int n = n1 + n2; // n = Total number of panels int j = 0; // j = Total counter panelsNames = new String[n]; for ( int i=0; i<n1; i++ ) { panelsNames[j] = NAMES_WINDOWS[i]; j++; } for ( int i=0; i<n2; i++ ) { panelsNames[j] = NAMES_COMMON[i]; j++; } // AC power window String acPath = "AC power supply"; // Value of combo box atmAC = new TableModelPowerStatusWindows(); // Table model ACselect cch1 = new ACselect(); // Listener for combo box final ViewerTableCombo vp1 = // Panel = Combo + Table new ViewerTableCombo( X_SIZE, Y_SIZE, AC_ENUM, cch1, atmAC ); vp1.getCombo().addItem( acPath ); // Set value for combo JPanel rp1 = vp1.getP(); // GUI panel, one of tabs // Battery power window atmBAT = new TableModelBatteryDetailsWindows(); // Table model String[] batPaths = atmBAT.getEnumerationPath(); // Get paths set int np = 0; if ( batPaths != null ) { np = batPaths.length; } atmBAT.setSelected(0); // Make selection for table BATselect cch2 = new BATselect(); // Listener for combo box final ViewerTableCombo vp2 = // Panel = Combo + Table new ViewerTableCombo( X_SIZE, Y_SIZE, BAT_ENUM , cch2, atmBAT ); for( int i=0; i<np; i++ ) // Set value for combo { vp2.getCombo().addItem( batPaths[i] ); } JPanel rp2 = vp2.getP(); // GUI panel, one of tabs // Add listener for combo box: battery enumeration path vp2.getCombo().addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JComboBox box = (JComboBox)e.getSource(); ComboBoxModel cbm = box.getModel(); Object ob = cbm.getSelectedItem(); int sel = 0; int n = cbm.getSize(); for ( sel=0; sel<n; sel++ ) { if ( ob.equals(cbm.getElementAt( sel )) ) break; } atmBAT.setSelected( sel ); rvt2.revalidate(); rvt2.repaint(); rvp1.revalidate(); rvp1.repaint(); } } ); // Set to table model // Charging monitor window // Graph1: current level, mWh = F (Time, seconds) gic1 = new GraphIcon( 560, 161 ); // Up icon, draw y=f(x) // Graph2: current rate, mW = F (Time, seconds) gic2 = new GraphIcon( 560, 161 ); // Down icon, draw y=f(x) // Data model int a = gic1.getUsedWidth(); int b = gic2.getUsedWidth(); if ( a < b ) { a = b; } bcm1 = new DataModelChargingMonitor( a ); // Data model = f(Xsize) bcm2 = new DataModelChargingMonitor( a ); // Setup power units: mWh/mW or Relative ratio units boolean c; c = atmBAT.getPowerUnits(); bcm1.setPowerUnits( c ); bcm2.setPowerUnits( c ); // Text strings, get from model, set to icons String s; s = bcm1.getNameX1(); gic1.setNameX( s ); // Text strings, up icon s = bcm1.getNameY1(); gic1.setNameY( s ); s = bcm1.getNameX2(); gic2.setNameX( s ); // Text strings, down icon s = bcm1.getNameY2(); gic2.setNameY( s ); // Select units double miny1, maxy1, miny2, maxy2; if (c) { // this values for Relative ratio units miny1 = 0.0; maxy1 = 120.0; miny2 = -100.0; maxy2 = 100.0; } else { // this values for mWh/mW miny1 = 45000.0; maxy1 = 60000.0; miny2 = -3000.0; maxy2 = 3000.0; } gic1.setMinX( 0.0 ); gic1.setMaxX( a/2 ); // Dimensions, up icon gic1.setMinY( miny1 ); gic1.setMaxY( maxy1 ); gic2.setMinX( 0.0 ); gic2.setMaxX( a/2 ); // Dimensions, down icon gic2.setMinY( miny2 ); gic2.setMaxY( maxy2 ); // Build viewer int nb = 0; Vector drawVector = new Vector(); if ( batPaths != null ) { nb = batPaths.length; drawVector = new Vector(); drawChecks = new JCheckBox[nb]; for( int i=0; i<nb; i++ ) { drawChecks[i] = new JCheckBox( batPaths[i], false ); drawVector.add( drawChecks[i] ); } drawChecks[0].setSelected(true); } else { drawVector.add( "N/A" ); } final ViewerPowerDraws vp3 = // Panel = 2 draws + 2 buttons new ViewerPowerDraws( X_SIZE, Y_SIZE, bcm1, gic1, gic2, BAT_ENUM, drawVector ); JPanel rp3 = vp3.getP(); // GUI panel, one of tabs // Add listeners for checkboxes, with build array drawFlags = new boolean[10]; for( int i=0; i<10; i++ ) { drawFlags[i] = false; } drawFlags[0] = true; for( int i=0; i<nb; i++ ) { drawChecks[i].addChangeListener( new ChangeListener() { @Override public void stateChanged( ChangeEvent e ) { for(int i=0; i<drawChecks.length; i++ ) { drawFlags[i] = drawChecks[i].getModel().isSelected(); } gic1.clearMeasure(); gic2.clearMeasure(); bcm1.clearArrayY1(); bcm1.clearArrayY2(); bcm2.clearArrayY1(); bcm2.clearArrayY2(); } }); } // Add listener for Graph CLEAR button vp3.getClearButton().addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent e ) { gic1.clearMeasure(); // This executed when press CLEAR button gic2.clearMeasure(); // clear drawings icon bcm1.clearArrayY1(); bcm1.clearArrayY2(); // clear model bcm2.clearArrayY1(); bcm2.clearArrayY2(); // clear model ctoggle=false; // disable drawings vp3.getRunButton().setText("Run"); } } ); // "Stop" replaced to "Run" // Add listener for Graph RUN button vp3.getRunButton().addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent e ) { if ( ctoggle == true ) // Check current state: STOP or RUN { // If current state is STOP, set RUN vp3.getRunButton().setText( "Run" ); } else { // If current state is RUN, set STOP vp3.getRunButton().setText( "Stop" ); } ctoggle =! ctoggle; // Invert status "Run" / "Stop" } } ); // Windows OS info window TableModelOs atm4 = new TableModelWindows(); // Windows info table model ViewerTable vp4 = new ViewerTable( X_SIZE, Y_SIZE, atm4 ); // Panel = Table JPanel rp4 = vp4.getP(); // GUI panel, one of tabs // Java info window TableModelJava atm5 = new TableModelJava(); // Java info table model ViewerTable vp5 = new ViewerTable( X_SIZE, Y_SIZE, atm5 ); // Panel = Table JPanel rp5 = vp5.getP(); // GUI panel, one of tabs // Build result of windows-specific branch // Create array of panels for visual and array of table models for report, // plus special pool for dynamical revisual rootPanels = new JPanel[] { rp1, rp2, rp3, rp4, rp5, rp10 }; reportTables1 = new AbstractTableModel[] { // BUG, NEED GET LATER (AbstractTableModel) vp1.getTable().getModel() , (AbstractTableModel) vp2.getTable().getModel() , null , (AbstractTableModel) vp4.getTable().getModel() , (AbstractTableModel) vp5.getTable().getModel() , (AbstractTableModel) vp10.getTable().getModel() , }; reportTables2 = new AbstractTableModel[] // Second array required, because { null, null, null, null, null, null }; // 2 tables supported at CPUID rvp1 = rp3; // drawings panel, supported dynamical revisual rvt1 = vp1.getTable(); // AC panel, supported dynamical revisual rvt2 = vp2.getTable(); // BAT panel, supported dynamical revisual } // --- LINUX BRANCH --- else if ( ( nativeID == 2 ) | ( nativeID == 3 ) ) // 2=Linux32, 3=Linux64 { int n1 = NAMES_LINUX.length; // n1 = Number of Linux-specific tabs int n2 = NAMES_COMMON.length; // n2 = Number of Common tabs int n = n1 + n2; // n = Total number of panels (tabs) int j = 0; // j = Total counter panelsNames = new String[n]; for (int i=0; i<n1; i++ ) { panelsNames[j] = NAMES_LINUX[i]; j++; } for (int i=0; i<n2; i++ ) { panelsNames[j] = NAMES_COMMON[i]; j++; } String acPath = "/sys/class/power_supply/AC"; // Linux Path for AC String batPath; // Linux Path for BAT TreeModelLinux trml = new TreeModelLinux(); // Models "/sys", "/proc" TreeMonitorLinux tmlx = new TreeMonitorLinux(); // Node open monitor // AC power window atmAC = new TableModelPowerStatusLinux(); // Table model for AC ACselect cch1 = new ACselect(); // Listener for combo box final ViewerTableCombo vp1 = // Panel = Combo + Table new ViewerTableCombo( X_SIZE, Y_SIZE, AC_ENUM, cch1, atmAC ); vp1.getCombo().addItem( acPath ); // Set one value for combo JPanel rp1 = vp1.getP(); // GUI panel, one of tabs // Battery power window atmBAT = new TableModelBatteryDetailsLinux(); // Table model for BAT String[] batPaths = atmBAT.getEnumerationPath(); // Get paths set batPath = ""; if (batPaths!=null) { batPath = batPaths[0]; // First path from set } BATselect cch2 = new BATselect(); // Listener for combo box final ViewerTableCombo vp2 = // Panel = Combo + Table new ViewerTableCombo( X_SIZE, Y_SIZE, BAT_ENUM , cch2, atmBAT ); vp2.getCombo().addItem(batPath); // Set one value for combo JPanel rp2 = vp2.getP(); // GUI panel, one of tabs // Add listener for combo box: enumeration path vp2.getCombo().addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent e ) { int sel = vp2.getCombo().getSelectedIndex(); // Get from combo atmBAT.setSelected(sel); } } ); // Set to table model // Charging monitor window // Graph1: current level, mWh = F (Time, seconds) gic1 = new GraphIcon( 560,161 ); // Up icon, y=f(x) // Graph2: current rate, mW = F (Time, seconds) gic2 = new GraphIcon( 560,161 ); // Down icon, y=f(x) // Data model int a = gic1.getUsedWidth(); int b = gic2.getUsedWidth(); if ( a<b ) { a=b; } bcm1 = new DataModelChargingMonitor( a ); // Setup data model = f(Xsize) bcm2 = new DataModelChargingMonitor( a ); // Setup data model = f(Xsize) // Text strings, get from model, set to icons String s; s = bcm1.getNameX1(); gic1.setNameX( s ); // Text strings, up icon s = bcm1.getNameY1(); gic1.setNameY( s ); s = bcm1.getNameX2(); gic2.setNameX( s ); // Text strings, down icon s = bcm1.getNameY2(); gic2.setNameY( s ); // Dimensions, set constants to icons gic1.setMinX(0.0); gic1.setMaxX( a/2 ); // Dimensions, up icon gic1.setMinY(45000.0); gic1.setMaxY( 60000.0 ); gic2.setMinX(0.0); gic2.setMaxX( a/2 ); // Dimensions, down icon gic2.setMinY(-3000.0); gic2.setMaxY( 3000.0 ); // Build viewer int nb = 0; Vector drawVector = new Vector(); if ( batPaths != null ) { nb = batPaths.length; drawVector = new Vector(); drawChecks = new JCheckBox[nb]; for( int i=0; i<nb; i++ ) { drawChecks[i] = new JCheckBox( batPaths[i], false ); drawVector.add( drawChecks[i] ); } drawChecks[0].setSelected(true); } else { drawVector.add( "N/A" ); } final ViewerPowerDraws vp3 = // Panel = 2 drawings + 2 buttons new ViewerPowerDraws( X_SIZE, Y_SIZE, bcm1, gic1, gic2, BAT_ENUM, drawVector ); JPanel rp3 = vp3.getP(); // GUI panel, one of tabs // Add listeners for checkboxes, with build array drawFlags = new boolean[10]; for( int i=0; i<10; i++ ) { drawFlags[i] = false; } drawFlags[0] = true; for( int i=0; i<nb; i++ ) { drawChecks[i].addChangeListener( new ChangeListener() { @Override public void stateChanged( ChangeEvent e ) { for(int i=0; i<drawChecks.length; i++ ) { drawFlags[i] = drawChecks[i].getModel().isSelected(); } gic1.clearMeasure(); gic2.clearMeasure(); bcm1.clearArrayY1(); bcm1.clearArrayY2(); bcm2.clearArrayY1(); bcm2.clearArrayY2(); } }); } // Add listener for Graph Clear button vp3.getClearButton().addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent e ) { gic1.clearMeasure(); // This executed when press CLEAR button gic2.clearMeasure(); bcm1.clearArrayY1(); bcm1.clearArrayY2(); bcm2.clearArrayY1(); bcm2.clearArrayY2(); ctoggle=false; vp3.getRunButton().setText( "Run" ); } } ); // Add listener for Graph Run button vp3.getRunButton().addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent e ) { if (ctoggle==true) // This executed when press RUN button { vp3.getRunButton().setText( "Run" ); // Set "RUN" if now "STOP" } else { vp3.getRunButton().setText( "Stop" ); // Set "STOP" if now "RUN" } ctoggle =! ctoggle; // Invert state "RUN" / "STOP" } } ); // Linux /sys window ArrayList<DefaultMutableTreeNode> list1 = trml.getSysList(); DefaultTreeModel dtm1 = new DefaultTreeModel( list1.get( 0 ) ,true ); AbstractTableModel atm1 = new STM1(); TreeNodeExpander tnx1 = new TNX1( dtm1, list1 ); final ViewerTree vp4 = new ViewerTree( X_SIZE, Y_SIZE, dtm1, atm1, tnx1 ); tnx1.setViewer(vp4); // Opener must read table from viewer tnx1.setMonitor(tmlx); // Opener must use node-specific open methods JPanel rp4 = vp4.getP(); // GUI Panel = Tree + Table // Linux /proc window ArrayList<DefaultMutableTreeNode> list2 = trml.getProcList(); DefaultTreeModel dtm2 = new DefaultTreeModel( list2.get( 0 ) ,true ); AbstractTableModel atm2 = new PTM1(); TreeNodeExpander tnx2 = new TNX1( dtm2, list2 ); final ViewerTree vp5 = new ViewerTree( X_SIZE, Y_SIZE, dtm2, atm2, tnx2 ); tnx2.setViewer( vp5 ); // Opener must read table from viewer tnx2.setMonitor( null ); // Opener must use node-specific open methods JPanel rp5 = vp5.getP(); // GUI Panel = Tree + Table // Java window TableModelJava atm6 = new TableModelJava(); // Table model for Java ViewerTable vp6 = new ViewerTable( X_SIZE, Y_SIZE, atm6 ); // Panel = Table JPanel rp6 = vp6.getP(); // GUI panel, one of tabs // Build result of linux-specific branch // Create array of panels for visual and array of table models for report, // plus special pool for dynamical revisual rootPanels = new JPanel[] { rp1, rp2, rp3, rp4, rp5, rp6, rp10 }; reportTables1 = new AbstractTableModel[] { // BUG, NEED GET LATER (AbstractTableModel) vp1.getTable().getModel() , (AbstractTableModel) vp2.getTable().getModel() , null , (AbstractTableModel) vp4.getTable().getModel() , (AbstractTableModel) vp5.getTable().getModel() , (AbstractTableModel) vp6.getTable().getModel() , (AbstractTableModel) vp10.getTable().getModel() }; reportTables2 = new AbstractTableModel[] // Second array required { null, null, null, null, null, null, null }; // because CPUID, 2 tables rvp1 = rp3; // drawings panel, supported dynamical revisual rvt1 = vp1.getTable(); // AC panel, supported dynamical revisual rvt2 = vp2.getTable(); // BAT panel, supported dynamical revisual } // --- BRANCHES CONVERGENTION, RETURN IF UNRECOGNIZED OS --- else { System.exit( 0 ); } // Exit if native OS not detected // Create dynamical revisualization timer // For Windows required native DLL, for Linux support by Java code if ( ( pal.getNativeValid() == true )|( nativeID == 2 )|( nativeID == 3) ) { timer1 = new Timer(); // Create timer timer1.schedule( new TimerTask() { // Create task for timer @Override public void run() { // Entry point to timer handler try { EventQueue.invokeLater( new Runnable() { @Override synchronized public void run() { //--- Drawings if enabled --- if ( ctoggle == true ) { double[][] allStamps = atmBAT.readAllStamps(); if ( allStamps == null ) { double stamp1 = atmBAT.getStamp1(); // Get from table models double stamp2 = atmBAT.getStamp2(); if ( ( stamp1 != Double.NaN ) && ( stamp2 != Double.NaN ) ) { bcm1.pushDataY1( stamp1 ); // Set to data models bcm1.pushDataY2( stamp2 ); gic1.setDrawData1 ( bcm1.getSizeX1(), bcm1.getArrayY1() ); gic2.setDrawData1 ( bcm1.getSizeX2(), bcm1.getArrayY2() ); } } else { double stamp1; double stamp2; if ( drawFlags[0]==true ) { stamp1 = allStamps[0][0]; stamp2 = allStamps[0][1]; if (( stamp1 != Double.NaN )&&( stamp2 != Double.NaN )) { bcm1.pushDataY1( stamp1 ); // Set to data models bcm1.pushDataY2( stamp2 ); gic1.setDrawData1 ( bcm1.getSizeX1(), bcm1.getArrayY1() ); gic2.setDrawData1 ( bcm1.getSizeX2(), bcm1.getArrayY2() ); } } if ( drawFlags[1]==true ) { stamp1 = allStamps[1][0]; stamp2 = allStamps[1][1]; if (( stamp1 != Double.NaN )&&( stamp2 != Double.NaN )) { bcm2.pushDataY1( stamp1 ); // Set to data models bcm2.pushDataY2( stamp2 ); gic1.setDrawData2 ( bcm2.getSizeX1(), bcm2.getArrayY1() ); gic2.setDrawData2 ( bcm2.getSizeX2(), bcm2.getArrayY2() ); } } } } // Dynamical revisual support if ( atmAC.DynamicalPowerStatus() ) { rvt1.revalidate(); rvt1.repaint(); } rvp1.revalidate(); rvp1.repaint(); if ( atmBAT.DynamicalBatteryDetails() ) { rvt2.revalidate(); rvt2.repaint(); } rvp1.revalidate(); rvp1.repaint(); } } ); } catch( Exception e1 ) { e1.printStackTrace(); } } }, 0, 500 ); // Initial delay=0, period=500 ms } // Buttons b1 = new JButton( "About" ); b2 = new JButton( "Report this" ); b3 = new JButton( "Report all" ); b4 = new JButton( "Cancel" ); downButtons = new JPanel(); BoxLayout boxx = new BoxLayout( downButtons, BoxLayout.X_AXIS ); downButtons.setLayout( boxx ); downButtons.add( Box.createHorizontalGlue()); // Left interval downButtons.add( b1 ); downButtons.add( Box.createHorizontalStrut( 2 ) ); // Interval between buttons downButtons.add( b2 ); downButtons.add( Box.createHorizontalStrut( 2 ) ); downButtons.add( b3 ); downButtons.add( Box.createHorizontalStrut( 2 ) ); downButtons.add( b4 ); downButtons.add( Box.createHorizontalGlue() ); // Right interval // Add listener for button #1: "About" b1.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent e ) { ActionAbout about = new ActionAbout(); final JDialog dialog = about.createDialog ( guiBox , About.getShortName() , About.getVendorName() ); dialog.setLocationRelativeTo( null ); dialog.setVisible( true ); }}); // Add listener for button #2: "Report this" (RT) b2.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent e ) { int i=rootMenu.getSelectedIndex(); ActionReport aReport = new ActionReport(); aReport.createDialogRT ( guiBox , reportTables1[i] , reportTables2[i] , // Table = f(tab) About.getShortName() , About.getVendorName() ); }}); // Add listener for button #3: "Report all" (RA) b3.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent e ) { ActionReport aReport = new ActionReport(); aReport.createDialogRF ( guiBox , reportTables1 , reportTables2 , // Tables for all tabs About.getShortName() , About.getVendorName() ); }}); // Add listener for button #4: "Cancel" b4.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent e ) { System.exit( 0 ); } } ); // Build Tabbed Panel rootMenu = new JTabbedPane(); for ( int i=0; i<rootPanels.length; i++ ) { // Add panels with names to JTabbedPane rootMenu.add( rootPanels[i] , panelsNames[i] ); } // Build GUI // SpringLayout putConstraint format (a,b,c,d) // a = positioned element size (NORTH, SOUTH, WEST, EAST) // b = positioned element name // c = distance from anchor element, can be positive or negative // d = anchor element guiBox = new GUIbox(About.getShortName()); SpringLayout sl = new SpringLayout(); Container c = guiBox.getContentPane(); c.setLayout(sl); sl.putConstraint (SpringLayout.NORTH, rootMenu, 1, SpringLayout.NORTH, c); sl.putConstraint (SpringLayout.SOUTH, rootMenu, -45, SpringLayout.SOUTH, c); sl.putConstraint (SpringLayout.WEST, rootMenu, 0, SpringLayout.WEST , c); sl.putConstraint (SpringLayout.EAST, rootMenu, 0, SpringLayout.EAST , c); sl.putConstraint (SpringLayout.NORTH, downButtons, 2, SpringLayout.SOUTH, rootMenu); sl.putConstraint (SpringLayout.SOUTH, downButtons, -1, SpringLayout.SOUTH, c); sl.putConstraint (SpringLayout.WEST, downButtons, 0, SpringLayout.WEST, c); sl.putConstraint (SpringLayout.EAST, downButtons, 0, SpringLayout.EAST, c); c.add(rootMenu); // add JTabbedPane c.add(downButtons); // add panel with buttons guiBox.setDefaultCloseOperation( EXIT_ON_CLOSE ); // discipline for close guiBox.setLocationRelativeTo( null ); // desktop centering option guiBox.setSize( X_SIZE, Y_SIZE ); // set size guiBox.setVisible( true ); // make GUI window visible } // end of main method } // end of class
package model; import java.util.Vector; /* * A CNFClause consists of a conjunction of CNFSubClauses * And each CNFSubClause in turn consists of a disjunction of Literals */ public class CNFClause { public Vector<CNFSubClause> theClauses = new Vector<CNFSubClause>(); public Vector<CNFSubClause> getSubclauses() { return theClauses; } public boolean contains(CNFSubClause newS) { for(int i = 0; i < theClauses.size(); i ++) { if(theClauses.get(i).getLiterals().equals(newS.getLiterals())) { return true; } } return false; } public static void printLinear(CNFClause expression){ int i = 0; System.out.println("---------"); for (CNFSubClause s: expression.getSubclauses()) { i++; if (expression.getSubclauses().size()==i) { s.printLinear(true); } else { s.printLinear(false); } } System.out.println("\n---------"); } public static String printReturnAsString(CNFClause expression){ int i = 0; String exp = ""; for (CNFSubClause s: expression.getSubclauses()) { i++; if (expression.getSubclauses().size()==i) { exp = exp + s.printReturnAsString(true); } else { exp = exp + s.printReturnAsString(false); } } return exp; } }
package retro; import com.javacambodia.retrofit2.wp.BasicPostVO; import com.javacambodia.retrofit2.wp.Post; import java.util.List; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Path; public interface PostServiceInterface { @GET("v2/posts") public Call<List<BasicPostVO>> getAllPost(); @GET("v2/posts/{id}") public Call<Post> getPost(@Path("id") int postId); }
package com.emp.rest.controllers; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.emp.rest.entity.Employee; import com.emp.rest.service.EmployeeService; @CrossOrigin(origins = "http://localhost:4200") @RestController @RequestMapping("/api") public class EmployeeRestController { private EmployeeService employeeService; @Autowired public EmployeeRestController(EmployeeService theEmployeeService) { employeeService = theEmployeeService; } // expose "/employees" and return list of employees @GetMapping("/emp/{username}/list") public List<Employee> findAll(@PathVariable String username) { return employeeService.findAll(); } // add mapping for GET @GetMapping("/emp/{username}/{employeeId}") public Employee getEmployee(@PathVariable String username,@PathVariable int employeeId) { Employee theEmployee = employeeService.findById(employeeId); if (theEmployee == null) { throw new RuntimeException("Employee id not found - " + employeeId); } return theEmployee; } // add mapping for POST /employees - add new employee @PostMapping("/emp/{username}") public Employee addEmployee(@PathVariable String username,@RequestBody Employee theEmployee) { theEmployee.setGender(theEmployee.getGender().equals("M")?"Male":"Female"); theEmployee.setEmpId(null); employeeService.save(theEmployee); return theEmployee; } // add mapping for PUT /employees - update existing employee @PutMapping("/emp/{username}") public Employee updateEmployee(@PathVariable String username,@RequestBody Employee theEmployee) { employeeService.save(theEmployee); return theEmployee; } // add mapping for DELETE /employees/{employeeId} - delete employee @DeleteMapping("/emp/{username}/{employeeId}") public ResponseEntity<Void> deleteEmployee(@PathVariable String username,@PathVariable int employeeId) { Employee tempEmployee = employeeService.findById(employeeId); // throw exception if null if (tempEmployee == null) { throw new RuntimeException("Employee id not found - " + employeeId); } employeeService.deleteById(employeeId); return ResponseEntity.noContent().build(); } }
/** * @Title: WorkflowExternalMain.java * @Package com.wonders.task.workflowExternal.main * @Description: TODO(用一句话描述该文件做什么) * @author zhoushun * @date 2014年7月1日 下午3:16:45 * @version V1.0 */ package com.wonders.task.workflowExternal.main; import java.io.StringWriter; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.wonders.schedule.util.SpringBeanUtil; import com.wonders.service.util.ServiceClient; import com.wonders.task.sample.ITaskService; import com.wonders.task.workflowExternal.model.bo.ReviewBo; import com.wonders.task.workflowExternal.model.vo.ApproveVo; import com.wonders.task.workflowExternal.model.vo.ApproveVoList; import com.wonders.task.workflowExternal.model.vo.ProcessInfoVo; import com.wonders.task.workflowExternal.model.vo.RegisterVo; import com.wonders.task.workflowExternal.model.vo.ReviewVo; import com.wonders.task.workflowExternal.model.xml.ReviewInfoXml; import com.wonders.task.workflowExternal.service.ExternalNewService; import com.wonders.task.workflowExternal.service.ExternalOldService; /** * @ClassName: WorkflowExternalMain * @Description: TODO(这里用一句话描述这个类的作用) * @author zhoushun * @date 2014年7月1日 下午3:16:45 * */ @Transactional(value = "txManager2",propagation = Propagation.REQUIRED, rollbackFor = Exception.class) @Service("workflowExternalMain") public class WorkflowExternalMain implements ITaskService{ @Autowired private ExternalOldService oldService; @Autowired private ExternalNewService newService; /** * @Title: exec * @Description: TODO(这里用一句话描述这个方法的作用) * @param @param param * @param @return 设定文件 * @throws */ @Override public String exec(String param) { List<ProcessInfoVo> list = oldService.getInfo(); String xmlStr = null; for(ProcessInfoVo vo : list){ ReviewInfoXml xml = new ReviewInfoXml(); ReviewVo a = this.oldService.getMainBo(vo.getProcess(), vo.getIncident()); RegisterVo b = this.newService.getInfo(vo.getLoginName()); if(b!=null){ b.setProcessName(vo.getProcess());b.setIncidentNo(vo.getIncident()); b.setStepName(vo.getStepName()); } List<ApproveVo> c = this.oldService.getApproveInfo(vo.getProcess(), vo.getIncident()); if(a!=null && b!=null && c!=null && c.size() > 0){ xml.registerVo = b; xml.mainBo = a; ApproveVoList d = new ApproveVoList(); d.list = c; xml.approveVo = d; service(xml,a.getContractType1()); } } return ""; } public void service(ReviewInfoXml xml,String type){ String xmlStr = null; if("建设类".equals(type)){ xmlStr = getResult(xml,"greataContractReview"); ServiceClient.setDataInfo("greata", "greata2013!", xmlStr); }else if("运维类".equals(type)){ xmlStr = getResult(xml,"eamContractReview"); ServiceClient.setDataInfo("eam", "eam2013!", xmlStr); } } public String getResult(ReviewInfoXml xml,String type){ String toDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date()); String result = ""; try { JAXBContext context = JAXBContext.newInstance(xml.getClass()); Marshaller m; m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8"); StringWriter sw = new StringWriter(); m.marshal(xml, sw); result = sw.toString().replace("<root>", "<root type=\""+type+"\" date=\""+toDate+"\">"); System.out.println(result); } catch (JAXBException e) { // TODO Auto-generated catch block e.printStackTrace(); } return result; } public static void main(String[] args){ ApplicationContext applicationContext = null; String[] fileUrl = new String[]{"classpath*:*Context*.xml"}; applicationContext = new ClassPathXmlApplicationContext(fileUrl); ITaskService task = (ITaskService) SpringBeanUtil.getBean("workflowExternalMain"); task.exec("5"); } }
package Selinium; public class Q17adding { public static void main(String[] args) { /* int array[] = {1,2,3,4,5}; int sum= 0; for(int i=0;i<array.length;i++) { if(array[i]%2==0) sum+=array[i]*array[i]; else sum +=array[i]*array[i]*array[i]; } System.out.println(sum); }*/ int num=125; int sum=0; int temp; while(num>0) { //Actual number 125 temp=num%10;//last digit ex--5 num=num/10; // remanning digit ex--12 sum=sum+(temp*temp); } System.out.println(sum); } }
package hl.restauth.auth.userbase; import org.json.JSONObject; import hl.restauth.auth.JsonUser; public interface IUserBase { public JsonUser getUser(String aUserID) throws Exception; public String getConfigKey(); public JSONObject getJsonConfig(); }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package loc.daos; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; import java.util.Random; import loc.db.DBConnection; import loc.dtos.ArticleDTO; /** * * @author hi */ public class ArticleDAO { private Connection conn = null; private PreparedStatement pre = null; private ResultSet rs = null; public ArticleDAO() { } public void closeConnection() throws Exception { if (rs != null) { rs.close(); } if (pre != null) { pre.close(); } if (conn != null) { conn.close(); } } public String getArticleID() throws Exception { String result = null; try { String sql = "SELECT COUNT(postID)+1 as Count From tblArticle"; conn = DBConnection.getMyConnection(); pre = conn.prepareStatement(sql); rs = pre.executeQuery(); if (rs.next()) { result = rs.getString("Count"); } } catch (Exception e) { } finally { closeConnection(); } return result; } public List<ArticleDTO> searchArticle(String search, int pageIndex, int pageSize) throws Exception { List<ArticleDTO> list = null; try { String sql = "exec SP_PhanNhuLoc_TestPaging ?,?,?,?,?,?"; conn = DBConnection.getMyConnection(); pre = conn.prepareStatement(sql); pre.setInt(1, pageIndex); pre.setInt(2, pageSize); pre.setString(3, "%" + search + "%"); pre.setString(4, "%" + search + "%"); pre.setString(5, "%" + search + "%"); pre.setString(6, "%" + search + "%"); rs = pre.executeQuery(); list = new ArrayList<ArticleDTO>(); while (rs.next()) { String postID = rs.getString("postID"); String image = rs.getString("image"); String title = rs.getString("title"); String email = rs.getString("email"); String description = rs.getString("description"); int status = rs.getInt("status"); String date = rs.getString(7); list.add(new ArticleDTO(postID, image, title, email, description, date, status)); } } catch (Exception e) { } finally { closeConnection(); } return list; } public int countArticle(String search) throws Exception { int result = 0; try { String sql = "SELECT COUNT(postID) as number FROM tblArticle WHERE (title LIKE ? OR email LIKE ? OR description LIKE ? OR date LIKE ?) AND status != 0"; conn = DBConnection.getMyConnection(); pre = conn.prepareStatement(sql); pre.setString(1, "%" + search + "%"); pre.setString(2, "%" + search + "%"); pre.setString(3, "%" + search + "%"); pre.setString(4, "%" + search + "%"); rs = pre.executeQuery(); if (rs.next()) { result = rs.getInt("number"); } } catch (Exception e) { } finally { closeConnection(); } return result; } public ArticleDTO getArticle(String postID) throws Exception { ArticleDTO result = null; try { String sql = "SELECT image,title,email,description,status,Convert(varchar,date,0) FROM tblArticle WHERE postID = ? AND status != 2"; conn = DBConnection.getMyConnection(); pre = conn.prepareStatement(sql); pre.setString(1, postID); rs = pre.executeQuery(); while (rs.next()) { String image = rs.getString("image"); String title = rs.getString("title"); String email = rs.getString("email"); String description = rs.getString("description"); int status = rs.getInt("status"); String date = rs.getString(6); result = new ArticleDTO(postID, image, title, email, description, date, status); } } catch (Exception e) { } finally { closeConnection(); } return result; } public String randomID() throws Exception { StringBuilder buildString = new StringBuilder(); String alpha = "ABCDEFGHIJKLMNOBQRSTUVWSYZ123456789"; String id = ""; Random rand = new Random(); do { for (int i = 0; i < 5; i++) { int x = rand.nextInt(35) + 1; buildString.append(alpha.charAt(x)); } id = buildString.toString(); } while (checkPostIDExist(id) == true); closeConnection(); return id; } public boolean checkPostIDExist(String id) throws Exception { boolean result = false; try { String sql = "SELECT date FROM tblArticle WHERE postID = ?"; conn = DBConnection.getMyConnection(); pre = conn.prepareStatement(sql); pre.setString(1, id); rs = pre.executeQuery(); if (rs.next()) { result = true; } } catch (Exception e) { } finally { closeConnection(); } return result; } public boolean insertNewArticle(ArticleDTO dto) throws Exception { boolean result = false; try { String sql = "INSERT into tblArticle(postID,image,title,email,description,status,date) VALUES(?,?,?,?,?,1,GETDATE())"; conn = DBConnection.getMyConnection(); pre = conn.prepareStatement(sql); pre.setString(1, dto.getPostID()); pre.setString(2, dto.getImage()); pre.setString(3, dto.getTitle()); pre.setString(4, dto.getEmail()); pre.setString(5, dto.getDescription()); result = pre.executeUpdate() > 0; } catch (Exception e) { } finally { closeConnection(); } return result; } public boolean updateArticleStatus(String postID, String email) throws Exception { boolean result = false; try { String sql = "UPDATE tblArticle SET status = 0 WHERE postID = ? AND email = ?"; conn = DBConnection.getMyConnection(); pre = conn.prepareStatement(sql); pre.setString(1, postID); pre.setString(2, email); result = pre.executeUpdate() > 0; } catch (Exception e) { } finally { closeConnection(); } return result; } }
package com.shivam.writer; /* Implementation To Do : Shivam */ public class CSVFileWriter implements DataFileWriter{ @Override public void write() { } }
// // Diese Datei wurde mit der JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.7 generiert // Siehe <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Änderungen an dieser Datei gehen bei einer Neukompilierung des Quellschemas verloren. // Generiert: 2016.05.11 um 01:33:35 PM CEST // package com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import javax.xml.datatype.XMLGregorianCalendar; /** * <p>Java-Klasse für TransportInformationType complex type. * * <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist. * * <pre> * &lt;complexType name="TransportInformationType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;choice minOccurs="0"> * &lt;element name="TransportmittelBahn" type="{http://www-fls.thyssen.com/xml/schema/qcs}TransportmittelBahnType"/> * &lt;element name="TransportmittelLKW" type="{http://www-fls.thyssen.com/xml/schema/qcs}TransportmittelLKWType"/> * &lt;element name="TransportmittelSchiff" type="{http://www-fls.thyssen.com/xml/schema/qcs}TransportmittelSchiffType"/> * &lt;element name="TransportmittelIntern" type="{http://www-fls.thyssen.com/xml/schema/qcs}TransportmittelInternType"/> * &lt;/choice> * &lt;element name="HeissTransport" type="{http://www-fls.thyssen.com/xml/schema/qcs}HeissTransportType" minOccurs="0"/> * &lt;element name="LageAufTransportmittel" type="{http://www-fls.thyssen.com/xml/schema/qcs}LageAufTransportmittelType" minOccurs="0"/> * &lt;element name="TransportInfo" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="Torabfertigung" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/> * &lt;element name="ZeitpunktTorabfertigung" type="{http://www.w3.org/2001/XMLSchema}dateTime" minOccurs="0"/> * &lt;element name="TransportabrufStatus" type="{http://www-fls.thyssen.com/xml/schema/qcs}TransportabrufStatusEnum" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "TransportInformationType", propOrder = { "transportmittelBahn", "transportmittelLKW", "transportmittelSchiff", "transportmittelIntern", "heissTransport", "lageAufTransportmittel", "transportInfo", "torabfertigung", "zeitpunktTorabfertigung", "transportabrufStatus" }) public class TransportInformationType { @XmlElement(name = "TransportmittelBahn") protected TransportmittelBahnType transportmittelBahn; @XmlElement(name = "TransportmittelLKW") protected TransportmittelLKWType transportmittelLKW; @XmlElement(name = "TransportmittelSchiff") protected TransportmittelSchiffType transportmittelSchiff; @XmlElement(name = "TransportmittelIntern") protected TransportmittelInternType transportmittelIntern; @XmlElement(name = "HeissTransport") protected HeissTransportType heissTransport; @XmlElement(name = "LageAufTransportmittel") protected LageAufTransportmittelType lageAufTransportmittel; @XmlElement(name = "TransportInfo") protected String transportInfo; @XmlElement(name = "Torabfertigung") protected Boolean torabfertigung; @XmlElement(name = "ZeitpunktTorabfertigung") @XmlSchemaType(name = "dateTime") protected XMLGregorianCalendar zeitpunktTorabfertigung; @XmlElement(name = "TransportabrufStatus") protected TransportabrufStatusEnum transportabrufStatus; /** * Ruft den Wert der transportmittelBahn-Eigenschaft ab. * * @return * possible object is * {@link TransportmittelBahnType } * */ public TransportmittelBahnType getTransportmittelBahn() { return transportmittelBahn; } /** * Legt den Wert der transportmittelBahn-Eigenschaft fest. * * @param value * allowed object is * {@link TransportmittelBahnType } * */ public void setTransportmittelBahn(TransportmittelBahnType value) { this.transportmittelBahn = value; } /** * Ruft den Wert der transportmittelLKW-Eigenschaft ab. * * @return * possible object is * {@link TransportmittelLKWType } * */ public TransportmittelLKWType getTransportmittelLKW() { return transportmittelLKW; } /** * Legt den Wert der transportmittelLKW-Eigenschaft fest. * * @param value * allowed object is * {@link TransportmittelLKWType } * */ public void setTransportmittelLKW(TransportmittelLKWType value) { this.transportmittelLKW = value; } /** * Ruft den Wert der transportmittelSchiff-Eigenschaft ab. * * @return * possible object is * {@link TransportmittelSchiffType } * */ public TransportmittelSchiffType getTransportmittelSchiff() { return transportmittelSchiff; } /** * Legt den Wert der transportmittelSchiff-Eigenschaft fest. * * @param value * allowed object is * {@link TransportmittelSchiffType } * */ public void setTransportmittelSchiff(TransportmittelSchiffType value) { this.transportmittelSchiff = value; } /** * Ruft den Wert der transportmittelIntern-Eigenschaft ab. * * @return * possible object is * {@link TransportmittelInternType } * */ public TransportmittelInternType getTransportmittelIntern() { return transportmittelIntern; } /** * Legt den Wert der transportmittelIntern-Eigenschaft fest. * * @param value * allowed object is * {@link TransportmittelInternType } * */ public void setTransportmittelIntern(TransportmittelInternType value) { this.transportmittelIntern = value; } /** * Ruft den Wert der heissTransport-Eigenschaft ab. * * @return * possible object is * {@link HeissTransportType } * */ public HeissTransportType getHeissTransport() { return heissTransport; } /** * Legt den Wert der heissTransport-Eigenschaft fest. * * @param value * allowed object is * {@link HeissTransportType } * */ public void setHeissTransport(HeissTransportType value) { this.heissTransport = value; } /** * Ruft den Wert der lageAufTransportmittel-Eigenschaft ab. * * @return * possible object is * {@link LageAufTransportmittelType } * */ public LageAufTransportmittelType getLageAufTransportmittel() { return lageAufTransportmittel; } /** * Legt den Wert der lageAufTransportmittel-Eigenschaft fest. * * @param value * allowed object is * {@link LageAufTransportmittelType } * */ public void setLageAufTransportmittel(LageAufTransportmittelType value) { this.lageAufTransportmittel = value; } /** * Ruft den Wert der transportInfo-Eigenschaft ab. * * @return * possible object is * {@link String } * */ public String getTransportInfo() { return transportInfo; } /** * Legt den Wert der transportInfo-Eigenschaft fest. * * @param value * allowed object is * {@link String } * */ public void setTransportInfo(String value) { this.transportInfo = value; } /** * Ruft den Wert der torabfertigung-Eigenschaft ab. * * @return * possible object is * {@link Boolean } * */ public Boolean isTorabfertigung() { return torabfertigung; } /** * Legt den Wert der torabfertigung-Eigenschaft fest. * * @param value * allowed object is * {@link Boolean } * */ public void setTorabfertigung(Boolean value) { this.torabfertigung = value; } /** * Ruft den Wert der zeitpunktTorabfertigung-Eigenschaft ab. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getZeitpunktTorabfertigung() { return zeitpunktTorabfertigung; } /** * Legt den Wert der zeitpunktTorabfertigung-Eigenschaft fest. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setZeitpunktTorabfertigung(XMLGregorianCalendar value) { this.zeitpunktTorabfertigung = value; } /** * Ruft den Wert der transportabrufStatus-Eigenschaft ab. * * @return * possible object is * {@link TransportabrufStatusEnum } * */ public TransportabrufStatusEnum getTransportabrufStatus() { return transportabrufStatus; } /** * Legt den Wert der transportabrufStatus-Eigenschaft fest. * * @param value * allowed object is * {@link TransportabrufStatusEnum } * */ public void setTransportabrufStatus(TransportabrufStatusEnum value) { this.transportabrufStatus = value; } }
package sample; import constants.ApplicationConstants; import helper.CategoryParser; import helper.Utility; import javafx.event.ActionEvent; import javafx.event.Event; import javafx.scene.control.*; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.MenuItem; import javafx.scene.control.TextField; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.paint.Color; import javafx.scene.text.FontWeight; import model.Category; import model.Word; import java.io.IOException; import java.util.Random; public class Controller { public MenuItem mnuItemChangeCategories; public TextField txtFieldUsername; public PasswordField passwordFieldPPWD; public Button btnLogin; public TabPane tabPane; public Tab tabPlay; public Tab tabLogin; public Label lblUsername; public Label lblPassword; public Tab tabCategories; public TextField txtFieldsCategoryName; public Button btnAddCategory; public ComboBox comboboxCategories; public TextField txtWordOrLetter; public Button btnPlay; public TextField txtWord2Guess; public ComboBox comboboxCategory; public Button btnHint; public Label lblHint; public Label lblWordTabCategory; public TextField txtFieldNewWord; public TextField txtFieldNewHint; public Button btnAddWord; public Label lblCategoryNameCombobox; public CheckBox chckBoxCleanWords; public ComboBox comboboxSelectCategoryPlay; public TextField txtFieldGuess; public Button btnGuess; public void initialize() { tabPane.getTabs().remove(tabLogin); tabPane.getTabs().remove(tabCategories); } public void loginAction(ActionEvent actionEvent) { if (btnLogin.getText().equals(ApplicationConstants.BTN_LOGIN_TEXT)) { //correct username and password if (txtFieldUsername.getText().equals(ApplicationConstants.APP_USERNAME) && passwordFieldPPWD.getText().equals(ApplicationConstants.APP_PASSWORD)) { btnLogin.setText(ApplicationConstants.BTN_LOGOUT_TEXT); lblPassword.setTextFill(Color.WHITE); lblUsername.setTextFill(Color.WHITE); // add tab categories tabPane.getTabs().add(tabCategories); //activate tab categories tabPane.getSelectionModel().select(tabCategories); //do not allow anymore to edit text field user name and password field txtFieldUsername.setEditable(false); passwordFieldPPWD.setEditable(false); // decorate text field with other font txtFieldUsername.setFont(javafx.scene.text.Font.font("Verdana", FontWeight.EXTRA_BOLD, 12)); //incorrect username and password } else { lblPassword.setTextFill(Color.RED); lblUsername.setTextFill(Color.RED); } // button has text logout } else { // allow to edit text field username and password field and clear the text txtFieldUsername.setEditable(true); passwordFieldPPWD.setEditable(true); txtFieldUsername.clear(); passwordFieldPPWD.clear(); btnLogin.setText(ApplicationConstants.BTN_LOGIN_TEXT); tabPane.getSelectionModel().select(tabPlay); tabPane.getTabs().remove(tabLogin); tabPane.getTabs().remove(tabCategories); } } public void activateLoginTab(ActionEvent actionEvent) { tabPane.getTabs().add(tabLogin); tabPane.getSelectionModel().select(tabLogin); } public void loginEnterKey(KeyEvent keyEvent) { if (keyEvent.getCode().equals(KeyCode.ENTER)) { loginAction(null); } } public void addCategory(ActionEvent actionEvent) { if (!txtFieldsCategoryName.getText().isEmpty()) { Utility.createCategoryFile(txtFieldsCategoryName.getText()); } Utility.listFilesWithoutExtensionFromPath(ApplicationConstants.APP_FOLDER_DATA_PATH + "\\" + ApplicationConstants.CATEGORY_FOLDER_NAME); fillCategoryCombobox(null); comboboxCategories.getSelectionModel().select(txtFieldsCategoryName.getText()); txtFieldsCategoryName.clear(); } public void fillCategoryCombobox(Event event) { if (tabPlay.isSelected()) { updateCombobox(comboboxSelectCategoryPlay); } else if (tabCategories.isSelected()) { updateCombobox(comboboxCategories); } } private void updateCombobox(ComboBox comboboxCategories) { comboboxCategories.getItems().clear(); try { comboboxCategories.getItems().addAll(Utility.listFilesWithoutExtensionFromPath(ApplicationConstants.APP_FOLDER_DATA_PATH + "\\" + ApplicationConstants.CATEGORY_FOLDER_NAME)); }catch (Exception e) { } } public void handleAddWord(ActionEvent event) { boolean chkBoxCleanActive = chckBoxCleanWords.isSelected(); //region combobox category if (comboboxCategories.getSelectionModel().getSelectedIndex() == -1) { lblCategoryNameCombobox.setTextFill(Color.RED); } else { lblCategoryNameCombobox.setTextFill(Color.WHITE); // region Text field new word if (!txtFieldNewWord.getText().isEmpty()) { lblWordTabCategory.setTextFill(Color.WHITE); try { Category category = CategoryParser.parseCategoryFile(chkBoxCleanActive, ApplicationConstants.APP_FOLDER_DATA_PATH + "\\" + ApplicationConstants.CATEGORY_FOLDER_NAME + "\\" + comboboxCategories.getSelectionModel().getSelectedItem().toString() + ApplicationConstants.CATEGORY_FILE_EXTENSION); //word already exists if if (category.wordExists(txtFieldNewWord.getText())) { lblWordTabCategory.setTextFill(Color.RED); } // else word does not exist else { if (chkBoxCleanActive) { Utility.cleanWordsInCategory(category.getWordList(), comboboxCategories.getSelectionModel().getSelectedItem().toString()); lblWordTabCategory.setTextFill(Color.WHITE);} Utility.addWordInCategory(category.getLastIdOfWord() + 1, txtFieldNewWord.getText(), txtFieldNewHint.getText(), comboboxCategories.getSelectionModel().getSelectedItem().toString()); comboboxCategories.getSelectionModel().select(-1); txtFieldNewWord.clear(); txtFieldNewHint.clear(); } } catch(IOException e){ e.printStackTrace(); System.out.println(e.getMessage()); } } else{ lblWordTabCategory.setTextFill(Color.RED); } //endregion } //endregion } Word wordToGuess; String secretWord; public void handlePlay(ActionEvent event) { try { Category category = CategoryParser.parseCategoryFile(false, ApplicationConstants.APP_FOLDER_DATA_PATH + "\\" + ApplicationConstants.CATEGORY_FOLDER_NAME + "\\" + comboboxSelectCategoryPlay.getSelectionModel().getSelectedItem().toString() + ApplicationConstants.CATEGORY_FILE_EXTENSION); Random rand = new Random(); int randomNumber = rand.nextInt(category.getLastIdOfWord()); wordToGuess = category.getWordList().get(randomNumber); for (int i = 0; i <wordToGuess.getName().length(); i++){ if(wordToGuess.getName().charAt(i)!= ' '){ secretWord += "_"; } } txtWord2Guess.setText(secretWord); } catch (Exception ex) { } } public void handleGuess(ActionEvent event) { StringBuilder sb = new StringBuilder(secretWord); if(wordToGuess.getName().contains(txtFieldGuess.getText())) { for (int i = 0; i < wordToGuess.getName().length(); i++) if (wordToGuess.getName().charAt(i) == txtFieldGuess.getText().toCharArray()[0]) { sb.setCharAt(i, txtFieldGuess.getText().toCharArray()[0]); } else { secretWord += " "; } } secretWord += sb.toString(); txtWord2Guess.setText(secretWord); } }
package com.bw.movie.mvp.view.apdater; import android.content.Context; import android.content.SharedPreferences; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.bumptech.glide.Glide; import com.bw.movie.IView.IUnAttenCinemaView; import com.bw.movie.R; import com.bw.movie.mvp.model.bean.AttenCinemaBean; import com.bw.movie.mvp.model.bean.AttenMovieBean; import com.bw.movie.mvp.present.UnAttenCinemaPresent; import java.util.List; /** * 作者:轻 on 2018/11/21 11:43 * <p> * 邮箱:379996854@qq.com */ public class AttenCinemaApdater extends RecyclerView.Adapter<MyRexommwnViewHoder> implements IUnAttenCinemaView { Context context; List<AttenCinemaBean.ResultBean> list; private boolean followCinema; private SharedPreferences user; private boolean isLogin; private UnAttenCinemaPresent unAttenCinemaPresent; private int id; public AttenCinemaApdater(Context context, List<AttenCinemaBean.ResultBean> list) { this.context = context; this.list = list; } @NonNull @Override public MyRexommwnViewHoder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { MyRexommwnViewHoder hoder = new MyRexommwnViewHoder(LayoutInflater.from(context).inflate(R.layout.rexommend_item,parent,false)); initView(); return hoder; } @Override public void onBindViewHolder(@NonNull final MyRexommwnViewHoder holder, int position) { Glide.with(context).load(list.get(position).getLogo()).into(holder.ivRxImage); holder.tvReName.setText(list.get(position).getName()); holder.tvRxTitle.setText(list.get(position).getAddress()); //holder.tvNearJuli.setText(list.get(position).get+"km"); id = list.get(position).getId(); AttenCinemaBean.ResultBean bean = list.get(position); followCinema = bean.isFollowCinema(); user = context.getSharedPreferences("user", Context.MODE_PRIVATE); isLogin = user.getBoolean("isLogin", true); holder.ivRxGuanzhu.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (v == holder.ivRxGuanzhu) { if (followCinema) { Toast.makeText(context, "已经关注", Toast.LENGTH_SHORT).show(); } else { /* holder.ivNearGuanzhu.setImageResource(R.drawable.guanzhu1); attenCinemaPresent.getAttenCinema(id);*/ holder.ivRxGuanzhu.setImageResource(R.drawable.guanzhu); unAttenCinemaPresent.getUnAttenCinema(id); } followCinema = !followCinema; } } }); //notifyDataSetChanged(); } private void initView() { //取消关注 unAttenCinemaPresent = new UnAttenCinemaPresent(this); } @Override public int getItemCount() { return list.size(); } //取消关注 @Override public void success(AttenMovieBean attenMovieBean) { Log.i("success", "success: ====="+attenMovieBean.getMessage()); } @Override public void Error(String msg) { } }
package com.company; import java.util.LinkedList; import java.util.ListIterator; import ibadts.Queue; import ibadts.Stack; import ibadts.StaticQueue; import java.util.Scanner; public class Main { public static void main(String[] args) { QueueCoSc.hw4(); } }
package com.example.demo.entity; import javax.persistence.*; @Entity @Table(name = "team_history_test") public class TeamHistoryTest { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @OneToOne private TeamTest teamTest; private String name; public TeamHistoryTest() { } public TeamHistoryTest(TeamTest teamTest, String name) { this.teamTest = teamTest; this.name = name; } public Long getId() { return id; } public TeamTest getTeamTest() { return teamTest; } public String getName() { return name; } }
import java.sql.*; import java.util.ArrayList; public class MySQL { private Connection connection; private Statement statement; private ResultSet resultSet; private String url = "jdbc:mysql://localhost:3306/"; private String user = "root", pass = ""; private String db_table = "dictionary", db = "datair"; public MySQL() throws ClassNotFoundException, SQLException { Class.forName("com.mysql.cj.jdbc.Driver"); connection = DriverManager.getConnection(url + db, user, pass); statement = connection.createStatement(); //getData(); } private void getData() throws SQLException { DatabaseMetaData dbmd = connection.getMetaData(); String dbName = dbmd.getDatabaseProductName(); String dbVersion = dbmd.getDatabaseProductVersion(); String dbUrl = dbmd.getURL(); String userName = dbmd.getUserName(); String driverName = dbmd.getDriverName(); System.out.println("Database Name is " + dbName); System.out.println("Database Version is " + dbVersion); System.out.println("Database Connection Url is " + dbUrl); System.out.println("Database User Name is " + userName); System.out.println("Database Driver Name is " + driverName); } public Words getWordsFlowEnglish(String sentence) throws SQLException { Words words = new Words(); ResultSet resultSet = statement.executeQuery( "SELECT * FROM " + db_table + " WHERE word = '" + sentence + "'"); while (resultSet.next()) { words.setId( resultSet.getString(1)); words.setWord( resultSet.getString(2)); words.setType( resultSet.getString(3)); words.setMean( resultSet.getString(4)); words.setExemple( resultSet.getString(5)); words.setMean_exemple( resultSet.getString(6)); } return words; } public Words getWordsFlowVietNam(String sentence) throws SQLException { Words words = new Words(); ResultSet resultSet = statement.executeQuery( "SELECT * FROM " + db_table + " WHERE mean = '" + sentence + "'"); while (resultSet.next()) { words.setId( resultSet.getString(1)); words.setWord( resultSet.getString(2)); words.setType( resultSet.getString(3)); words.setMean( resultSet.getString(4)); words.setExemple( resultSet.getString(5)); words.setMean_exemple( resultSet.getString(6)); } return words; } }
/** * Nguru Ian Davis * 15059844 */ public abstract class PayingPassenger extends Passenger implements Chargeable { private double baseFare; private double typeCharge; private final String FFC; /** * Constructor for the abstract class that will be used by concrete classes that inherit from it. */ public PayingPassenger(int passengerNumberStart, String fName, String lName, double w, double lugg, int typecharge, int basefare, String ffc) { super(passengerNumberStart, fName, lName, w, lugg); baseFare = basefare; typeCharge = typecharge; FFC = "FF" + ffc; } /** * Method to calculate the passengers fare for the flight */ public double getCharge() { double fare = baseFare + (super.getWeight() * typeCharge); return fare; } // /** // * Method to set the Frequent Flyer Code // */ // public String setFFC(String ffc) // { // // FFC = "FF" + ffc; // // } public String getFFC() { return FFC; } /** * toString method that prints out the the passenger's details */ @Override public String toString() { String string = super.toString(); return string + " Fare: £" + getCharge() + " Frequent Flyer Code: " + getFFC(); } }
package com.beiyelin.addressservice.controller; import com.beiyelin.addressservice.entity.Province; import com.beiyelin.addressservice.service.ProvinceService; import com.beiyelin.common.resbody.ResultBody; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; /** * @Description: * @Author: newmann * @Date: Created in 9:26 2018-02-25 */ @RestController @RequestMapping("/api/address/province") public class ProvinceController { public final static String PERMISSION_ADDRESS_PROVINCEMODULE_NAME="省市"; private ProvinceService provinceService; @Autowired public void setProvinceService(ProvinceService service){ this.provinceService = service; } @GetMapping("/find-all") public ResultBody<List<Province>> findAll(){ return new ResultBody<>(provinceService.findAll()); } @GetMapping("/find-by-countryid/{countryid}") public ResultBody<List<Province>> findByCountryId(@PathVariable("countryid") String countryId){ return new ResultBody<>(provinceService.findAllByCountryIdOrderByCode(countryId)); } }
package com.stem.core.task; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.stem.wechat.WeChat; /** * 描述:刷新accessToken<br/> * 作者:stem zhang <br/> * 修改日期:2015年9月2日 - 下午4:09:41<br/> * E-mail: sireezhang@163.com<br/> */ public class AccessTokenTask { private Logger logger = LoggerFactory.getLogger(getClass()); public void run(){ try{ String accessToken = WeChat.getAccessToken(); // AppContext.getContext().setSyncValue(AppContext.ACCESS_TOKEN_KEY,accessToken); logger.info("更新AccessToken成功,值被更新为["+accessToken+"]"); } catch (Exception e){ e.printStackTrace(); logger.warn("获取AccessToken异常:"+e.getMessage()); } } }
/** * OpenKM, Open Document Management System (http://www.openkm.com) * Copyright (c) 2006-2015 Paco Avila & Josep Llort * * No bytes were intentionally harmed during the development of this application. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package com.openkm.servlet.admin; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.sql.SQLException; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Properties; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileItemFactory; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.io.IOUtils; import org.artofsolving.jodconverter.office.OfficeUtils; import org.hibernate.Session; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.gson.Gson; import com.openkm.bean.ConfigStoredFile; import com.openkm.bean.ConfigStoredOption; import com.openkm.bean.ConfigStoredSelect; import com.openkm.core.DatabaseException; import com.openkm.core.MimeTypeConfig; import com.openkm.dao.ConfigDAO; import com.openkm.dao.HibernateUtil; import com.openkm.dao.bean.Config; import com.openkm.servlet.admin.DatabaseQueryServlet.WorkerUpdate; import com.openkm.util.FileUtils; import com.openkm.util.ImageUtils; import com.openkm.util.SecureStore; import com.openkm.util.UserActivity; import com.openkm.util.WarUtils; import com.openkm.util.WebUtils; /** * Execute config servlet */ public class ConfigServlet extends BaseServlet { private static final long serialVersionUID = 1L; private static Logger log = LoggerFactory.getLogger(ConfigServlet.class); private static Map<String, String> types = new LinkedHashMap<String, String>(); private static final String[][] breadcrumb = new String[][] { new String[] { "Config", "Configuration" }, }; static { types.put(Config.STRING, "String"); types.put(Config.TEXT, "Text"); types.put(Config.BOOLEAN, "Boolean"); types.put(Config.INTEGER, "Integer"); types.put(Config.LONG, "Long"); types.put(Config.FILE, "File"); types.put(Config.SELECT, "Select"); types.put(Config.LIST, "List"); } @Override public void service(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String method = request.getMethod(); if (checkMultipleInstancesAccess(request, response)) { if (method.equals(METHOD_GET)) { doGet(request, response); } else if (method.equals(METHOD_POST)) { doPost(request, response); } } } @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { log.debug("doGet({}, {})", request, response); request.setCharacterEncoding("UTF-8"); String action = WebUtils.getString(request, "action"); String filter = WebUtils.getString(request, "filter"); String userId = request.getRemoteUser(); updateSessionManager(request); try { if (action.equals("create")) { create(userId, types, request, response); } else if (action.equals("edit")) { edit(userId, types, request, response); } else if (action.equals("delete")) { delete(userId, types, request, response); } else if (action.equals("view")) { view(userId, request, response); } else if (action.equals("check")) { check(userId, request, response); } else if (action.equals("export")) { export(userId, request, response); } else { list(userId, filter, request, response); } } catch (DatabaseException e) { log.error(e.getMessage(), e); sendErrorRedirect(request, response, e); } } @Override @SuppressWarnings("unchecked") public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { log.debug("doPost({}, {})", request, response); request.setCharacterEncoding("UTF-8"); ServletContext sc = getServletContext(); String action = null; String filter = ""; String userId = request.getRemoteUser(); Session dbSession = null; updateSessionManager(request); try { if (ServletFileUpload.isMultipartContent(request)) { InputStream is = null; FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(request); ConfigStoredFile stFile = new ConfigStoredFile(); Config cfg = new Config(); byte data[] = null; for (Iterator<FileItem> it = items.iterator(); it.hasNext();) { FileItem item = it.next(); if (item.isFormField()) { if (item.getFieldName().equals("action")) { action = item.getString("UTF-8"); } else if (item.getFieldName().equals("filter")) { filter = item.getString("UTF-8"); } else if (item.getFieldName().equals("cfg_key")) { cfg.setKey(item.getString("UTF-8")); } else if (item.getFieldName().equals("cfg_type")) { cfg.setType(item.getString("UTF-8")); } else if (item.getFieldName().equals("cfg_value")) { cfg.setValue(item.getString("UTF-8").trim()); } } else { is = item.getInputStream(); stFile.setName(item.getName()); stFile.setMime(MimeTypeConfig.mimeTypes.getContentType(item.getName())); if (cfg.getKey() != null && cfg.getKey().startsWith("logo")) { String size = null; if (cfg.getKey().equals(com.openkm.core.Config.PROPERTY_LOGO_LOGIN)) { size = "316x74>"; } else if (cfg.getKey().equals(com.openkm.core.Config.PROPERTY_LOGO_REPORT)) { size = "150x35>"; } File tmpIn = FileUtils.createTempFileFromMime(stFile.getMime()); File tmpOut = FileUtils.createTempFileFromMime(stFile.getMime()); FileOutputStream fos = null; try { fos = new FileOutputStream(tmpIn); IOUtils.copy(is, fos); ImageUtils.resize(tmpIn, size, tmpOut); data = FileUtils.readFileToByteArray(tmpOut); } finally { FileUtils.deleteQuietly(tmpIn); FileUtils.deleteQuietly(tmpOut); IOUtils.closeQuietly(fos); IOUtils.closeQuietly(is); } } else { data = IOUtils.toByteArray(is); IOUtils.closeQuietly(is); } stFile.setContent(SecureStore.b64Encode(data)); } } if (action.equals("create")) { if (Config.FILE.equals(cfg.getType())) { cfg.setValue(new Gson().toJson(stFile)); } else if (Config.BOOLEAN.equals(cfg.getType())) { cfg.setValue(Boolean.toString(cfg.getValue() != null && !cfg.getValue().equals(""))); } else if (Config.SELECT.equals(cfg.getType())) { ConfigStoredSelect stSelect = ConfigDAO.getSelect(cfg.getKey()); if (stSelect != null) { for (ConfigStoredOption stOption : stSelect.getOptions()) { if (stOption.getValue().equals(cfg.getValue())) { stOption.setSelected(true); } } } cfg.setValue(new Gson().toJson(stSelect)); } ConfigDAO.create(cfg); com.openkm.core.Config.reload(sc, new Properties()); // Activity log UserActivity.log(userId, "ADMIN_CONFIG_CREATE", cfg.getKey(), null, cfg.toString()); list(userId, filter, request, response); } else if (action.equals("edit")) { if (Config.FILE.equals(cfg.getType())) { cfg.setValue(new Gson().toJson(stFile)); } else if (Config.BOOLEAN.equals(cfg.getType())) { cfg.setValue(Boolean.toString(cfg.getValue() != null && !cfg.getValue().equals(""))); } else if (Config.SELECT.equals(cfg.getType())) { ConfigStoredSelect stSelect = ConfigDAO.getSelect(cfg.getKey()); if (stSelect != null) { for (ConfigStoredOption stOption : stSelect.getOptions()) { if (stOption.getValue().equals(cfg.getValue())) { stOption.setSelected(true); } else { stOption.setSelected(false); } } } cfg.setValue(new Gson().toJson(stSelect)); } ConfigDAO.update(cfg); com.openkm.core.Config.reload(sc, new Properties()); // Activity log UserActivity.log(userId, "ADMIN_CONFIG_EDIT", cfg.getKey(), null, cfg.toString()); list(userId, filter, request, response); } else if (action.equals("delete")) { ConfigDAO.delete(cfg.getKey()); com.openkm.core.Config.reload(sc, new Properties()); // Activity log UserActivity.log(userId, "ADMIN_CONFIG_DELETE", cfg.getKey(), null, null); list(userId, filter, request, response); } else if (action.equals("import")) { dbSession = HibernateUtil.getSessionFactory().openSession(); importConfig(userId, request, response, data, dbSession); // Activity log UserActivity.log(request.getRemoteUser(), "ADMIN_CONFIG_IMPORT", null, null, null); list(userId, filter, request, response); } } } catch (DatabaseException e) { log.error(e.getMessage(), e); sendErrorRedirect(request, response, e); } catch (FileUploadException e) { log.error(e.getMessage(), e); sendErrorRedirect(request,response, e); } catch (SQLException e) { log.error(e.getMessage(), e); sendErrorRedirect(request,response, e); } finally { HibernateUtil.close(dbSession); } } /** * Create config */ private void create(String userId, Map<String, String> types, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, DatabaseException { ServletContext sc = getServletContext(); Config cfg = new Config(); sc.setAttribute("action", WebUtils.getString(request, "action")); sc.setAttribute("filter", WebUtils.getString(request, "filter")); sc.setAttribute("persist", true); sc.setAttribute("types", types); sc.setAttribute("cfg", cfg); sc.getRequestDispatcher("/admin/config_edit.jsp").forward(request, response); } /** * Edit config */ private void edit(String userId, Map<String, String> types, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, DatabaseException { ServletContext sc = getServletContext(); String cfgKey = WebUtils.getString(request, "cfg_key"); Config cfg = ConfigDAO.findByPk(cfgKey); sc.setAttribute("action", WebUtils.getString(request, "action")); sc.setAttribute("filter", WebUtils.getString(request, "filter")); sc.setAttribute("persist", true); sc.setAttribute("types", types); sc.setAttribute("cfg", cfg); sc.getRequestDispatcher("/admin/config_edit.jsp").forward(request, response); } /** * Delete config */ private void delete(String userId, Map<String, String> types, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, DatabaseException { ServletContext sc = getServletContext(); String cfgKey = WebUtils.getString(request, "cfg_key"); Config cfg = ConfigDAO.findByPk(cfgKey); sc.setAttribute("action", WebUtils.getString(request, "action")); sc.setAttribute("filter", WebUtils.getString(request, "filter")); sc.setAttribute("persist", true); sc.setAttribute("types", types); sc.setAttribute("cfg", cfg); sc.getRequestDispatcher("/admin/config_edit.jsp").forward(request, response); } /** * List config */ private void list(String userId, String filter, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, DatabaseException { log.debug("list({}, {}, {}, {})", new Object[] { userId, filter, request, response }); ServletContext sc = getServletContext(); List<Config> list = ConfigDAO.findAll(); for (Iterator<Config> it = list.iterator(); it.hasNext(); ) { Config cfg = it.next(); if (Config.STRING.equals(cfg.getType())) { cfg.setType("String"); } else if (Config.TEXT.equals(cfg.getType())) { cfg.setType("Text"); } else if (Config.BOOLEAN.equals(cfg.getType())) { cfg.setType("Boolean"); } else if (Config.INTEGER.equals(cfg.getType())) { cfg.setType("Integer"); } else if (Config.LONG.equals(cfg.getType())) { cfg.setType("Long"); } else if (Config.FILE.equals(cfg.getType())) { cfg.setType("File"); } else if (Config.LIST.equals(cfg.getType())) { cfg.setType("List"); } else if (Config.SELECT.equals(cfg.getType())) { cfg.setType("Select"); ConfigStoredSelect stSelect = new Gson().fromJson(cfg.getValue(), ConfigStoredSelect.class); for (ConfigStoredOption stOption : stSelect.getOptions()) { if (stOption.isSelected()) { cfg.setValue(stOption.getValue()); } } } else if (Config.HIDDEN.equals(cfg.getType())) { it.remove(); } if (!Config.HIDDEN.equals(cfg.getType()) && !cfg.getKey().contains(filter)) { it.remove(); } } sc.setAttribute("configs", list); sc.setAttribute("filter", filter); sc.getRequestDispatcher("/admin/config_list.jsp").forward(request, response); log.debug("list: void"); } /** * Download file */ private void view(String userId, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, DatabaseException { log.debug("view({}, {}, {})", new Object[] { userId, request, response }); String cfgKey = WebUtils.getString(request, "cfg_key"); Config cfg = ConfigDAO.findByPk(cfgKey); if (cfg != null) { ConfigStoredFile stFile = new Gson().fromJson(cfg.getValue(), ConfigStoredFile.class); byte[] content = SecureStore.b64Decode(stFile.getContent()); ByteArrayInputStream bais = new ByteArrayInputStream(content); WebUtils.sendFile(request, response, stFile.getName(), stFile.getMime(), true, bais); } log.debug("view: void"); } /** * Check configuration */ private void check(String userId, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, DatabaseException { log.debug("check({}, {}, {})", new Object[] { userId, request, response }); PrintWriter out = response.getWriter(); response.setContentType(MimeTypeConfig.MIME_HTML); header(out, "Configuration check", breadcrumb); out.flush(); try { out.println("<ul>"); out.print("<li>"); out.print("<b>" + com.openkm.core.Config.PROPERTY_SYSTEM_SWFTOOLS_PDF2SWF + "</b>"); checkExecutable(out, com.openkm.core.Config.SYSTEM_SWFTOOLS_PDF2SWF); out.print("</li>"); out.print("<li>"); out.print("<b>" + com.openkm.core.Config.PROPERTY_SYSTEM_IMAGEMAGICK_CONVERT + "</b>"); checkExecutable(out, com.openkm.core.Config.SYSTEM_IMAGEMAGICK_CONVERT); out.print("</li>"); out.print("<li>"); out.print("<b>" + com.openkm.core.Config.PROPERTY_SYSTEM_OCR + "</b>"); checkExecutable(out, com.openkm.core.Config.SYSTEM_OCR); out.print("</li>"); out.print("<li>"); out.print("<b>" + com.openkm.core.Config.PROPERTY_SYSTEM_OPENOFFICE_PATH + "</b>"); checkOpenOffice(out, com.openkm.core.Config.SYSTEM_OPENOFFICE_PATH); out.print("</li>"); out.println("</ul>"); out.flush(); } catch (Exception e) { out.println("<div class=\"warn\">Exception: "+e.getMessage()+"</div>"); out.flush(); } finally { footer(out); out.flush(); out.close(); } log.debug("check: void"); } /** * File existence and if can be executed */ private void checkExecutable(PrintWriter out, String cmd) { if (cmd.equals("")) { warn(out, "Not configured"); } else { int idx = cmd.indexOf(" "); String exec = null; if (idx > -1) { exec = cmd.substring(0, idx); } else { exec = cmd; } File prg = new File(exec); if (prg.exists() && prg.canRead() && prg.canExecute()) { ok(out, "OK - " + prg.getPath()); } else { warn(out, "Can't read or execute: " + prg.getPath()); } } } /** * File existence and if can be executed */ private void checkOpenOffice(PrintWriter out, String path) { if (path.equals("")) { warn(out, "Not configured"); } else { File prg = new File(path); if (prg.exists() && prg.canRead()) { File offExec = OfficeUtils.getOfficeExecutable(prg); if (offExec.exists() && offExec.canRead() && offExec.canExecute()) { ok(out, "OK - " + offExec.getPath()); } else { warn(out, "Can't read or execute: " + offExec.getPath()); } } else { warn(out, "Can't read: " + prg.getPath()); } } } /** * Export configuration */ private void export(String userId, HttpServletRequest request, HttpServletResponse response) throws DatabaseException, IOException { log.debug("export({}, {}, {})", new Object[] { userId, request, response }); // Disable browser cache response.setHeader("Expires", "Sat, 6 May 1971 12:00:00 GMT"); response.setHeader("Cache-Control", "max-age=0, must-revalidate"); response.addHeader("Cache-Control", "post-check=0, pre-check=0"); String fileName = "OpenKM_" + WarUtils.getAppVersion().getVersion() + "_cfg.sql"; response.setHeader("Content-disposition", "inline; filename=\""+fileName+"\""); response.setContentType("text/x-sql; charset=UTF-8"); PrintWriter out = new PrintWriter(new OutputStreamWriter(response.getOutputStream(), "UTF8"), true); for (Config cfg : ConfigDAO.findAll()) { if (!Config.HIDDEN.equals(cfg.getType())) { out.println("DELETE FROM OKM_CONFIG WHERE CFG_KEY='" + cfg.getKey() + "';"); } } for (Config cfg : ConfigDAO.findAll()) { if (!Config.HIDDEN.equals(cfg.getType())) { StringBuffer insertCfg = new StringBuffer("INSERT INTO OKM_CONFIG (CFG_KEY, CFG_TYPE, CFG_VALUE) VALUES ('"); insertCfg.append(cfg.getKey()).append("', '"); insertCfg.append(cfg.getType()).append("', '"); if (cfg.getValue() == null || cfg.getValue().equals("null")) { insertCfg.append("").append("');"); } else { insertCfg.append(cfg.getValue()).append("');"); } out.println(insertCfg); } } out.flush(); log.debug("export: void"); } /** * Import configuration into database */ private void importConfig(String userId, HttpServletRequest request, HttpServletResponse response, final byte[] data, Session dbSession) throws DatabaseException, IOException, SQLException { log.debug("importConfig({}, {}, {}, {}, {})", new Object[] { userId, request, response, data, dbSession }); WorkerUpdate worker = new DatabaseQueryServlet().new WorkerUpdate(); worker.setData(data); dbSession.doWork(worker); log.debug("importConfig: void"); } }
package de.dzmitry_lamaka.lesaratesttask.ui; import android.content.Context; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import java.util.ArrayList; import java.util.List; import de.dzmitry_lamaka.lesaratesttask.R; import de.dzmitry_lamaka.lesaratesttask.network.data.Product; class ProductsAdapter extends RecyclerView.Adapter<ProductsAdapter.ViewHolder> { @NonNull private final LayoutInflater layoutInflater; @NonNull private final List<Product> products = new ArrayList<>(); ProductsAdapter(@NonNull final Context context) { this.layoutInflater = LayoutInflater.from(context); setHasStableIds(true); } void addProducts(@NonNull final List<Product> newProducts) { if (newProducts.isEmpty()) { return; } notifyItemRangeInserted(products.size() - 1, newProducts.size()); products.addAll(newProducts); } boolean hasProducts() { return !products.isEmpty(); } @Override public long getItemId(int position) { return position; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { return new ViewHolder(layoutInflater.inflate(R.layout.item_product, parent, false)); } @Override public void onBindViewHolder(ViewHolder holder, int position) { final Context context = holder.itemView.getContext(); final Product item = products.get(position); Glide.with(context) .load(item.getThumbnailPath()) .into(holder.image); holder.name.setText(item.getName()); holder.price.setText(context.getString(R.string.item_product_price, item.getPrice())); } @Override public int getItemCount() { return products.size(); } static class ViewHolder extends RecyclerView.ViewHolder { @NonNull private final ImageView image; @NonNull private final TextView name; @NonNull private final TextView price; private ViewHolder(@NonNull final View itemView) { super(itemView); image = (ImageView) itemView.findViewById(R.id.image); name = (TextView) itemView.findViewById(R.id.name); price= (TextView) itemView.findViewById(R.id.price); if (image == null || name == null || price == null) { throw new IllegalStateException("Forgot to add all required views"); } } } }
package com.farukcankaya.springcase.discount.entity; import org.springframework.lang.Nullable; import javax.validation.constraints.NotNull; import javax.validation.constraints.Positive; import java.math.BigDecimal; public class Product { @Positive @NotNull private Long productId; @Positive @NotNull private Long categoryId; @Positive @NotNull private BigDecimal price; @Positive @Nullable private BigDecimal discountedPrice; public Product() {} public Product(@NotNull Long productId, @NotNull Long categoryId, @NotNull BigDecimal price) { this.productId = productId; this.categoryId = categoryId; this.price = price; } public Product( @NotNull Long productId, @NotNull Long categoryId, @NotNull BigDecimal price, BigDecimal discountedPrice) { this.productId = productId; this.categoryId = categoryId; this.price = price; this.discountedPrice = discountedPrice; } public Long getProductId() { return productId; } public void setProductId(Long productId) { this.productId = productId; } public Long getCategoryId() { return categoryId; } public void setCategoryId(Long categoryId) { this.categoryId = categoryId; } public BigDecimal getPrice() { return price; } public void setPrice(BigDecimal price) { this.price = price; } public BigDecimal getDiscountedPrice() { return discountedPrice; } public void setDiscountedPrice(BigDecimal discountedPrice) { this.discountedPrice = discountedPrice; } }
package cn.canlnac.onlinecourse.presentation.internal.di.modules; import cn.canlnac.onlinecourse.domain.executor.PostExecutionThread; import cn.canlnac.onlinecourse.domain.executor.ThreadExecutor; import cn.canlnac.onlinecourse.domain.interactor.GetChatUseCase; import cn.canlnac.onlinecourse.domain.interactor.UseCase; import cn.canlnac.onlinecourse.domain.repository.ChatRepository; import cn.canlnac.onlinecourse.presentation.internal.di.PerActivity; import dagger.Module; import dagger.Provides; /** * 注入模块. */ @Module public class GetChatModule { private final int chatId; public GetChatModule( int chatId ) { this.chatId = chatId; } @Provides @PerActivity UseCase provideGetChatUseCase(ChatRepository chatRepository, ThreadExecutor threadExecutor, PostExecutionThread postExecutionThread){ return new GetChatUseCase(chatId, chatRepository, threadExecutor, postExecutionThread); } }
package main; import javafx.scene.control.*; import javafx.scene.layout.FlowPane; import utils.Filter; import utils.Utils; import componentsFX.*; import javafx.application.Application; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.layout.ColumnConstraints; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.stage.Stage; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.*; import java.util.concurrent.Executors; import javax.imageio.ImageIO; /** * Main class */ public class SmartCam extends Application { double percentValue = 50.0; String descValue = ""; BufferedImage imgBuff; String imgPath = "src/inception5h/tensorPics/jack.jpg"; String labels[] = {"None", "Red", "Green", "Blue", "Black and White", "Sepia"}; String labelsFrame[] = {"Golden", "Brush"}; @Override public void start(Stage stage) throws IOException { // Tabs declaration TabPane tabPane = new TabPane(); tabPane.setTabClosingPolicy(TabPane.TabClosingPolicy.UNAVAILABLE); Tab tabImage = new Tab("Image"); Tab tabCamera = new Tab("Camera"); tabPane.getTabs().add(tabImage); tabPane.getTabs().add(tabCamera); imgBuff = ImageIO.read(new File(imgPath)); // Results of image classification ArrayList<Object> classifyResult = ClassifyImage.displayClassify("src/inception5h/", imgPath); // Display of image with classification ImageViewer viewer = new ImageViewer(imgBuff, String.format("Best match: %s (%.2f%%)%n", classifyResult.get(0), classifyResult.get(1))); viewer.setMaxWidth(Double.MAX_VALUE); //Color filter inputs CheckBox checkBoxFilter = new CheckBox(); ChoiceBoxCustom choiceBoxFilter = new ChoiceBoxCustom(labels); FlowPane flowPaneFilter = new FlowPane(); flowPaneFilter.getChildren().add(checkBoxFilter); flowPaneFilter.getChildren().add(choiceBoxFilter); // Borders inputs CheckBox checkBoxFrame = new CheckBox(); ChoiceBoxCustom choiceBoxFrame = new ChoiceBoxCustom(labelsFrame); FlowPane flowPaneFrame = new FlowPane(); flowPaneFrame.getChildren().add(checkBoxFrame); flowPaneFrame.getChildren().add(choiceBoxFrame); //Image past inputs CheckBox checkBoxImageToPaste = new CheckBox(); ButtonSelectFilePath buttonSelectImage = new ButtonSelectFilePath("Choose image", stage); Spinner<Integer> spinnerX = new Spinner<Integer>(0, 10000, 0); Spinner<Integer> spinnerY = new Spinner<Integer>(0, 10000, 0); Spinner<Integer> spinnerH = new Spinner<Integer>(0, 10000, 50); Spinner<Integer> spinnerW = new Spinner<Integer>(0, 10000, 50); spinnerX.setEditable(true); spinnerY.setEditable(true); FlowPane flowPaneImage = new FlowPane(); flowPaneImage.getChildren().addAll(checkBoxImageToPaste, buttonSelectImage, spinnerX, spinnerY, spinnerH, spinnerW); // slider for percent SliderAndLabel percent = new SliderAndLabel(0.0, 100.0, percentValue, "Percentage"); // text input for description TextfieldAndLabel desc = new TextfieldAndLabel("Your description:"); /* Buttons */ ButtonSelectFilePath fileToOpen = new ButtonSelectFilePath("Open img.", stage); ButtonSelectDirectoryPath directoryToTest = new ButtonSelectDirectoryPath("Image dir.", stage); ButtonSelectDirectoryPath directoryToSave = new ButtonSelectDirectoryPath("Save dir.", stage); Button runFilter = new Button("Run"); Button updateImage = new Button("Update Image"); // box for filter buttons ChoiceBoxCustom choiceBoxFilter2 = new ChoiceBoxCustom(labels); HBox buttonFilterBox = new HBox(directoryToTest, directoryToSave, choiceBoxFilter2, runFilter); buttonFilterBox.setSpacing(0); buttonFilterBox.setAlignment(Pos.BOTTOM_CENTER); // box for open buttons HBox buttonFileBox = new HBox(fileToOpen, updateImage); buttonFileBox.setSpacing(0); buttonFileBox.setAlignment(Pos.BOTTOM_CENTER); updateImage.setOnAction(event -> { if (fileToOpen.getPath() != null) { // Results of image classification ArrayList<Object> tempResult = ClassifyImage.displayClassify("src/inception5h/", fileToOpen.getPath()); try { imgBuff = ImageIO.read(new File(fileToOpen.getPath())); } catch (IOException e) { e.printStackTrace(); } if (choiceBoxFilter.getValue() != null && checkBoxFilter.isSelected()) { imgBuff = Filter.applyColor(imgBuff, (String) choiceBoxFilter.getValue()); } if (choiceBoxFrame.getValue() != null && checkBoxFrame.isSelected()) { try { imgBuff = Filter.applyFrame(imgBuff, "src/frame/" + choiceBoxFrame.getValue() + ".png", null); } catch (IOException e) { e.printStackTrace(); } } if (buttonSelectImage.getPath() != null && checkBoxImageToPaste.isSelected()) { try { imgBuff = Filter.applyImage(imgBuff, buttonSelectImage.getPath(), spinnerX.getValue(), spinnerY.getValue(), spinnerH.getValue(), spinnerW.getValue()); } catch (IOException e) { e.printStackTrace(); } } viewer.setImageView(imgBuff); viewer.setLabel(String.format("Best match: %s (%.2f%%)%n", tempResult.get(0), tempResult.get(1))); } }); runFilter.setOnAction(event -> { percentValue = percent.getValue(); descValue = desc.getText(); List<ArrayList<Object>> results = ClassifyImage.ArrayClassify("src/inception5h/", directoryToTest.getPath()); for (ArrayList result : results) { String[] labelFound = result.get(0).toString().split(" "); if (((Float) result.get(1)) >= percentValue) { for (String labelWord : labelFound) { if (descValue.contains(labelWord) || descValue.equals("")) { try { Utils.copyFile(result.get(2).toString(), labelWord, directoryToSave.getPath()); } catch (IOException e) { e.printStackTrace(); } String filter = (String) choiceBoxFilter2.getValue(); if (filter != null && !filter.equals("aucun")) { try { Filter.filter(directoryToSave.getPath() + "/" + labelWord + "." + Utils.getExtension(result.get(2).toString()), labelWord, directoryToSave.getPath(), filter); } catch (Exception e) { e.printStackTrace(); } } break; } } } } }); /* Image Pane */ GridPane gridImage = new GridPane(); GridPane gridControl = new GridPane(); gridControl.add(flowPaneFilter, 0, 0, 1, 1); gridControl.add(flowPaneFrame, 0, 1, 1, 1); gridControl.add(flowPaneImage, 0, 2, 1, 1); gridImage.add(buttonFileBox, 0, 0, 3, 1); gridImage.add(viewer, 0, 1, 2, 1); gridImage.add(gridControl, 2, 1, 3, 1); gridImage.add(percent, 0, 2, 1, 1); gridImage.add(desc, 1, 2, 1, 1); gridImage.add(buttonFilterBox, 2, 2, 1, 1); tabImage.setContent(gridImage); viewer.setAlignment(Pos.CENTER); percent.setAlignment(Pos.CENTER); desc.setAlignment(Pos.CENTER); updateImage.setAlignment(Pos.CENTER); ColumnConstraints col3 = new ColumnConstraints(); col3.setPercentWidth(100); gridImage.getColumnConstraints().addAll(col3, col3, col3); /* Camera Pane */ GridPane gridCamera = new GridPane(); ClassifyWebcam webcamFeed = new ClassifyWebcam(stage); gridCamera.add(webcamFeed, 0, 0, 1, 1); webcamFeed.setAlignment(Pos.CENTER); gridCamera.getColumnConstraints().addAll(col3); tabCamera.setContent(gridCamera); /* Scene declaration for window */ Scene scene = new Scene(tabPane, 780, 570); stage.setScene(scene); stage.show(); } public static void main(String[] args) { launch(); } }
package animatronics.client.render.block; import org.lwjgl.opengl.GL11; import animatronics.client.render.LibRenderIDs; import animatronics.client.render.tile.RenderTileEntityMoonPrism; import animatronics.common.tile.TileEntityMoonPrism; import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler; import net.minecraft.block.Block; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.client.renderer.tileentity.TileEntityRendererDispatcher; import net.minecraft.world.IBlockAccess; public class RenderBlockMoonPrism implements ISimpleBlockRenderingHandler { @Override public void renderInventoryBlock(Block block, int metadata, int modelId, RenderBlocks renderer) { GL11.glPushMatrix(); GL11.glTranslatef(-0.5F, -0.5F, -0.5F); RenderTileEntityMoonPrism.renderInInventory(new TileEntityMoonPrism()); System.out.println("RenderBlockMoonPrism.renderInventoryBlock()"); GL11.glPopMatrix(); } @Override public boolean renderWorldBlock(IBlockAccess world, int x, int y, int z, Block block, int modelId, RenderBlocks renderer) { return false; } @Override public boolean shouldRender3DInInventory(int modelId) { return true; } @Override public int getRenderId() { return LibRenderIDs.idMoonPrism; } }
package com.ojas.rpo.security.transfer; import java.util.Date; public class UserListTransfer { public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getFullName() { return fullName; } public void setFullName(String fullName) { this.fullName = fullName; } public Long getContactNumber() { return contactNumber; } public void setContactNumber(Long contactNumber) { this.contactNumber = contactNumber; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getRole() { return role; } public void setRole(String role) { this.role = role; } public String getQuestion() { return question; } public void setQuestion(String question) { this.question = question; } public String getAnswer() { return answer; } public void setAnswer(String answer) { this.answer = answer; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public String getReportsTo() { return reportsTo; } public void setReportsTo(String reportsTo) { this.reportsTo = reportsTo; } public String getReportingMail() { return reportingMail; } public void setReportingMail(String reportingMail) { this.reportingMail = reportingMail; } public Integer getExtension() { return extension; } public void setExtension(Integer extension) { this.extension = extension; } public String getDesignation() { return designation; } public void setDesignation(String designation) { this.designation = designation; } public Date getDob() { return dob; } public void setDob(Date dob) { this.dob = dob; } public Date getDoj() { return doj; } public void setDoj(Date doj) { this.doj = doj; } public String getNewPassword() { return newPassword; } public void setNewPassword(String newPassword) { this.newPassword = newPassword; } public Long getSalary() { return salary; } public void setSalary(Long salary) { this.salary = salary; } public Long getVariablepay() { return variablepay; } public void setVariablepay(Long variablepay) { this.variablepay = variablepay; } public Long getCtc() { return ctc; } public void setCtc(Long ctc) { this.ctc = ctc; } public Long getMintarget() { return mintarget; } public void setMintarget(Long mintarget) { this.mintarget = mintarget; } public Long getMaxtarget() { return maxtarget; } public void setMaxtarget(Long maxtarget) { this.maxtarget = maxtarget; } public String getTargetduration() { return targetduration; } public void setTargetduration(String targetduration) { this.targetduration = targetduration; } public String getDob1() { return dob1; } public void setDob1(String dob1) { this.dob1 = dob1; } public String getDoj1() { return doj1; } public void setDoj1(String doj1) { this.doj1 = doj1; } private Long id; private String name; private String password; private String fullName; private Long contactNumber; private String email; private String role; private String question; private String answer; private String status; private Date date; private String dob1; private String doj1; private String reportsTo; private String reportingMail; private Integer extension; private String designation; private Date dob; private Date doj; private String newPassword; private Long salary; private Long variablepay; private Long ctc; private Long mintarget; private Long maxtarget; private String targetduration; }
package com.lucasgr7.hexagontest.domain; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="VEHICLE") public class Vehicle implements Serializable { private static final long serialVersionUID = 1281996955136816880L; public Vehicle() {} public Vehicle(String name, String desc, Integer vehicle_type, String plate) { super(); this.name = name; this.desc = desc; this.vehicleType = vehicle_type; this.plate = plate; } public Vehicle(int id, String name, String desc, Integer vehicle_type, String plate) { super(); this.id = id; this.name = name; this.desc = desc; this.vehicleType = vehicle_type; this.plate = plate; } @Id @Column(name="ID", updatable=false, nullable=false) @GeneratedValue public int id; @Column(name="NAME") public String name; @Column(name="DESCRIPTION") public String desc; @Column(name="VEHICLE_TYPE") public Integer vehicleType; @Column(name="PLATE") public String plate; }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package contactmanagementsoftware; import java.util.ArrayList; import java.util.HashMap; /** * * @author jiefo */ public interface AcquaintancesSystem{ public void addAcquaintances(AcquaintancesSystem acquaintances); public void removeAcquaintances(int position); public AcquaintancesSystem getAcquaintances(int position); public ArrayList<AcquaintancesSystem> getChild(); public HashMap<String, String> getInformation(); public HashMap<String, String> getOtherInformation(); }
package com.tencent.mm.plugin.j; import com.tencent.mm.plugin.j.b.10; import com.tencent.mm.plugin.j.c.a; import com.tencent.mm.plugin.messenger.foundation.a.a.f.c; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.storage.bd; import java.util.Iterator; class b$10$1 implements Runnable { final /* synthetic */ c htd; final /* synthetic */ 10 hte; b$10$1(10 10, c cVar) { this.hte = 10; this.htd = cVar; } public final void run() { x.d("MicroMsg.CalcWxService", "on notify change [%s] [%d]", new Object[]{this.htd.lcx, Integer.valueOf(this.htd.lcy.size())}); if (!"delete".equals(this.htd.lcx)) { int i = "delete".equals(this.htd.lcx) ? 2 : 1; Iterator it = this.htd.lcy.iterator(); while (it.hasNext()) { bd bdVar = (bd) it.next(); if (bdVar != null) { boolean contains; b bVar = this.hte.hsX; long j = bdVar.field_msgId; if (bVar.hsJ) { contains = bVar.hsI.contains(Long.valueOf(j)); } else { contains = false; } if (contains) { x.d("MicroMsg.CalcWxService", "it locked now [%d]", new Object[]{Long.valueOf(bdVar.field_msgId)}); } else { b.d(this.hte.hsX).H(new a(bdVar, i)); } } } } } }
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) package com.pybeta.daymatter.ui; import java.util.Calendar; import java.util.Locale; import java.util.TimeZone; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import com.pybeta.daymatter.R; import com.pybeta.daymatter.WorldTimeZone; import com.pybeta.daymatter.utils.LogUtil; import com.pybeta.ui.utils.ItemListAdapter; // Referenced classes of package com.pybeta.daymatter.ui: // WorldTimeView public class WorldTimeListAdapter extends ItemListAdapter<WorldTimeZone, WorldTimeView> { class TimeHolder { String date; String day; String dayOfMonth; int hour; int mins; String month; String timeInShort; } public WorldTimeListAdapter(Context context) { super(R.layout.worldtime_list_item, LayoutInflater.from(context)); mContext = context; } private TimeHolder getTimeHolder(Calendar calendar, long l, Locale locale) { TimeHolder timeholder = new TimeHolder(); calendar.setTimeInMillis(l); int i = calendar.get(5); timeholder.dayOfMonth = calendar.getDisplayName(Calendar.DAY_OF_MONTH, Calendar.ALL_STYLES, locale); timeholder.month = calendar.getDisplayName(Calendar.MONTH, Calendar.SHORT, locale); timeholder.day = calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, locale); if(locale.equals(Locale.CHINA) || locale.equals(Locale.TAIWAN) || locale.equals(Locale.CHINESE)) timeholder.date = (new StringBuilder(String.valueOf(timeholder.month))).append(" ").append(i).append("日 ").append(timeholder.day).toString(); else timeholder.date = (new StringBuilder(String.valueOf(timeholder.month))).append(" ").append(i).append(" ").append(timeholder.day).toString(); timeholder.hour = calendar.get(Calendar.HOUR_OF_DAY); timeholder.mins = calendar.get(Calendar.MINUTE); String mins = timeholder.mins+""; if(timeholder.mins < 10){ mins = "0"+timeholder.mins; } timeholder.timeInShort = (new StringBuilder(String.valueOf(timeholder.hour))).append(":").append(mins).toString(); return timeholder; } protected WorldTimeView createView(View view) { return new WorldTimeView(view); } protected void update(int i, WorldTimeView worldtimeview, WorldTimeZone worldtimezone) { int j = TimeZone.getDefault().getRawOffset(); Calendar calendar = Calendar.getInstance(); long l = calendar.getTimeInMillis(); long l1 = l - (long)j; long l2 = l1 + (long)worldtimezone.getRawOffset(); LogUtil.Sysout((new StringBuilder("nowTimeInMillis: ")).append(l).append(" ,gmt0TimeInMillis: ").append(l1).append(" ,itemTimeInMillis: ").append(l2).toString()); Locale locale = mContext.getResources().getConfiguration().locale; locale.getLanguage(); String s = locale.getCountry(); locale.getDisplayCountry(); calendar.setTimeInMillis(l2); Locale locale1; String s1; String s2; TimeHolder timeholder; if(s.equalsIgnoreCase("cn")) { s1 = worldtimezone.getCityNameZH(); s2 = worldtimezone.getCountryNameZH(); locale1 = Locale.CHINA; } else if(s.equalsIgnoreCase("tw")) { locale1 = Locale.TAIWAN; s1 = worldtimezone.getCityNameTW(); s2 = worldtimezone.getCountryNameTW(); } else { locale1 = Locale.US; s1 = worldtimezone.getCityName(); s2 = worldtimezone.getCountryName(); } timeholder = getTimeHolder(calendar, l2, locale1); worldtimeview.mWorldTime_tv_cityName.setText(s1); worldtimeview.mWorldTime_tv_countryName.setText(s2); worldtimeview.mWorldTime_tv_time.setText(timeholder.timeInShort); worldtimeview.mWorldTime_tv_date.setText(timeholder.date); worldtimeview.mWorldTime_tv_gmt.setText(worldtimezone.getGMT()); } private Context mContext; }
package net.liuzd.spring.boot.v2.model; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; import net.liuzd.spring.boot.v2.entity.User; /** * 自定义分页 */ @Data @Accessors(chain = true) @EqualsAndHashCode(callSuper = true) public class UserPage extends Page<User> { private static final long serialVersionUID = 7246194974980132237L; private Integer selectInt; private String selectStr; public UserPage(long current, long size) { super(current, size); } }
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int zs = sc.nextInt(); for (int qqq = 0; qqq < zs; qqq++) { int n = sc.nextInt(); for (int i = 0; i < n; i++) { String s = sc.next(); char ch = '3'; for (int j = 0; j < s.length(); j++) { if (s.charAt(j) == '0') { if (ch == '0' || ch == '2') { System.out.print("1"); ch = '1'; } if (ch == '1') { System.out.print("0"); ch = '0'; } } if (s.charAt(j) == '1') { if (ch == '0' || ch == '1') { System.out.print("1"); ch = '2'; } if (ch == '2') { System.out.print("0"); ch = '1'; } } } System.out.println(""); } } } }
package com.argentinatecno.checkmanager.main.fragment_checks; import com.argentinatecno.checkmanager.entities.Check; import java.util.List; public interface FragmentChecksRepository { void removeCheck(List<Check> checks); void updateCheckDestiny(int id,String destiny, String destinyDate, boolean isUpdate); void selectAll(); void getChecksSearch(String s); }
package br.unipe.cc.mlpIII.gui; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.TreeSet; import br.unipe.cc.mlpIII.modelo.Veiculo; import br.unipe.cc.mlpIII.pertinencia.Db; import br.unipe.cc.mlpIII.report.RelatorioVeiculos; import br.unipe.cc.mlpIII.util.EntidadeNaoEncontradaException; import javafx.application.Application; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.Button; import javafx.scene.control.ButtonType; import javafx.scene.control.SelectionMode; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.image.Image; import javafx.stage.Stage; import javafx.stage.WindowEvent; @SuppressWarnings({"rawtypes","unchecked"}) public class TelaCadastroVeiculo extends Application { private Scene scene; private Parent root; private Stage telaCadastroSeguroStage; private Db db = new Db(); private ResultSet segurosInDataBase; private TableView<Veiculo> table; private ObservableList<Veiculo> veiculos; private TableColumn colunaId = new TableColumn("ID"); private TableColumn colunaPlaca = new TableColumn("Placa"); private TableColumn colunaModelo = new TableColumn("Modelo"); private TableColumn colunaChassis = new TableColumn("Chassis"); private TableColumn colunaAno = new TableColumn("Ano"); private TableColumn colunaFabricante = new TableColumn("Fabricante"); private TableColumn colunaTitular = new TableColumn("Titular"); private Button btnIncluir; private Button btnAlterar; private Button btnDeletar; private Button btnRelatorio; private Stage telaEditStage = new Stage(); public TelaCadastroVeiculo(){ db.abrirConexao(); } public void show(){ telaCadastroSeguroStage.show(); } @Override public void start(Stage primaryStage) throws Exception { this.telaCadastroSeguroStage = primaryStage; try { root = FXMLLoader.load(getClass().getResource("TelaCadastroEnderecos.fxml")); scene = new Scene(root); table = (TableView<Veiculo>) scene.lookup("#table"); veiculos = getInitialTableData(); table.setItems(veiculos); btnIncluir = (Button) scene.lookup("#btnIncluir"); btnIncluir.setOnAction( new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { incluir(); } }); btnAlterar = (Button) scene.lookup("#btnAlterar"); btnAlterar.setOnAction( new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { alterar(); } }); btnDeletar = (Button) scene.lookup("#btnDeletar"); btnDeletar.setOnAction( new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { if (deletarNoBancoDedados(table.getSelectionModel().getSelectedItem().getId())){ veiculos.remove(table.getSelectionModel().getSelectedItem()); } } }); btnRelatorio = (Button) scene.lookup("#btnRelatorio"); btnRelatorio.setOnAction( new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { try { relatorio(); } catch (EntidadeNaoEncontradaException e) { e.printStackTrace(); } } }); colunaId.setCellValueFactory(new PropertyValueFactory<Veiculo, Integer>("id")); colunaPlaca.setCellValueFactory(new PropertyValueFactory<Veiculo, String>("placa")); colunaModelo.setCellValueFactory(new PropertyValueFactory<Veiculo, String>("modelo")); colunaChassis.setCellValueFactory(new PropertyValueFactory<Veiculo, String>("chassis")); colunaAno.setCellValueFactory(new PropertyValueFactory<Veiculo, String>("ano")); colunaFabricante.setCellValueFactory(new PropertyValueFactory<Veiculo, String>("fabricante")); colunaTitular.setCellValueFactory(new PropertyValueFactory<Veiculo, String>("titular")); table.getColumns().setAll(colunaId, colunaPlaca, colunaModelo, colunaChassis, colunaAno, colunaFabricante, colunaTitular); table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY); table.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE); telaCadastroSeguroStage.setTitle("Cadastro de Veiculos"); telaCadastroSeguroStage.getIcons().add(new Image("file:imagens\\seguro.png")); telaCadastroSeguroStage.setScene(scene); telaCadastroSeguroStage.show(); } catch(Exception e) { e.printStackTrace(); } } public void fecharTelaCadastroEnderecos(){ db.fecharConexao(); telaCadastroSeguroStage.hide(); } private ObservableList<Veiculo> getInitialTableData() { List<Veiculo> list = new ArrayList<>(); segurosInDataBase = db.consulta("SELECT * FROM veiculo"); try { while(segurosInDataBase.next()){ list.add(new Veiculo(segurosInDataBase.getInt("id"), segurosInDataBase.getString("placa"), segurosInDataBase.getString("modelo"), segurosInDataBase.getString("chassis"), segurosInDataBase.getString("ano"), segurosInDataBase.getString("fabricante"), segurosInDataBase.getInt("titular"))); } } catch (SQLException e) { e.printStackTrace(); } ObservableList<Veiculo> data = FXCollections.observableList(list); return data; } private boolean deletarNoBancoDedados(int id) { Alert dialogConfirmacao = new Alert(Alert.AlertType.CONFIRMATION); ButtonType btnSim = new ButtonType("Sim"); ButtonType btnNao = new ButtonType("Não"); dialogConfirmacao.setTitle("Excluir registro"); dialogConfirmacao.setHeaderText("Deseja realmente excluir o registro selecionado?"); dialogConfirmacao.getButtonTypes().setAll(btnSim, btnNao); dialogConfirmacao.showAndWait(); if (dialogConfirmacao.getResult() == btnSim){ if (db.comando("DELETE FROM veiculo WHERE id = " + id)) return true; else{ Alert warning = new Alert(Alert.AlertType.WARNING); warning.setTitle("Erro"); warning.setHeaderText("Não foi possível deletar o registro no banco de dados."); warning.showAndWait(); return false; } } else { return false; } } private void incluir(){ TelaEditVeiculo telaEditEnderecos = new TelaEditVeiculo(); try { telaEditEnderecos.start(telaEditStage); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } telaEditStage.setOnHiding( new EventHandler<WindowEvent>() { @Override public void handle(WindowEvent event) { veiculos = getInitialTableData(); table.setItems(veiculos); } }); } private void alterar(){ if (table.getSelectionModel().getSelectedItem() != null){ TelaEditVeiculo telaEditVeiculo = new TelaEditVeiculo(table.getSelectionModel().getSelectedItem()); try { telaEditVeiculo.start(telaEditStage); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } telaEditStage.setOnHiding( new EventHandler<WindowEvent>() { @Override public void handle(WindowEvent event) { veiculos = getInitialTableData(); table.setItems(veiculos); } }); } } private void relatorio() throws EntidadeNaoEncontradaException{ if (table.getSelectionModel().getSelectedItem() != null){ Set<Veiculo> st = new TreeSet<Veiculo>(table.getSelectionModel().getSelectedItems()); RelatorioVeiculos rt = new RelatorioVeiculos(st); rt.print(); rt.end(); Alert dialogoInfo = new Alert(Alert.AlertType.INFORMATION); dialogoInfo.setTitle("Relatório"); dialogoInfo.setHeaderText("Relatório gerado!!!"); dialogoInfo.showAndWait(); } else { EntidadeNaoEncontradaException entidadeNaoEncontradaException = new EntidadeNaoEncontradaException(); throw entidadeNaoEncontradaException; } } }
package browser.base; import helper.PropHelper; import org.apache.log4j.Logger; import org.openqa.selenium.*; import java.lang.*; import java.util.*; /** * Created by admin.son.ton on 1/23/18. */ public class Browser { protected WebDriver driver; protected Properties properties; protected Logger logger = Logger.getLogger(Browser.class); protected static final String USER_AGENT_OPTS_PREFIX = "user-agent="; protected Browser(){ properties = PropHelper.loadPropertiesByFilePath("src/test/resources/browser.properties"); } public void tearDown(){ if(driver!=null){ driver.quit(); } } public WebDriver getWebDriver(){ return driver; } public void goTo(String url){ driver.get(url); } public String getUrl() {return driver.getCurrentUrl(); } public byte[] takeScreenShot(){ return ((TakesScreenshot)driver).getScreenshotAs(OutputType.BYTES); } public String getHtml(){ return String.valueOf(((JavascriptExecutor) driver).executeScript("return document.getElementsByTagName('body')[0].innerHTML")); } public void refresh(){ driver.navigate().refresh(); } public void openNewTab(String url){ ((JavascriptExecutor) driver).executeScript("window.open(arguments[0], '_blank');", url); Set<String> winHandles = driver.getWindowHandles(); String[] windHandlesArray = winHandles.toArray(new String[0]); driver.switchTo().window(windHandlesArray[windHandlesArray.length-1]); } public void switchToTab(String windowHandleId){ driver.switchTo().window(windowHandleId); } public String currentWindowHandleId(){ return driver.getWindowHandle(); } public Map<String,String> getCookiesAsMap(){ Map<String,String> cookiesMap = new HashMap<>(); Set<Cookie> cks = driver.manage().getCookies(); for (Cookie cookie : cks) { cookiesMap.put(cookie.getName(), cookie.getValue()); } return cookiesMap; } public JavascriptExecutor getJsExecutor(){ return ((JavascriptExecutor) driver); } public void addCookie(String name, String value) { Cookie ck = new Cookie(name, value); driver.manage().deleteCookieNamed(name); driver.manage().addCookie(ck); } }
package com.tencent.mm.g.a; import com.tencent.mm.sdk.b.b; public final class ay extends b { public a bIt; public static final class a { public boolean bIu = false; public boolean bIv = false; public boolean bIw = false; } public ay() { this((byte) 0); } private ay(byte b) { this.bIt = new a(); this.sFm = false; this.bJX = null; } }
package top.wangruns.nowcoder.leetcode; /** * * 题目描述 Sort a linked list using insertion sort. 输入{3,2,4} 输出{2,3,4} 分析 要求使用插入排序,对于数组的插入排序,我们可能会比较熟悉. 但是对于链表的插入排序,我们也可以参考着数组的思路来. 即,外部循环为每次要插入的元素; 内循环在已经排好的局部扫描,看在哪里插入. * */ public class P5_InsertionSortList { //链表的插入排序 public ListNode insertionSortList (ListNode head) { if(head==null||head.next==null) return head; ListNode res=new ListNode(0x80000000); //对于每一个需要插入的元素 while(head!=null) { ListNode next=head.next; ListNode resRef=res; //遍历找到合适的插入位置 while(resRef.next!=null&&resRef.next.val<head.val) { resRef=resRef.next; } head.next=resRef.next; resRef.next=head; head=next; } return res.next; } //数组的插入排序 public void insertionSortArray(int []a){ for(int i=1;i<a.length;i++) { for(int j=i;j>0;j--) { if(a[j]<a[j-1]) { int temp=a[j]; a[j]=a[j-1]; a[j-1]=temp; } } } } }
package com.polsl.edziennik.desktopclient.model.tables; import java.util.List; import com.polsl.edziennik.modelDTO.exam.ExamTaskTypeDTO; public class ExamTaskTypeTableModel extends TableModel<ExamTaskTypeDTO> { public ExamTaskTypeTableModel(List<ExamTaskTypeDTO> list) { super(list); } public ExamTaskTypeTableModel() { super(); } @Override public Object getValueAt(int rowIndex, int columnIndex) { if (rowIndex > -1 && rowIndex < data.size() && columnIndex > -1 && columnIndex < classNames.length) { if (data.get(rowIndex) == null || columnIndex > 0) return null; switch (columnIndex) { case 0: return data.get(rowIndex).getType(); case 1: return data.get(rowIndex).getWeight(); default: return null; } } else { return null; } } @Override public void setColumns() { columnNames = new String[] { entity.getString("taskType"), entity.getString("taskWeight") }; classNames = new Class[] { String.class, Float.class }; } }
package com.praveen.bo; import org.junit.*; import static org.junit.Assert.*; import com.praveen.model.*; import com.praveen.bo.*; public class TestEmployeeService{ private Employee emp; private EmployeeService empSer; @Before public void setup(){ emp = new Employee(); emp.setEmpId(1); emp.setEmpName("Balagowni"); emp.setEmpSal(20000); empSer = new EmployeeService(); } @Test public void testCalAppraisal(){ double actual = empSer.calAppraisal(emp); assertTrue("This will succeed", 1000 == actual); } @Test public void testCalAnnualSal(){ assertTrue("This is correct", 240000 == empSer.calAnnualSal(emp)); } }//end of class
package db.member; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; // 자바에서는 이벤트 리스너의 메서드가 3개이상 될때는, 개발자 대신 메서드 재정의 의무를 짊어진 어댑터 클래스를 지원한다 //그리고 어댑터 클래스의 예) keylistener -->keyadapter, windowlistener-->windowadapter, mouselistener-->mouseadapter public class MyWindowAdapter implements WindowListener{ @Override public void windowOpened(WindowEvent e) {} @Override public void windowClosing(WindowEvent e) {} @Override public void windowClosed(WindowEvent e) {} @Override public void windowIconified(WindowEvent e) {} @Override public void windowDeiconified(WindowEvent e) {} @Override public void windowActivated(WindowEvent e) {} @Override public void windowDeactivated(WindowEvent e) {} }
package com.simbircite.demo.validator; import org.springframework.validation.Errors; import org.springframework.validation.ValidationUtils; import org.springframework.validation.Validator; import com.simbircite.homesecretary.entity.PeriodicTransaction; public class PeriodicTransactionValidator implements Validator { @Override public boolean supports(Class<?> type) { return type.equals(PeriodicTransaction.class); } @Override public void validate(Object object, Errors errors) { ValidationUtils.rejectIfEmptyOrWhitespace(errors, "user", "user", "required"); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "accrual", "accrual", "required"); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "summ", "summ", "required"); } }
package springframework2; public interface WithSpringInterface { String add(String a, String b); int sub( int c, int d); }
package de.lise.terradoc.core.report.elements; import java.io.StringWriter; public class CodeElement extends TextElement { public CodeElement(String text) { super(text); } @Override public void appendHtml(StringWriter writer) { writer.append("<pre>"); super.appendHtml(writer); writer.append("</pre>"); } @Override public void appendAsciidoc(StringWriter writer) { writer.append(NEW_LINE).append(NEW_LINE); writer.append("----").append(NEW_LINE); super.appendAsciidoc(writer); writer.append(NEW_LINE).append("----").append(NEW_LINE); } }
package com.dennistjahyadigotama.soaya.activities.SearchActivity.Fragment; import android.os.Bundle; import android.os.Handler; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonArrayRequest; import com.android.volley.toolbox.Volley; import com.dennistjahyadigotama.soaya.Menu.Paginate.EndlessRecyclerViewScrollListener; import com.dennistjahyadigotama.soaya.Menu.adapter.ThreadListAdapter; import com.dennistjahyadigotama.soaya.Menu.adapter.ThreadListGetter; import com.dennistjahyadigotama.soaya.R; import com.dennistjahyadigotama.soaya.User; import com.dennistjahyadigotama.soaya.activities.SearchActivity.SearchActivity; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; /** * Created by Denn on 7/12/2016. */ public class SearchFragmentThread extends Fragment { List<ThreadListGetter> threadListGetterList = new ArrayList<>(); ThreadListAdapter adapter; RecyclerView recyclerView; RequestQueue requestQueue; String url = User.searchFragmentThreadUrl; public static SearchFragmentThread newInstance(int page, String title) { SearchFragmentThread fragmentFirst = new SearchFragmentThread(); Bundle args = new Bundle(); args.putInt("someInt", page); args.putString("someTitle", title); fragmentFirst.setArguments(args); return fragmentFirst; } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.search_fragment_thread, container, false); requestQueue = Volley.newRequestQueue(getContext()); recyclerView = (RecyclerView)view.findViewById(R.id.recycler_view); return view; } @Override public void onResume() { super.onResume(); threadListGetterList.clear(); Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { SetupPagination(SearchActivity.text); } }, 100); } protected void SetupPagination(final String text){ adapter = new ThreadListAdapter(threadListGetterList); LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity()); recyclerView.setLayoutManager(layoutManager); recyclerView.setItemAnimator(new DefaultItemAnimator()); recyclerView.setAdapter(adapter); recyclerView.addOnScrollListener(new EndlessRecyclerViewScrollListener(layoutManager) { @Override public void onLoadMore(int page, int totalItemsCount) { // GetData(totalItemsCount); GetData(totalItemsCount,text); } }); GetData(0,text); } private void GetData(int c, String text){ JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url+"?searchForum="+text+"&rrr="+c, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { String id,title, createby, createdate,category,profilepic,content,totalReply,totalViews,imageContentUrl; // String jsonResponse = ""; try { for (int i = 0; i < response.length(); i++) { JSONObject person = response.getJSONObject(i); ThreadListGetter threadGetter = new ThreadListGetter(); id = person.getString("id"); title = person.getString("title"); createby = person.getString("createBy"); createdate = person.getString("theDate"); category = person.getString("category"); profilepic = person.getString("profilepic"); content = person.getString("content"); totalReply = person.getString("totalReply"); totalViews= person.getString("views"); imageContentUrl = person.getString("imageUrl"); threadGetter.setTotalReply(totalReply); threadGetter.setTotalViews(totalViews); threadGetter.setId(id); threadGetter.setTitle(title); threadGetter.setCreateBy(createby); threadGetter.setDate(createdate); threadGetter.setCategory(category); threadGetter.setContent(content); threadGetter.setPhoto(profilepic); threadGetter.setImageContentUrl(imageContentUrl); threadListGetterList.add(threadGetter); } adapter.notifyDataSetChanged(); } catch (JSONException e) { e.printStackTrace(); Toast.makeText(getContext(), "Error: " + e.getMessage(), Toast.LENGTH_LONG).show(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { } }); requestQueue.add(jsonArrayRequest); } }
package org.fhcrc.honeycomb.metapop.environment; import org.fhcrc.honeycomb.metapop.RandomNumberUser; /** * Changes the environment as a Binomial process with a specified probability. * * Created on 26 Apr, 2013 * @author Adam Waite * @version $Id: BinomialEnvironmentChanger.java 1990 2013-04-26 21:39:23Z ajwaite $ */ public class BinomialEnvironmentChanger implements EnvironmentChanger { private double prob; private RandomNumberUser rng; /** * Constructor. * @param prob the probability that the environment changes. * @param rng the {@link RandomNumberUser}. * */ public BinomialEnvironmentChanger(double prob, RandomNumberUser rng) { this.prob = prob; this.rng = rng; } @Override public boolean environmentChanged() { return rng.getNextBinomial(1, prob) == 1 ? true : false; } @Override public double getProb() { return prob; } @Override public RandomNumberUser getRNG() { return rng; } @Override public String toString() { return new String("BinomialEnvironmentChanger, prob=" + prob + ", seed=" + getRNG()); } }
package tw.org.iii.java; public class HelloWorld { public static void main(String[] args) { // ln => ijk<l>mn => l => line System.out.println("Hello, Brad"); } }
package br.com.opensig.fiscal.server.sped.blocoH; import br.com.opensig.core.shared.modelo.Dados; import br.com.opensig.fiscal.server.sped.ARegistro; public class RegistroH001 extends ARegistro<DadosH001, Dados> { @Override protected DadosH001 getDados(Dados dados) throws Exception { DadosH001 d = new DadosH001(); d.setInd_mov(sped.getFisSpedFiscalMes() == 2 ? 0 : 1); return d; } }
package designer.ui.properties.tableModel; import com.intellij.openapi.project.Project; import designer.ui.editor.ElementFactory; import designer.ui.editor.JSLCanvas; import designer.ui.editor.element.Element; import designer.ui.properties.PropertyTable; import designer.ui.properties.editor.PropertiesCellEditor; import designer.ui.properties.renderer.PropertiesCellRenderer; import specification.Decision; import specification.Properties; import specification.definitions.Definition; import javax.swing.*; import javax.swing.table.AbstractTableModel; /** * Created by Tomas Hanus on 4/15/2015. */ public class DecisionTableModel extends AbstractTableModel { private Definition definition; private ElementFactory elementFactory; private Project project; private final String[] columnNames = {"Name", "Value"}; private Element element; private PropertyTable propertyTable; private JSLCanvas jslCanvas; private String[] idCollisionIn = new String[1]; public DecisionTableModel(Element element, PropertyTable propertyTable, Project project, JSLCanvas jslCanvas) { this.element = element; this.propertyTable = propertyTable; this.jslCanvas = jslCanvas; // this.elementFactory = ElementFactory.getInstance(); this.elementFactory = jslCanvas.getElementFactory(); this.propertyTable.setRowSelectionAllowed(true); this.project = project; this.definition = jslCanvas.getDiagramDefinition(); setRenderers(); setEditors(); } private void setRenderers() { this.propertyTable.getRowRendererModel().addRendererForRow(2, new PropertiesCellRenderer());//Step Properties } private void setEditors() { this.propertyTable.getRowEditorModel().addEditorForRow(2, new PropertiesCellEditor(project)); } public String getColumnName(int col) { return this.columnNames[col]; } @Override public int getRowCount() { return 3; } @Override public int getColumnCount() { return 2; } @Override public Object getValueAt(int row, int col) { if (row == 0) { if (col == 0) return new String("Id"); if (col == 1) return element.getId(); } else if (row == 1) { if (col == 0) return new String("Reference"); if (col == 1) return ((Decision) element).getRef(); } else if (row == 2) { if (col == 0) return new String("Properties"); if (col == 1) return ((Decision) element).getProperties(); } return null; } public void setValueAt(Object value, int row, int col) { if (row == 0) { if (elementFactory.isIdentifierAlreadyUsed((String) value, idCollisionIn) && !value.equals(getValueAt(row, col))) showIdCollisionWarning(); else element.setId((String) value); } else if (row == 1) { if (elementFactory.isIdentifierAlreadyUsed((String) value, idCollisionIn) && !value.equals(getValueAt(row, col))) showIdCollisionWarning(); else ((Decision) element).setRef((String) value); } else if (row == 2) { ((Decision) element).setProperties((Properties) value); } this.jslCanvas.fireJobDiagramChange(); } public boolean isCellEditable(int row, int col) { if (col == 1) return true; return false; } private void showIdCollisionWarning() { JOptionPane.showMessageDialog(this.propertyTable, "This identifier is already used in element " + this.idCollisionIn[0] + "!", "Identifier conflict", JOptionPane.WARNING_MESSAGE); } }
package com.mango.leo.zsproject.industrialpanorama.show; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import com.mango.leo.zsproject.R; import com.mango.leo.zsproject.industrialpanorama.address.AddressSelector; import com.mango.leo.zsproject.industrialpanorama.address.CityInterface; import com.mango.leo.zsproject.industrialpanorama.address.OnItemClickListener; import com.mango.leo.zsproject.industrialpanorama.bean.ChooseBean; import com.mango.leo.zsproject.industrialpanorama.bean.CityS; import com.mango.leo.zsproject.industrialservice.createrequirements.util.ProjectsJsonUtils; import com.mango.leo.zsproject.utils.AppUtils; import com.mango.leo.zsproject.utils.HttpUtils; import org.greenrobot.eventbus.EventBus; import java.io.IOException; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.List; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response; public class ChooseActivity extends Activity { @Bind(R.id.textView45) TextView textView45; @Bind(R.id.address) AddressSelector address; @Bind(R.id.button_city_re) Button buttonCityRe; @Bind(R.id.button_city_ok) Button buttonCityOk; private ArrayList<ChooseBean.ResponseListBean> c1 = new ArrayList<>(); private ArrayList<ChooseBean.ResponseListBean> c2 = new ArrayList<>(); private ArrayList<ChooseBean.ResponseListBean> c3 = new ArrayList<>(); private ArrayList<ChooseBean.ResponseListBean> c4 = new ArrayList<>(); private int what = -1; private CityS cityS; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.city_choose); ButterKnife.bind(this); initCity("",-1); initChoose(); cityS = new CityS(); } private void initChoose() { address.setTabAmount(4); //address.setCities(c1); address.setOnItemClickListener(new OnItemClickListener() { @Override public void itemClick(AddressSelector addressSelector, CityInterface city, int tabPosition) { switch (tabPosition){ case 0: initCity(city.getCityName(),0);//加载省 //AppUtils.showToast(getBaseContext(),"tabPosition :"+tabPosition+" "+city.getCityName()); break; case 1: initCity(city.getCityName(),1);//加载市 //AppUtils.showToast(getBaseContext(),"tabPosition :"+tabPosition+" "+city.getCityName()); break; case 2: cityS.setCity(city.getCityName()); initCity(city.getCityName(),2);//加载区 //AppUtils.showToast(getBaseContext(),"tabPosition :"+tabPosition+" "+city.getCityName()); break; case 3: cityS.setDistrict(city.getCityName()); //initCity(city.getCityName()); //AppUtils.showToast(getBaseContext(),"tabPosition :"+tabPosition+" "+city.getCityName()); break; } } }); address.setOnTabSelectedListener(new AddressSelector.OnTabSelectedListener() { @Override public void onTabSelected(AddressSelector addressSelector, AddressSelector.Tab tab) { switch (tab.getIndex()){ case 0: addressSelector.setCities(c1); c2.clear(); c3.clear(); c4.clear(); break; case 1: addressSelector.setCities(c2); c3.clear(); c4.clear(); break; case 2: addressSelector.setCities(c3); c4.clear(); break; case 4: addressSelector.setCities(c4); break; } } @Override public void onTabReselected(AddressSelector addressSelector, AddressSelector.Tab tab) { } }); } private void initCity(final String s,final int i) { new Thread(new Runnable() { @Override public void run() { HttpUtils.doGet("http://47.106.184.121:9999/business-service/tool/list/regions?parent=" + s, new Callback() { @Override public void onFailure(Call call, IOException e) { mHandler.sendEmptyMessage(1); Log.v("ccccccccc"," 1!! "); } @Override public void onResponse(Call call, Response response) { try { List<ChooseBean.ResponseListBean> beanList = ProjectsJsonUtils.readChooseBeans(response.body().string());//data是json字段获得data的值即对象数组 beanList.get(0).getName();//异常判断 至少要一个值 Message m = mHandler.obtainMessage(); m.obj = beanList; m.what = 0; m.sendToTarget(); } catch (Exception e) { Log.v("ccccccccc"," 2!! "+response.code()); what = i; mHandler.sendEmptyMessage(1); } } }); } }).start(); } private final ChooseActivity.MyHandler mHandler = new ChooseActivity.MyHandler(this); private class MyHandler extends Handler { private final WeakReference<ChooseActivity> mActivity; public MyHandler(ChooseActivity activity) { mActivity = new WeakReference<ChooseActivity>(activity); } @Override public void handleMessage(Message msg) { super.handleMessage(msg); ChooseActivity activity = mActivity.get(); if (activity != null) { switch (msg.what) { case 0: //AppUtils.showToast(getBaseContext(), "地区加载成功"); List<ChooseBean.ResponseListBean> chooseList = (List<ChooseBean.ResponseListBean>) msg.obj; for(int i =0;i<chooseList.size();i++){ if (chooseList.get(0).getType().toString().equals("country")){ c1.add(chooseList.get(i)); } if (chooseList.get(0).getType().toString().equals("province")){ c2.add(chooseList.get(i)); } if (chooseList.get(0).getType().toString().equals("city")){ c3.add(chooseList.get(i)); } if (chooseList.get(0).getType().toString().equals("district")){ c4.add(chooseList.get(i)); } } if (chooseList.get(0).getType().equals("country")){ address.setCities(c1); } if (chooseList.get(0).getType().equals("province")){ address.setCities(c2); } if (chooseList.get(0).getType().equals("city")){ address.setCities(c3); } if (chooseList.get(0).getType().equals("district")){ address.setCities(c4); } break; case 1: AppUtils.showToast(activity, "地区加载失败"); Log.v("wwwww"," what "+what); /* switch (what){ case 0: c2.clear(); address.setCities(c2); break; case 1: c3.clear(); address.setCities(c3); break; case 2: c4.clear(); address.setCities(c4); break; }*/ break; case 2: break; default: break; } } } } @OnClick({R.id.button_city_re, R.id.button_city_ok}) public void onViewClicked(View view) { switch (view.getId()) { case R.id.button_city_re: finish(); break; case R.id.button_city_ok: if (cityS.getCity() != null && cityS.getDistrict() != null){ EventBus.getDefault().postSticky(cityS); finish(); }else { AppUtils.showToast(this,"请选择城市和地区"); } break; } } }
package com.tencent.mm.plugin.fts.a; import com.tencent.mars.smc.IDKey; import com.tencent.mm.a.o; import com.tencent.mm.hardcoder.HardCoderJNI; import com.tencent.mm.kernel.a; import com.tencent.mm.kernel.g; import com.tencent.mm.plugin.report.f; import com.tencent.mm.protocal.d; import com.tencent.mm.sdk.platformtools.x; import java.util.ArrayList; public final class e { public static final int[] jqK = new int[]{8, 9, 10, 11, 12, 14, 19, 20, 21, 22, 24, 25, 26}; public static final a jqL = new a(); public static String jqM = ""; public static final void g(int i, long j, long j2) { if (d.b(i, jqK)) { g.Eg(); long longValue = new o(a.Df()).longValue(); if (d.qVO) { if (longValue % 100 != 1) { return; } } else if (d.qVP && longValue % 10 != 1) { return; } String str = "%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s"; Object[] objArr = new Object[11]; objArr[0] = Integer.valueOf(0); objArr[1] = Integer.valueOf(i); objArr[2] = Long.valueOf(j); objArr[3] = Integer.valueOf(0); objArr[4] = Integer.valueOf(jqL.jqN >= 1536 ? 1 : 0); objArr[5] = Long.valueOf(jqL.jqN); objArr[6] = Long.valueOf(jqL.jqO); objArr[7] = Long.valueOf(jqL.jqP); objArr[8] = Long.valueOf(jqL.jqQ); objArr[9] = Long.valueOf(jqL.jqR); objArr[10] = Long.valueOf(j2); x.v("MicroMsg.FTS.FTSReportApiLogic", "reportKVSearchTime: %d %s", Integer.valueOf(14175), String.format(str, objArr)); f.mDy.k(14175, r0); } } public static void u(int i, long j) { if (i > 0) { int i2 = ((i - 1) * 2) + 1; x.v("MicroMsg.FTS.FTSReportApiLogic", "reportIDKeySearchTime: reportKey=%d taskId=%d time=%d", Integer.valueOf(i2), Integer.valueOf(i), Long.valueOf(j)); ArrayList arrayList = new ArrayList(); IDKey iDKey = new IDKey(); iDKey.SetID(HardCoderJNI.SCENE_DECODE_PIC); iDKey.SetKey(i2); iDKey.SetValue((long) ((int) j)); arrayList.add(iDKey); iDKey = new IDKey(); iDKey.SetID(HardCoderJNI.SCENE_DECODE_PIC); iDKey.SetKey(i2 + 1); iDKey.SetValue(1); arrayList.add(iDKey); f.mDy.b(arrayList, false); } } public static void v(int i, long j) { if (i > 0) { int i2 = ((i - 1) * 4) + 1; ArrayList arrayList = new ArrayList(); IDKey iDKey = new IDKey(); iDKey.SetID(HardCoderJNI.SCENE_GIF); iDKey.SetKey(i2); iDKey.SetValue(1); arrayList.add(iDKey); if (j <= 100) { iDKey = new IDKey(); iDKey.SetID(HardCoderJNI.SCENE_GIF); iDKey.SetKey(i2 + 1); iDKey.SetValue(1); arrayList.add(iDKey); } else if (j <= 500) { iDKey = new IDKey(); iDKey.SetID(HardCoderJNI.SCENE_GIF); iDKey.SetKey(i2 + 2); iDKey.SetValue(1); arrayList.add(iDKey); } else { iDKey = new IDKey(); iDKey.SetID(HardCoderJNI.SCENE_GIF); iDKey.SetKey(i2 + 3); iDKey.SetValue(1); arrayList.add(iDKey); } f.mDy.b(arrayList, false); } } public static void qd(int i) { IDKey iDKey = new IDKey(); iDKey.SetID(146); iDKey.SetKey(0); iDKey.SetValue(1); ArrayList arrayList = new ArrayList(); arrayList.add(iDKey); if (i != 1) { iDKey = new IDKey(); iDKey.SetID(146); iDKey.SetKey(2); iDKey.SetValue(1); arrayList.add(iDKey); iDKey = new IDKey(); iDKey.SetID(146); iDKey.SetKey(i); iDKey.SetValue(1); arrayList.add(iDKey); } else { iDKey = new IDKey(); iDKey.SetID(146); iDKey.SetKey(1); iDKey.SetValue(1); arrayList.add(iDKey); } f.mDy.b(arrayList, false); } public static final void qe(int i) { x.i("MicroMsg.FTS.FTSReportApiLogic", "reportCommonChatroom: %d %d", Integer.valueOf(14731), Integer.valueOf(i)); f.mDy.h(14731, Integer.valueOf(i)); } public static final void aPZ() { x.i("MicroMsg.FTS.FTSReportApiLogic", "reportIDKeyFTSData %d %d %d %d %d", Long.valueOf(jqL.jqN), Long.valueOf(jqL.jqO), Long.valueOf(jqL.jqP), Long.valueOf(jqL.jqR), Long.valueOf(jqL.jqQ)); ArrayList arrayList = new ArrayList(); d(arrayList, 0); if (jqL.jqN > 1536) { d(arrayList, 1); } if (jqL.jqO >= 10000) { d(arrayList, 2); } if (jqL.jqP >= 5000) { d(arrayList, 3); } if (jqL.jqR >= 10000) { d(arrayList, 4); } if (jqL.jqQ >= 1000000) { d(arrayList, 5); } f.mDy.b(arrayList, false); } private static final void d(ArrayList<IDKey> arrayList, int i) { IDKey iDKey = new IDKey(); iDKey.SetID(729); iDKey.SetKey(i); iDKey.SetValue(1); arrayList.add(iDKey); } public static final void qf(int i) { x.i("MicroMsg.FTS.FTSReportApiLogic", "reportFTSVoiceResult 15375 %d", Integer.valueOf(i)); f.mDy.h(15375, Integer.valueOf(i)); } }
import edu.princeton.cs.algs4.Picture; import java.awt.Color; public class SeamCarver { private Picture picture = null; private static final double DEFAULT_ENERGY = 195075; // create a seam carver object based on the given picture public SeamCarver(Picture picture) { this.picture = new Picture(picture); } // current picture public Picture picture() { return picture; } // width of current picture public int width() { return picture.width(); } // height of current picture public int height() { return picture.height(); } // energy of pixel at column x and row y public double energy(int x, int y) { if (x < 0 || x >= width() || y < 0 || y >= height()) { throw new IndexOutOfBoundsException(); } if (x == 0 || y == 0 || x == width() - 1 || y == height() - 1) return DEFAULT_ENERGY; double dX = gradient(picture.get(x - 1, y), picture.get(x + 1, y)); double dY = gradient(picture.get(x, y - 1), picture.get(x, y + 1)); return dX + dY; } private double gradient(Color color1, Color color2) { int red = color2.getRed() - color1.getRed(); int green = color2.getGreen() - color1.getGreen(); int blue = color2.getBlue() - color1.getBlue(); return red * red + green * green + blue * blue; } // sequence of indices for horizontal seam public int[] findHorizontalSeam() { int height = height(); int width = width(); double[][] energies = new double[height][width]; int[][] pathTo = new int[height][width]; double[][] cumEngy = new double[height][width]; for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { energies[i][j] = energy(j, i); } } for (int i = 0; i < height; i++) cumEngy[i][0] = energies[i][0]; for (int j = 1; j < width; j++) { for (int i = 0; i < height; i++) { int col = j - 1; if (i == 0 || i == height - 1) { cumEngy[i][j] = cumEngy[i][col] + energies[i][j]; continue; } if (cumEngy[i - 1][col] > cumEngy[i][col]) { if (cumEngy[i][col] > cumEngy[i + 1][col]) { pathTo[i][j] = i + 1; cumEngy[i][j] = cumEngy[i + 1][col] + energies[i][j]; } else { pathTo[i][j] = i; cumEngy[i][j] = cumEngy[i][col] + energies[i][j]; } } else if (cumEngy[i - 1][col] > cumEngy[i + 1][col]) { pathTo[i][j] = i + 1; cumEngy[i][j] = cumEngy[i + 1][col] + energies[i][j]; } else { pathTo[i][j] = i - 1; cumEngy[i][j] = cumEngy[i - 1][col] + energies[i][j]; } } } int minIdx = 0; double min = Integer.MAX_VALUE; for (int i = 0; i < height; i++) { if (min > cumEngy[i][width - 1]) { min = cumEngy[i][width - 1]; minIdx = i; } } int[] seam = new int[width]; for (int i = seam.length - 1; i > 0; i--) { seam[i] = minIdx; minIdx = pathTo[minIdx][i]; } seam[0] = minIdx; return seam; } // sequence of indices for vertical seam public int[] findVerticalSeam() { int height = height(); int width = width(); double[][] energies = new double[height][width]; int[][] pathTo = new int[height][width]; double[][] cumEngy = new double[height][width]; for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { energies[i][j] = energy(j, i); } } for (int i = 0; i < width; i++) cumEngy[0][i] = energies[0][i]; for (int i = 1; i < height; i++) { for (int j = 0; j < width; j++) { int row = i - 1; if (j == 0 || j == width - 1) { cumEngy[i][j] = cumEngy[row][j] + energies[i][j]; continue; } if (cumEngy[row][j + 1] > cumEngy[row][j]) { if (cumEngy[row][j] > cumEngy[row][j - 1]) { pathTo[i][j] = j - 1; cumEngy[i][j] = cumEngy[row][j - 1] + energies[i][j]; } else { pathTo[i][j] = j; cumEngy[i][j] = cumEngy[row][j] + energies[i][j]; } } else if (cumEngy[row][j - 1] > cumEngy[row][j + 1]) { pathTo[i][j] = j + 1; cumEngy[i][j] = cumEngy[row][j + 1] + energies[i][j]; } else { pathTo[i][j] = j - 1; cumEngy[i][j] = cumEngy[row][j - 1] + energies[i][j]; } } } int minIdx = 0; double min = Integer.MAX_VALUE; for (int i = 0; i < width; i++) { if (min > cumEngy[height - 1][i]) { min = cumEngy[height - 1][i]; minIdx = i; } } int[] seam = new int[height]; for (int i = seam.length - 1; i > 0; i--) { seam[i] = minIdx; minIdx = pathTo[i][minIdx]; } seam[0] = minIdx; return seam; } // remove horizontal seam from current picture public void removeHorizontalSeam(int[] seam) { if (null == seam) throw new NullPointerException(); if (height() <= 1) throw new IllegalArgumentException(); if (seam.length != width() || !isValidSeam(seam, height())) throw new IllegalArgumentException(); Picture pit = new Picture(width(), height() - 1); int width = pit.width(); int height = pit.height(); for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { if (i >= seam[j]) pit.set(j, i, picture.get(j, i + 1)); else pit.set(j, i, picture.get(j, i)); } } picture = pit; } // remove vertical seam from current picture public void removeVerticalSeam(int[] seam) { if (null == seam) throw new NullPointerException(); if (width() <= 1) throw new IllegalArgumentException(); if (seam.length != height() || !isValidSeam(seam, width())) throw new IllegalArgumentException(); Picture pit = new Picture(width() - 1, height()); int width = pit.width(); int height = pit.height(); for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { if (j >= seam[i]) pit.set(j, i, picture.get(j + 1, i)); else pit.set(j, i, picture.get(j, i)); } } picture = pit; } private boolean isValidSeam(int[] seam, int boundary) { if (seam[0] >= boundary) return false; for (int i = 1; i < seam.length; i++) { if (seam[i] >= boundary || Math.abs(seam[i] - seam[i - 1]) > 1) return false; } return true; } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub } }
package java2.businesslogic.announcementban; public interface AnnouncementBanService { AnnouncementBanResponse ban(AnnouncementBanRequest request); }
package com.forsrc.utils; import org.apache.activemq.ActiveMQConnection; import org.apache.activemq.ActiveMQConnectionFactory; import javax.jms.*; import java.text.MessageFormat; /** * The type Active mq utils. */ public final class ActiveMqUtils { private ThreadLocal<Connection> threadLocal = new ThreadLocal<Connection>(); private ConnectionFactory connectionFactory; private String url; /** * Instantiates a new Active mq utils. * * @param url the url */ public ActiveMqUtils(String url) { connectionFactory = getConnectionFactory(url); } private ConnectionFactory getConnectionFactory(String url) { Connection connection = null; connectionFactory = new ActiveMQConnectionFactory( ActiveMQConnection.DEFAULT_USER, ActiveMQConnection.DEFAULT_PASSWORD, url); return connectionFactory; } /** * Gets connection. * * @return the connection * @throws JMSException the jms exception */ public synchronized Connection getConnection() throws JMSException { Connection connection = threadLocal.get(); if (connection != null) { LogUtils.LOGGER.info(MessageFormat.format("GetConnection form threadLocal: {0}", connection)); return connection; } connection = connectionFactory.createConnection(); threadLocal.set(connection); LogUtils.LOGGER.info(MessageFormat.format("New connection : {0}", connection)); return connectionFactory.createConnection(); } /** * Close. * * @throws JMSException the jms exception */ public synchronized void close() throws JMSException { Connection connection = threadLocal.get(); threadLocal.set(null); if (connection != null) { connection.close(); } } /** * Send message active mq utils. * * @param queueName the queue name * @param activeMqUtilsSendMessage the active mq utils send message * @return the active mq utils * @throws JMSException the jms exception */ public ActiveMqUtils sendMessage(String queueName, ActiveMqUtilsSendMessage activeMqUtilsSendMessage) throws JMSException { Connection connection = getConnection(); connection.start(); LogUtils.LOGGER.info(MessageFormat.format("Connection start : {0}", connection)); Session session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE); LogUtils.LOGGER.info(MessageFormat.format("Session create : {0}", connection)); Destination destination = session.createQueue(queueName); MessageProducer producer = session.createProducer(destination); producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); activeMqUtilsSendMessage.sendMessage(session, producer, destination); session.commit(); LogUtils.LOGGER.info(MessageFormat.format("Session commit : {0}", connection)); session.close(); LogUtils.LOGGER.info(MessageFormat.format("Session close : {0}", connection)); connection.close(); LogUtils.LOGGER.info(MessageFormat.format("Connection close : {0}", connection)); return this; } /** * Send message active mq utils. * * @param queueName the queue name * @param message the message * @return the active mq utils * @throws JMSException the jms exception */ public ActiveMqUtils sendMessage(String queueName, final String message) throws JMSException { return sendMessage(queueName, new ActiveMqUtilsSendMessage() { @Override public void sendMessage(Session session, MessageProducer producer, Destination destination) throws JMSException { TextMessage textMessage = session.createTextMessage(message); producer.send(destination, textMessage); } }); } /** * Send message active mq utils. * * @param topic the topic * @param activeMqUtilsSendMessage the active mq utils send message * @return the active mq utils * @throws JMSException the jms exception */ public ActiveMqUtils sendMessage(String[] topic, ActiveMqUtilsSendMessage activeMqUtilsSendMessage) throws JMSException { Connection connection = getConnection(); connection.start(); LogUtils.LOGGER.info(MessageFormat.format("Connection start : {0}", connection)); Session session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE); LogUtils.LOGGER.info(MessageFormat.format("Session create : {0}", connection)); for (int i = 0; i < topic.length; i++) { Destination destination = session.createTopic(topic[i]); MessageProducer producer = session.createProducer(destination); producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); activeMqUtilsSendMessage.sendMessage(session, producer, destination); } session.commit(); LogUtils.LOGGER.info(MessageFormat.format("Session commit : {0}", connection)); session.close(); LogUtils.LOGGER.info(MessageFormat.format("Session close : {0}", connection)); connection.close(); LogUtils.LOGGER.info(MessageFormat.format("Connection close : {0}", connection)); return this; } /** * Receive message active mq utils. * * @param queueName the queue name * @param activeMqUtilsReceiveMessage the active mq utils receive message * @return the active mq utils * @throws JMSException the jms exception */ public ActiveMqUtils receiveMessage(String queueName, ActiveMqUtilsReceiveMessage activeMqUtilsReceiveMessage) throws JMSException { Connection connection = getConnection(); connection.start(); LogUtils.LOGGER.info(MessageFormat.format("Connection start : {0}", connection)); Session session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE); LogUtils.LOGGER.info(MessageFormat.format("Session create : {0}", connection)); Destination destination = session.createQueue(queueName); MessageConsumer consumer = session.createConsumer(destination); activeMqUtilsReceiveMessage.receiveMessage(session, consumer, destination); while (true) { TextMessage message = (TextMessage) consumer.receive(2000); if (message != null) { LogUtils.LOGGER.info(MessageFormat.format("Receive message : {0} --> {1}", message, connection)); activeMqUtilsReceiveMessage.todo(message); break; } } session.commit(); LogUtils.LOGGER.info(MessageFormat.format("Session commit : {0}", connection)); session.close(); LogUtils.LOGGER.info(MessageFormat.format("Session close : {0}", connection)); connection.close(); LogUtils.LOGGER.info(MessageFormat.format("Connection colse : {0}", connection)); return this; } /** * Receive message active mq utils. * * @param queueName the queue name * @return the active mq utils * @throws JMSException the jms exception */ public ActiveMqUtils receiveMessage(String queueName) throws JMSException { return receiveMessage(queueName, new ActiveMqUtilsReceiveMessage() { @Override public void receiveMessage(Session session, MessageConsumer consumer, Destination destination) throws JMSException { } @Override public void todo(TextMessage message) { System.out.print(message); } }); } /** * The interface Active mq utils send message. */ public interface ActiveMqUtilsSendMessage { /** * Send message. * * @param session the session * @param producer the producer * @param destination the destination * @throws JMSException the jms exception */ void sendMessage(Session session, MessageProducer producer, Destination destination) throws JMSException; } /** * The interface Active mq utils receive message. */ public interface ActiveMqUtilsReceiveMessage { /** * Receive message. * * @param session the session * @param consumer the consumer * @param destination the destination * @throws JMSException the jms exception */ void receiveMessage(Session session, MessageConsumer consumer, Destination destination) throws JMSException; /** * Todo. * * @param message the message */ void todo(TextMessage message); } }
package com.cienet.springBootTest.controller; import com.cienet.springBootTest.entities.User; import com.cienet.springBootTest.repositories.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping(path = "/demo") public class UserController { @Autowired private UserRepository userRepository; @GetMapping(path = "/add") public @ResponseBody String addNewUser(@RequestParam String name, @RequestParam int age) { User user = new User(); user.setName(name); user.setAge(age); userRepository.save(user); return "user " + name + ", age " + age + ", has been saved"; } @GetMapping(path = "/change") public @ResponseBody String changeUser(@RequestParam int id, @RequestParam String name, @RequestParam int age) { User user = new User(); user.setId(id); user.setName(name); user.setAge(age); user = userRepository.save(user); return user.toString() + " changed"; } @GetMapping(path = "/delete") public @ResponseBody String deleteUser(@RequestParam int id) { User user = userRepository.findById(id); userRepository.delete(user); return user.toString() + " deleted"; } @GetMapping(path = "/find") public @ResponseBody String findUser(@RequestParam int id) { User user = userRepository.findById(id); return user.toString(); } @GetMapping(path = "/all") // @RequestMapping(method = GET, path = "/all") public @ResponseBody Iterable<User> getAllUsers() { return userRepository.findAll(); } @GetMapping(path = "/nameCondFind") public @ResponseBody Iterable<User> condFind(@RequestParam String name) { return userRepository.findByNameLike(name); } @GetMapping(path = "/AgeCondFind") public @ResponseBody Iterable<User> condFind(@RequestParam int age) { return userRepository.findByAgeLessThanEqual(age); } @GetMapping(path = "/multiCondFind") public @ResponseBody Iterable<User> condFind(@RequestParam String name, @RequestParam int age) { return userRepository.findByNameContainingAndAgeGreaterThanEqualOrderByIdDesc(name, age); } }
package design.pattern.project.example.store.domain; public class StoreManagement extends Management { @Override void calculateDuration(int term) { // TODO Auto-generated method stub setDuration(term*2); } public StoreManagement(String president, String director, int duration) { super(president, director, duration); // TODO Auto-generated constructor stub } }
package zm.gov.moh.common.submodule.form.widget; import android.content.Context; import android.os.Bundle; import android.text.InputFilter; import android.util.TypedValue; import android.text.InputType; import android.view.Gravity; import android.widget.TextView; import androidx.appcompat.widget.AppCompatEditText; import androidx.appcompat.widget.AppCompatTextView; import androidx.core.util.Consumer; public class EditTextWidget extends SubmittableWidget<CharSequence> { protected String mValue; protected String mHint; protected String mLabel; protected int mTextSize; protected AppCompatEditText mEditText; protected TextView mTextView; private Context context; protected Consumer<CharSequence> mValueChangeListener; protected String dataType; public EditTextWidget(Context context) { super(context); } public void setDataType(String DataType) { this.dataType = DataType; } @Override public String getValue() { return mValue; } public void setHint(String hint) { mHint = hint; } @Override public void setValue(CharSequence value) { mBundle.putString((String) this.getTag(), value.toString()); if (mValueChangeListener != null) mValueChangeListener.accept(value); } public void setLabel(String mLabel) { this.mLabel = mLabel; } public void setOnValueChangeListener(Consumer<CharSequence> valueChangeListener) { mValueChangeListener = valueChangeListener; } public void setTextSize(int mTextSize) { this.mTextSize = mTextSize; } @Override public void setBundle(Bundle bundle) { mBundle = bundle; } @Override public void onCreateView() { if(mLabel != null) { mTextView = new AppCompatTextView(mContext); mTextView.setText(mLabel); mTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18); WidgetUtils.setLayoutParams(mTextView, WidgetUtils.WRAP_CONTENT, WidgetUtils.WRAP_CONTENT, mWeight) .setGravity(Gravity.CENTER_VERTICAL); addView(mTextView); } mEditText = new AppCompatEditText(mContext); mEditText.setHint(mHint); mEditText.addTextChangedListener(WidgetUtils.createTextWatcher(this::setValue)); mEditText.setGravity(Gravity.TOP); //auto populate if (mBundle != null) { String value = mBundle.getString((String) getTag()); if (value != null) mEditText.setText(value); } if (dataType != null && dataType.equals("Numeric")) { mEditText.setInputType(InputType.TYPE_CLASS_NUMBER); } else if (dataType != null && dataType.equals("Text")) { //auto capitalize first word in sentence mEditText.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES | InputType.TYPE_CLASS_TEXT); InputFilter filtertxt = (source, start, end, dest, dstart, dend) -> { for (int i = start; i < end; i++) { if (!Character.isLetter(source.charAt(i))) { mEditText.setError("Enter letters only"); return ""; } } return null; }; mEditText.setFilters(new InputFilter[]{filtertxt}); } mEditText.setGravity(Gravity.TOP); mEditText.setGravity(Gravity.START); WidgetUtils.setLayoutParams(mEditText, WidgetUtils.WRAP_CONTENT, WidgetUtils.WRAP_CONTENT, mWeight); addView(mEditText); } public boolean isValid(){ if(mRequired != null && mRequired) { mValue = mBundle.getString((String) getTag()); if (mValue != null && mValue.matches(mRegex)) return true; else { mEditText.setError(mErrorMessage); return false; } } else return true; } AppCompatEditText getEditTextView() { return mEditText; } public static class Builder extends SubmittableWidget.Builder{ protected String mHint; protected int mTextSize; protected String mLabel; protected String mDataType; public Builder setDataType(String dataType) { mDataType = dataType; return this; } protected Consumer<CharSequence> mValueChangeListener; public Builder(Context context) { super(context); } public Builder setHint(String hint) { mHint = hint; return this; } public Builder setLabel(String label){ mLabel = label; return this; } public Builder setTextSize(int textSize) { this.mTextSize = textSize; return this; } public Builder setOnValueChangeListener(Consumer<CharSequence> valueChangeListener) { mValueChangeListener = valueChangeListener; return this; } @Override public BaseWidget build() { EditTextWidget widget = new EditTextWidget(mContext); if (mHint != null) widget.setHint(mHint); if (mBundle != null) widget.setBundle(mBundle); if (mLabel != null) widget.setLabel(mLabel); if (mTag != null) widget.setTag(mTag); if (mDataType != null) widget.setDataType(mDataType); if (mValueChangeListener != null) widget.setOnValueChangeListener(mValueChangeListener); if(mRegex != null) widget.setRegex(mRegex); if(mErrorMessage != null) widget.setErrorMessage(mErrorMessage); if(mRequired != null) widget.setRequired(mRequired); widget.setTextSize(mTextSize); widget.onCreateView(); return widget; } } }
///* // * @Author : fengzhi // * @date : 2019 - 01 - 19 10 : 53 // * @Description : 输入一个包含八个数字的数组, // * 判断有没有可能把这八个数字分别放到正方体的八个顶点,使得正方体三组相对的面上的四个顶点的和均相等。 // * 分析:假设将a1 a2 a3 a4 a5 a6 a7 a8八个数字分别放在正方体的八个顶点上, // * 问题即转化为有没有可能存在一种组合使得,a1 + a2 + a3 + a4 = a5 + a6 + a7 + a8; // * a1 + a2 + a5 + a6 = a3 + a4 + a7 + a8; // * a2 + a3 + a6 + a7 = a1 + a4 + a5 + a8; // */ // //package problem38; // //import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ; // //import java.util.ArrayList; //import java.util.HashSet; //import java.util.Set; //import java.util.TreeSet; // //public class Solution3_unsolved { // private static void permutation(ArrayList<String> arrayList, ArrayList<ArrayList<String>> arrayList_ret) { // if (arrayList == null || arrayList.isEmpty()) // return; // HashSet<ArrayList<String>> hashSet = new HashSet<>(); // permutation(arrayList, 0, hashSet); // arrayList_ret.addAll(hashSet); // } // // // 组合 // private static void permutation(ArrayList<String> arrayList, int index, HashSet<ArrayList<String>> hashSet) { // // if (index == arrayList.size() && // (( (arrayList.get(0) + arrayList.get(1) + arrayList.get(2) + arrayList.get(3)). // equals((arrayList.get(4) + arrayList.get(5) + arrayList.get(6) + arrayList.get(7))) // ) && // ( (arrayList.get(0) + arrayList.get(1) + sb.charAt(4) + sb.charAt(5)) == // (sb.charAt(2) + sb.charAt(3) + sb.charAt(6) + sb.charAt(7)) ) && // ( (sb.charAt(1) + sb.charAt(2) + sb.charAt(5) + sb.charAt(6)) == // (sb.charAt(0) + sb.charAt(3) + sb.charAt(4) + sb.charAt(7)) ))) { // // treeSet.add(sb.toString()); // return; // } // for (int i = 0; i < sb.length(); i ++) { // swap(sb, i, index); // permutation(sb, index + 1, treeSet); // swap(sb, i, index); // } // } // private static void swap(StringBuilder sb, int i, int j) { // char c = sb.charAt(i); // sb.setCharAt(i, sb.charAt(j)); // sb.setCharAt(j, c); // } // // public static ArrayList<ArrayList<String>> isVertexOfCube(int[] ints) { // // ArrayList<ArrayList<String>> arrayLists_ret = new ArrayList<>(); // if (ints.length != 8) { // return arrayLists_ret; // } // // ArrayList<String> arrayList = new ArrayList<>(); // for (int i : ints) { // arrayList.add(String.valueOf(i)); // } // // permutation(str, arrayList); // return arrayList; // } //}
package tutorial; import java.util.ArrayList; import java.util.List; public class Spiral_Array { public ArrayList<Integer> spiralOrder(final List<ArrayList<Integer>> a) { ArrayList<Integer> result = new ArrayList<Integer>(); // Populate result; int m = a.size(), n = a.get(0).size(); System.out.println("m = " + m); System.out.println("n = " + n); System.out.println("Array : "); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { System.out.print(a.get(i).get(j)); } System.out.println(""); } int east = n - 1, south = m - 1, north = 0, west = 0, arraySize = (m * n); String last_trace = "north"; do { if (last_trace == "north") { result = trace_east(a, result, west, east, north); north++; last_trace = "east"; if (result.size() >= arraySize) break; } if (last_trace == "east") { result = trace_south(a, result, north, south, east); east--; last_trace = "south"; if (result.size() >= arraySize) break; } if (last_trace == "south") { result = trace_west(a, result, east, west, south); south--; last_trace = "west"; if (result.size() >= arraySize) break; } if (last_trace == "west") { result = trace_north(a, result, south, north, west); west++; last_trace = "north"; if (result.size() >= arraySize) break; } System.out.println("Result Size = " + result.size()); System.out.println("Array Size = " + (m * n)); } while (result.size() < m * n); return result; } private ArrayList<Integer> trace_east(List<ArrayList<Integer>> a, ArrayList<Integer> result, int start, int end, int permanent) { int val; for (int i = start; i <= end; i++) { val = a.get(permanent).get(i); result.add(val); } return result; } private ArrayList<Integer> trace_south(List<ArrayList<Integer>> a, ArrayList<Integer> result, int start, int end, int permanent) { int val; for (int i = start; i <= end; i++) { val = a.get(i).get(permanent); result.add(val); } return result; } private ArrayList<Integer> trace_west(List<ArrayList<Integer>> a, ArrayList<Integer> result, int start, int end, int permanent) { int val; for (int i = start; i >= end; i--) { val = a.get(permanent).get(i); result.add(val); } return result; } private ArrayList<Integer> trace_north(List<ArrayList<Integer>> a, ArrayList<Integer> result, int start, int end, int permanent) { int val; for (int i = start; i >= end; i--) { val = a.get(i).get(permanent); result.add(val); } return result; } }
package com.example.dilu583.flag_sys.DbHelper; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.os.Build; import android.util.Log; import com.example.dilu583.flag_sys.Common.Common; import com.example.dilu583.flag_sys.Model.Question; import com.example.dilu583.flag_sys.Model.Ranking; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; /** * Created by dilu583 on 10/24/2016. */ public class DbHelper extends SQLiteOpenHelper { private static String DB_NAME= "Mydb22.db"; private static String TAG = "DataBaseHelper"; private static String DB_PATH=""; private SQLiteDatabase mDataBase; private Context mContext = null; public DbHelper(Context context) { super(context, DB_NAME,null ,1); if(android.os.Build.VERSION.SDK_INT >= 17){ DB_PATH = context.getApplicationInfo().dataDir + "/databases/"; } else { DB_PATH = "/data/data/" + context.getPackageName() + "/databases/"; } openDataBase(); System.out.println(DB_PATH); this.mContext = context; } public boolean openDataBase() { String myPath= DB_PATH+DB_NAME; mDataBase = SQLiteDatabase.openDatabase(myPath,null,SQLiteDatabase.OPEN_READONLY); return mDataBase != null; } public void copyDataBase() throws IOException { try{ InputStream myInput = mContext.getAssets().open(DB_NAME); String outputFileName = DB_PATH + DB_NAME; OutputStream myOutput = new FileOutputStream(outputFileName); byte[] buffer = new byte[1024]; int length; while((length=myInput.read(buffer))> 0 ) myOutput.write(buffer,0,length); myOutput.flush(); myOutput.close(); myInput.close(); } catch(Exception e) { e.printStackTrace(); } } private boolean checkDataBase() { File dbFile = new File(DB_PATH + DB_NAME); //Log.v("dbFile", dbFile + " "+ dbFile.exists()); return dbFile.exists(); } public void createDataBase() throws IOException { boolean isDBExists = checkDataBase(); if(isDBExists) {} else { this.getReadableDatabase(); this.close(); try{ copyDataBase(); Log.e(TAG, "createDatabase database created"); } catch(IOException e) { e.printStackTrace(); } } } @Override public synchronized void close() { if(mDataBase!=null) mDataBase.close(); super.close(); } @Override public void onCreate(SQLiteDatabase db) { } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } public String getTablename() { SQLiteDatabase db = this.getWritableDatabase(); Cursor c; String Id = ""; try { c = db.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null); if (c == null) return null; do { String Image = c.getString(c.getColumnIndex("name")); Id += " " + Image; } while (c.moveToNext()); c.close(); } catch (Exception e) { e.printStackTrace(); } db.close(); return Id; } public List<Question> getQuestionMode(String mode) { List<Question> listQuestion = new ArrayList<>(); SQLiteDatabase db = this.getWritableDatabase(); Cursor c; int limit = 0; if(mode.equals(Common.MODE.EASY.toString())) limit =30; if(mode.equals(Common.MODE.MEDIUM.toString())) limit =50; if(mode.equals(Common.MODE.HARD.toString())) limit =100; if(mode.equals(Common.MODE.HARDEST.toString())) limit =200; try{ c=db.rawQuery(String.format("SELECT *FROM Question ORDER BY Random() LIMIT %d",limit),null); if(c==null) return null; c.moveToFirst(); do{ int Id =c.getInt(c.getColumnIndex("ID")); String Image = c.getString(c.getColumnIndex("Image")); String AnswerA = c.getString(c.getColumnIndex("AnswerA")); String AnswerB = c.getString(c.getColumnIndex("AnswerB")); String AnswerC = c.getString(c.getColumnIndex("AnswerC")); String AnswerD = c.getString(c.getColumnIndex("AnswerD")); String CorrectAnswer = c.getString(c.getColumnIndex("CorrectAnswer")); Question question = new Question(Id, Image, AnswerA, AnswerB,AnswerC,AnswerD,CorrectAnswer); listQuestion.add(question); } while(c.moveToNext()); c.close(); } catch(Exception e) { e.printStackTrace(); } db.close(); return listQuestion; } public List<Question> getAllQuestion() { List<Question> listQuestion = new ArrayList<>(); SQLiteDatabase db = this.getWritableDatabase(); Cursor c; try{ c=db.rawQuery("SELECT *FROM Question ORDER BY Random()",null); if(c==null) return null; c.moveToFirst(); do{ int Id =c.getInt(c.getColumnIndex("ID")); String Image = c.getString(c.getColumnIndex("Image")); String AnswerA = c.getString(c.getColumnIndex("AnswerA")); String AnswerB = c.getString(c.getColumnIndex("AnswerB")); String AnswerC = c.getString(c.getColumnIndex("AnswerC")); String AnswerD = c.getString(c.getColumnIndex("AnswerD")); String CorrectAnswer = c.getString(c.getColumnIndex("CorrectAnswer")); Question question = new Question(Id, Image, AnswerA, AnswerB,AnswerC,AnswerD,CorrectAnswer); listQuestion.add(question); } while(c.moveToNext()); c.close(); } catch(Exception e) { e.printStackTrace(); } db.close(); return listQuestion; } public Question getQuestion(String name) { Question question = new Question(0,"","","","","",""); SQLiteDatabase db = this.getWritableDatabase(); Cursor c; try{ c=db.rawQuery("SELECT *FROM Question WHERE CorrectAnswer = ?",new String[]{name}); if(c==null) return null; c.moveToFirst(); int Id =c.getInt(c.getColumnIndex("ID")); String Image = c.getString(c.getColumnIndex("Image")); String AnswerA = c.getString(c.getColumnIndex("AnswerA")); String AnswerB = c.getString(c.getColumnIndex("AnswerB")); String AnswerC = c.getString(c.getColumnIndex("AnswerC")); String AnswerD = c.getString(c.getColumnIndex("AnswerD")); String CorrectAnswer = c.getString(c.getColumnIndex("CorrectAnswer")); question = new Question(Id, Image, AnswerA, AnswerB,AnswerC,AnswerD,CorrectAnswer); c.close(); } catch(Exception e) { e.printStackTrace(); } db.close(); return question; } public void insetScore(int Score) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put("Score",Score); db.insert("Ranking",null,contentValues); } public List<Ranking> getRanking() { List<Ranking> listRanking = new ArrayList<>(); SQLiteDatabase db = this .getWritableDatabase(); Cursor c; try { c=db.rawQuery("SELECT * FROM Ranking ORDER BY Score DESC",null); if(c==null) return null; c.moveToNext(); do{ int Id = c.getInt(c.getColumnIndex("id")); int score = c.getInt(c.getColumnIndex("Score")); Ranking ranking = new Ranking(Id, score); listRanking.add(ranking); } while(c.moveToNext()); c.close(); } catch (Exception e) { e.printStackTrace(); } db.close(); return listRanking; } }
package myn; import java.io.*; import java.util.*; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.io.IOUtils; public class DuplicateFile { protected int dcount=0,fcount=0; protected Map<String,Vector<File>> map=new HashMap<String,Vector<File>>(); void run(File file){ sum=0;cur=0; if (!file.isDirectory()){ System.out.println("输入格式错误,请输入一个目录文件"); PALETTE.textArea.append("输入格式错误,请输入一个目录文件\n"); return; } else{ System.out.println("扫描中............"); PALETTE.textArea.append("扫描中............\n"); dfssum(file); dfs(file); PALETTE.num.setText("正在展示重复文件:"); PALETTE.textArea.setText(""); print(); PALETTE.num.setText("完成"); } return; } public int sum=0; public int cur=0; public void dfssum(File f){ if(!f.isDirectory()) sum++; else{ sum++; File[] childs = f.listFiles(); for (int i=0;i<childs.length;i++){ dfssum(childs[i]); } } } public void dfs(File f){ if(!f.isDirectory()){ FileInputStream fis; cur++; PALETTE.progressBar.setValue(cur*100/sum); PALETTE.num.setText((int)cur*100/sum+" %"); fcount++; try { fis = new FileInputStream(f.getAbsolutePath()); String md5 = DigestUtils.md5Hex(IOUtils.toByteArray(fis)); IOUtils.closeQuietly(fis); if (map.containsKey(md5)){ System.out.println("已存在md5 "+md5+" ,正在进一步比较:"); PALETTE.textArea.append("已存在md5 "+md5+" ,正在进一步比较:\n" ); Vector<File> vct = map.get(md5); File exsit=vct.get(0); if (compareFile(f,exsit)){ System.out.println("两文件相同: "+f.getAbsolutePath()+" == "+exsit.getAbsolutePath()); PALETTE.textArea.append("两文件相同: "+f.getAbsolutePath()+" == "+exsit.getAbsolutePath() +"\n"); vct.addElement(f); } else return; } else{ Vector<File> temp=new Vector<File>(); temp.add(f); map.put( md5,temp); System.out.println("记录md5-文件 : "+md5+" s "+f.getName()); PALETTE.textArea.append("记录md5-文件 : "+md5+" s "+f.getName()+"\n"); } return; }catch(Exception e){} } else{ cur++; PALETTE.progressBar.setValue(cur*100/sum); PALETTE.num.setText((int)cur*100/sum+" %"); dcount++; File[] childs = f.listFiles(); for (int i=0;i<childs.length;i++){ dfs(childs[i]); } } } public void print(){ System.out.println("-------------------------------------------"); System.out.println("扫描结束 : 共扫描"+dcount+"个目录文件, "+fcount+"个非目录文件"); System.out.println("查询结果:"); PALETTE.textArea.append("-------------------------------------------\n"); PALETTE.textArea.append("扫描结束 : 共扫描"+dcount+"个目录文件, "+fcount+"个非目录文件\n"); PALETTE.textArea.append("查询结果:\n"); int sum=0; for(Map.Entry<String, Vector<File>> f : map.entrySet()){ if(f.getValue().size()>1){ sum++; System.out.println("md5为:"+f.getKey()+"的文件共有"+f.getValue().size()+"个,展示如下:"); PALETTE.textArea.append("md5为:"+f.getKey()+"的文件共有"+f.getValue().size()+"个,展示如下:\n"); for(File o:f.getValue()){ System.out.println(o.toString()); PALETTE.textArea.append(o.toString()+"\n"); } System.out.println(""); PALETTE.textArea.append("\n"); } } System.out.println("共扫描到"+sum+"个重复文件"); PALETTE.textArea.append("共扫描到"+sum+"个重复文件"+ "\n"); } protected boolean compareFile(File file1,File file2) { try{ BufferedInputStream inFile1 = new BufferedInputStream(new FileInputStream(file1)); BufferedInputStream inFile2 = new BufferedInputStream(new FileInputStream(file2)); //比较文件的长度是否一样 if(inFile1.available() != inFile2.available()){ inFile1.close(); inFile2.close(); return false; } //比较文件的具体内容是否一样 while(inFile1.read() != -1 && inFile2.read() != -1){ if(inFile1.read() != inFile2.read()){ inFile1.close(); inFile2.close(); return false; } } inFile1.close(); inFile2.close(); return true; }catch (FileNotFoundException e){ e.printStackTrace(); return false; }catch (IOException e){ e.printStackTrace(); return false; } } }
/* Natalie Suboc * September 9, 2017 * Runner for Calculate library * Used to test the methods in Calculate */ public class DoMath { public static void main(String[] args) { //System.out.println(Calculate.absValue(-3)); //System.out.println(Calculate.cube(3)); System.out.println(Calculate.toMixedNum(1, 2)); System.out.println(Calculate.toImproperFrac(3, 1, 2)); /*System.out.println(Calculate.toImproperFrac(-3, 1, 2)); System.out.println(Calculate.average(5, -10)); System.out.println(Calculate.average(1, 2, 3)); System.out.println(Calculate.toDegrees(2 * 3.14159)); System.out.println(Calculate.toRadians(-180)); System.out.println(Calculate.discriminant(1, 4, 4)); System.out.println(Calculate.gcf(2, 1)); System.out.println(Calculate.foil(2, 3, 6, -7, "n"));*/ } }
package com.lss.atcrowdfunding.service.impl; import com.lss.atcrowdfunding.bean.TAdmin; import com.lss.atcrowdfunding.bean.TAdminExample; import com.lss.atcrowdfunding.mapper.TAdminMapper; import com.lss.atcrowdfunding.service.TAdminService; import com.lss.atcrowdfunding.util.Const; import com.lss.atcrowdfunding.util.DateUtil; import com.lss.atcrowdfunding.util.MD5Util; import com.lss.atcrowdfunding.util.StringUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service; import java.util.List; @Service public class TAdminServiceImpl implements TAdminService { @Autowired private TAdminMapper tAdminMapper; @Override public TAdmin getTAdmin(TAdmin tAdmin) { //创建查询条件 TAdminExample example = new TAdminExample(); TAdminExample.Criteria criteria=example.createCriteria(); criteria.andLoginacctEqualTo(tAdmin.getLoginacct()); criteria.andUserpswdEqualTo(MD5Util.digest(tAdmin.getUserpswd())); //把查询结果放到List集合中 List<TAdmin> tAdmins = tAdminMapper.selectByExample(example); if (tAdmins==null||tAdmins.size()==0){ throw new RuntimeException("账号或密码错误"); } return tAdmins.get(0); } @Override public List<TAdmin> listTAdminPage(String keyWord) { TAdminExample example = new TAdminExample(); if(StringUtil.isNotEmpty(keyWord)){//如果需要模糊查询 TAdminExample.Criteria criteria1 = example.createCriteria(); criteria1.andLoginacctLike("%"+keyWord+"%"); TAdminExample.Criteria criteria2 = example.createCriteria(); criteria2.andUsernameLike("%"+keyWord+"%"); TAdminExample.Criteria criteria3 = example.createCriteria(); criteria3.andEmailLike("%"+keyWord+"%"); example.or(criteria2); example.or(criteria3); } List<TAdmin> tAdmins = tAdminMapper.selectByExample(example);//查询条件之后的结果(如果没有keyWord条件查询,则为null==>查询全部) return tAdmins; } @Override public void saveTadmin(TAdmin tAdmin) { tAdmin.setUserpswd(new BCryptPasswordEncoder().encode(Const.DEFALUT_PASSWORD)); tAdmin.setCreatetime(DateUtil.getFormatTime()); tAdminMapper.insertSelective(tAdmin); } @Override public TAdmin getTAdminById(Integer id) { return tAdminMapper.selectByPrimaryKey(id); } @Override public void updateTAdmin(TAdmin tAdmin) { tAdminMapper.updateByPrimaryKeySelective(tAdmin); } @Override public void deleteTAdminById(Integer id) { tAdminMapper.deleteByPrimaryKey(id); } @Override public void deleteBath(List<Integer> idInts) { TAdminExample example = new TAdminExample(); TAdminExample.Criteria criteria = example.createCriteria(); criteria.andIdIn(idInts); tAdminMapper.deleteByExample(example); } }
/** * */ package cp120.assignments.geo_shape; import java.awt.Color; import java.awt.Graphics2D; import java.awt.geom.Line2D; /** * The GeoLine class defines a line. * * @author Jack R. Lisenko * @version 1.00, 20 November 2016 */ public class GeoLine extends GeoShape { private GeoPoint end; /** * Constructor for GeoShape. * * @param origin * @param color * @param end */ public GeoLine(GeoPoint origin, Color color, GeoPoint end) { super(origin, color); this.end = end; } /** * Constructor for GeoShape. * * @param origin * @param end */ public GeoLine(GeoPoint origin, GeoPoint end) { this(origin, DEFAULT_COLOR, end); } /* (non-Javadoc) * Method to draw the line. * @param gtx * @see cp120.assignments.geo_shape.GeoShape#draw(java.awt.Graphics2D) */ @Override public void draw(Graphics2D gtx) { String arg1 = this.toString(); String output = String.format("Drawing line: %s", arg1); System.out.println(output); float xStart = this.getOrigin().getXco(); float yStart = this.getOrigin().getYco(); float xEnd = end.getXco(); float yEnd = end.getYco(); Line2D.Double line = new Line2D.Double(xStart, yStart, xEnd, yEnd); gtx.setColor(this.getColor()); gtx.fill(line); gtx.draw(line); } /** * Returns a GeoPoint of the end of the line. * @return the end */ public GeoPoint getEnd() { return end; } /** * Set the end of the line. * @param end the end to set */ public void setEnd(GeoPoint end) { this.end = end; } /* * Returns a GeoPoint of the start of the line. * @return origin */ public GeoPoint getStart() { return super.getOrigin(); } /* * Set the start of the line. * @param origin */ public void setStart(GeoPoint origin) { super.setOrigin(origin); } /** * Returns the length of the line. * @return the length of the line */ public double length() { double distance = getStart().distance(end); return distance; } /** * Returns the slope of the line. * @return the slope of the line */ public double slope() { float xEnd = end.getXco(); float yEnd = end.getYco(); float xStart = getStart().getXco(); float yStart = getStart().getYco(); double slope = (yEnd - yStart) / (xEnd -xStart); return slope; } /* (non-Javadoc) * @see java.lang.Object#toString() * origin=(5.1,6.2),color=#ff0000,end=(-3.7,-5.4) */ @Override public String toString() { String arg1 = super.toString(); String arg2 = end.toString(); String output = String.format("%s,end=%s", arg1, arg2); return output; } }
package net.hongqianfly.decoratepattern; import android.util.Log; /** * Created by HongQian.Wang on 2017/11/2. */ public class Person implements Human { @Override public void wearClothes() { Log.e("msg","穿什么呢?"); } @Override public void walkToWhere() { Log.e("msg","去哪里呢?"); } }
package modelo.poblacion; import java.util.Random; public class Individuals { private Chromosome individuals[]; public Individuals (int population, int seed, int depthChromosome, boolean useIf, String initializationType) { this.individuals = new Chromosome[population]; //Inicializamos los terminales. Terminal [] listaterminals = new Terminal[11]; listaterminals[0] = new Terminal ("a0"); listaterminals[1] = new Terminal ("a1"); listaterminals[2] = new Terminal ("a2"); listaterminals[3] = new Terminal ("d0"); listaterminals[4] = new Terminal ("d1"); listaterminals[5] = new Terminal ("d2"); listaterminals[6] = new Terminal ("d3"); listaterminals[7] = new Terminal ("d4"); listaterminals[8] = new Terminal ("d5"); listaterminals[9] = new Terminal ("d6"); listaterminals[10] = new Terminal ("d7"); Random rnd = new Random(seed); // utilizamos la semilla para crear la poblacion inicial. Vamos pasando el objeto Random para aprovecharla. if (initializationType.equals("Ramped and half")) {// si es ramped and half tenemos que elegir entre completa o creciente. int groupMembers = population / (depthChromosome); int depth = 0; for (int i = 0; i < population; i++) {//creamos cada cromosoma pasandole el largo de cada uno de sus genes y el objeto Random if (i % groupMembers == 0) {// usamos una profundidad diferente para cada grupo. if (depth < depthChromosome) depth++; } if (i % 2 == 0) this.individuals[i] = new Chromosome(rnd, depth, useIf, "Inicializacion completa",listaterminals); else this.individuals[i] = new Chromosome(rnd, depth, useIf, "Inicializacion creciente",listaterminals); } } else { for (int i = 0; i < population; i++) {//creamos cada cromosoma pasandole el largo de cada uno de sus genes y el objeto Random this.individuals[i] = new Chromosome(rnd, depthChromosome, useIf, initializationType,listaterminals); } } } public Chromosome[] getIndividuals() { return individuals; } public void setIndividuals(Chromosome [] newpopu){ this.individuals=newpopu; } }
package com.argentinatecno.checkmanager.main.fragment_checks.di; import com.argentinatecno.checkmanager.CheckManagerAppModule; import com.argentinatecno.checkmanager.lib.di.LibsModule; import com.argentinatecno.checkmanager.main.fragment_checks.ui.FragmentChecks; import javax.inject.Singleton; import dagger.Component; @Singleton @Component(modules = {FragmentChecksModule.class, LibsModule.class, CheckManagerAppModule.class}) public interface FragmentChecksComponent { void inject(FragmentChecks fragment); }
package task111; import common.Utils; import common.Watch; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * @author Igor */ public class Main111 { private static final int N = 10; public static void main(String[] args) { Watch.start(); long sum = 0; List<Integer> specialDigits = new ArrayList<>(); for (int d = 0; d <= 9; d++) { int[] digits = new int[N]; Arrays.fill(digits, d); long dSum = 0; for (int i = 0; i <= 9; i++) if (i != d) for (int position = 0; position < N; position++) { digits[position] = i; if (possiblePrime(digits)) { long number = numberOf(digits); if (Utils.isPrime(number)) dSum += number; } digits[position] = d; } if (dSum == 0) specialDigits.add(d); sum += dSum; } for (Integer d : specialDigits) { int[] digits = new int[N]; Arrays.fill(digits, d); for (int d1 = 0; d1 <= 9; d1++) if (d1 != d) for (int d2 = 0; d2 <= 9; d2++) if (d2 != d) for (int pos1 = 0; pos1 < N; pos1++) for (int pos2 = pos1 + 1; pos2 < N; pos2++) { digits[pos1] = d1; digits[pos2] = d2; if (possiblePrime(digits)) { long number = numberOf(digits); if (Utils.isPrime(number)) sum += number; } digits[pos1] = d; digits[pos2] = d; } } System.out.println(sum); Watch.stop(); } private static long numberOf(int[] digits) { StringBuilder builder = new StringBuilder(); for (int digit : digits) builder.append(digit); return Long.valueOf(builder.toString()); } private static boolean possiblePrime(int[] digits) { if (digits[0] == 0 || digits[digits.length - 1] % 2 == 0) return false; int sum = 0; for (int digit : digits) sum += digit; return sum % 3 != 0; } }
/** * Package a ketszemelyes reversi jatekhoz. */ package reversi;
package selenium; import org.openqa.selenium.Alert; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import junit.framework.Assert; public class alerts { @SuppressWarnings("deprecation") public static void main(String[] args) throws InterruptedException { WebDriver driver; System.setProperty("webdriver.gecko.driver", "C:/Users/Nisum/Desktop/jahangir/Softwares/geckodriver.exe"); driver = new FirefoxDriver(); driver.manage().window().maximize(); driver.get("http://toolsqa.com/handling-alerts-using-selenium-webdriver/"); //This step will result in an alert on screen Thread.sleep(3000); driver.findElement(By.xpath("//button[contains(text(),'Simple Alert')]")).click(); Alert simpleAlert = driver.switchTo().alert(); String alertText = simpleAlert.getText(); System.out.println("Alert text is = " + alertText); simpleAlert.accept(); Assert.assertEquals("A simple Alert", alertText); //Once alert is present try to click on any button on the page driver.findElement(By.xpath("//button[contains(text(),'Confirm Pop up')]")).click(); Alert simple = driver.switchTo().alert(); String simple_text = simple.getText(); System.out.println("simple_text is = " + simple_text); simpleAlert.dismiss(); Assert.assertEquals("Confirm pop up with OK and Cancel button", simple_text); driver.close();}}
import java.util.*; import java.io.*; public class Zamka { public static void main(String[] args) throws IOException { Scanner nya = new Scanner(System.in); int l = nya.nextInt(); int d = nya.nextInt(); int x = nya.nextInt(); for (int i = l; i <= d; i++) { if(dsum(i) == x) { System.out.println(i); break; } } for (int i = d; i >= l; i--) { if(dsum(i) == x) { System.out.println(i); break; } } } public static int dsum(int i){ int sum = 0; while(i > 0){ sum+=i%10; i/=10; } return sum; } }
package kr.co.toondra.web.login.controller; import javax.servlet.http.HttpServletRequest; import kr.co.toondra.base.controller.BaseController; import kr.co.toondra.common.collection.PMap; import kr.co.toondra.web.login.service.LoginService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @RequestMapping("/admin/login") @Controller public class LoginController extends BaseController{ @Autowired LoginService service = new LoginService(); @RequestMapping(value = "/loginView", method = RequestMethod.GET) public String loginView(HttpServletRequest request) { if(request.getSession().getAttribute("s_manager_seq") != null){ return "redirect:/admin/"; } return "toondra/login/loginView"; } @RequestMapping(value = "/loginDo") public String login(HttpServletRequest request, Model model) throws Exception { request.getSession().invalidate(); PMap pMap = new PMap(request); model.addAttribute("result", service.login(pMap)); return JSON_VIEW; } @RequestMapping(value="/logout") public String logout(HttpServletRequest request) { request.getSession().invalidate(); return "redirect:/admin/login/loginView"; } }
package problems; import java.util.*; public class Longest_Palindromic_Substring { public static void main(String[] args) { String s="babad"; System.out.println(longestPalindrome(s)); } static boolean check_pallindrome(String s,int start,int end){ while(start<end){ if(s.charAt(start)!=s.charAt(end)){ return false; } start++; end--; } return true; } static String longestPalindrome(String s){ String ans=""; HashMap<String,Boolean>map=new HashMap<>(); for(int i=0;i<s.length();i++){ for(int j=i;j<s.length();j++){ String sub=s.substring(i,j+1); if(map.containsKey(sub)){ continue; }else{ boolean res=check_pallindrome(s, i, j); if(res){ //check if the substring is a palindrome if(ans.length()<(j-i+1)){ //check if the substring is the longest palindrome ans=sub; } } map.put(sub, res); } } } return ans; } }
package com.myapp.factory; import com.myapp.exception.InvalidShipException; import com.myapp.model.Cell; import com.myapp.model.Ship; import com.myapp.model.ShipType; import java.util.List; public class ShipFactory { public static Ship createShip(List<Cell> cells, ShipType shipType) { Ship ship = new Ship(cells, shipType); if(!ship.isValid()) throw new InvalidShipException(String.format("Invalid Ship. Cells required %s Found %s", shipType.getSize(), cells.size())); return ship; } }
package me.ljseokd.basicboard.modules.account; import me.ljseokd.basicboard.infra.MockMvcTest; import me.ljseokd.basicboard.modules.account.form.SignUpForm; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.web.servlet.MockMvc; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.authenticated; import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.unauthenticated; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; @MockMvcTest class AccountControllerTest { @Autowired MockMvc mockMvc; @Autowired AccountService accountService; @Autowired AccountRepository accountRepository; @DisplayName("회원 가입 페이지") @Test void sign_up_form() throws Exception { mockMvc.perform(get("/sign-up")) .andExpect(status().isOk()) .andExpect(view().name("sign-up")) .andDo(print()) .andExpect(unauthenticated()); } @DisplayName("회원 가입 성공") @Test void sign_up_success() throws Exception { mockMvc.perform(post("/sign-up") .param("username", "ljseokd") .param("password", "12345678") .with(csrf())) .andDo(print()) .andExpect(model().hasNoErrors()) .andExpect(status().is3xxRedirection()) .andExpect(view().name("redirect:/")) .andExpect(authenticated()) ; Account ljseokd = accountRepository.findByNickname("ljseokd").get(); Assertions.assertNotEquals("12345678",ljseokd.getPassword()); } @DisplayName("회원가입 실패 (중복된 이름)") @Test void sign_up_duplicate_fail() throws Exception { accountRepository.save(new Account("ljseokd", "12345678")); mockMvc.perform(post("/sign-up") .param("username", "ljseokd") .param("password", "12345678") .with(csrf())) .andExpect(status().isOk()) .andExpect(model().hasErrors()) .andExpect(view().name("sign-up")) .andExpect(unauthenticated()); } @DisplayName("회원가입 실패 (비밀번호 길이 부족)") @Test void sign_up_password_length_fail() throws Exception { mockMvc.perform(post("/sign-up") .param("username", "ljseokd") .param("password", "1234567") .with(csrf())) .andExpect(status().isOk()) .andExpect(model().hasErrors()) .andExpect(view().name("sign-up")) .andExpect(unauthenticated()); } @Test @DisplayName("프로필 보기 성공") void view_profile_success() throws Exception { // given SignUpForm signUpForm = new SignUpForm(); String username = "홍길동"; signUpForm.setUsername(username); signUpForm.setPassword("12341234"); accountService.join(signUpForm); // when mockMvc.perform(get("/profile/"+ username)) .andExpect(status().isOk()) .andExpect(model().attribute("isOwner", true)) .andExpect(view().name("account/profile")) .andDo(print()); } @Test @DisplayName("다른 사용자의 프로필 접근") void view_profile_non_owner() throws Exception { // given SignUpForm signUpForm = new SignUpForm(); String username = "홍길동"; signUpForm.setUsername(username); signUpForm.setPassword("12341234"); accountService.join(signUpForm); SignUpForm signUpForm2 = new SignUpForm(); String username2 = "홍길동2"; signUpForm2.setUsername(username2); signUpForm2.setPassword("123412342"); accountService.join(signUpForm2); // when mockMvc.perform(get("/profile/"+ username)) .andExpect(status().isOk()) .andExpect(model().attribute("isOwner", false)) .andExpect(view().name("account/profile")) .andDo(print()); } @Test @DisplayName("프로필 보기 잘못된 경로") void view_profile_fail() throws Exception { Assertions.assertThrows(Exception.class , () -> mockMvc.perform(get("/profile/홍길동"))); } }
package org.alienideology.jcord.event.channel.guild; import org.alienideology.jcord.handle.channel.IGuildChannel; import org.alienideology.jcord.handle.guild.IGuild; /** * @author AlienIdeology */ public interface IGuildChannelEvent { IGuild getGuild(); IGuildChannel getGuildChannel(); }
package com.tencent.mm.plugin.nearby.a; import com.tencent.mm.g.a.iq; import com.tencent.mm.g.a.jz; import com.tencent.mm.g.a.ka; import com.tencent.mm.g.a.rg; import com.tencent.mm.sdk.b.b; import com.tencent.mm.sdk.b.c; class f$5 extends c<rg> { final /* synthetic */ f lBu; f$5(f fVar) { this.lBu = fVar; this.sFo = rg.class.getName().hashCode(); } public final /* synthetic */ boolean a(b bVar) { rg rgVar = (rg) bVar; if (rgVar.cbZ.cca.equals(jz.class.getName())) { if (rgVar.cbZ.bNI == 1) { this.lBu.lBq.cbp(); } else { this.lBu.lBq.aYG(); } } else if (rgVar.cbZ.cca.equals(ka.class.getName())) { if (rgVar.cbZ.bNI == 1) { this.lBu.lBr.cbp(); } else { this.lBu.lBr.aYG(); } } else if (rgVar.cbZ.cca.equals(iq.class.getName())) { if (rgVar.cbZ.bNI == 1) { this.lBu.lBs.adc(); } else { this.lBu.lBs.unregister(); } } return false; } }
package dlsim.DLSim; import dlsim.DLSim.Util.*; import javax.swing.*; import java.awt.*; import java.awt.event.MouseEvent; /** * DLPainter: * Deals with the graphical part of a DLComponent. * @version 1.0 * @author M. Leslie */ public abstract class ComponentView extends Paintable { private ComponentModel myModel; public static Color pink=new Color(255,192,255,150); public static Color green=new Color(10,192,10,150); public ComponentView(ComponentModel m) { myModel=m; } public ComponentModel getModel() { return myModel; } public abstract void refreshTerminals(Graphics g); /** All positions are relative to the circuit */ public abstract Point getPositionOfInput(int i); /** All positions are relative to the circuit */ public abstract Point getPositionOfOutput(int i); /** Get the area contanining this output * All positions are relative to the circuit */ public abstract Shape getAreaOfOutput(int i); /** Get the area contanining this input * All positions are relative to the circuit */ public abstract Shape getAreaOfInput(int i); /** * @returns -1 if not found */ public abstract int getOutputAt(Point p); /** * @returns -1 if not found */ public abstract int getInputAt(Point p); public JPopupMenu getMenu() { return myModel.getMenu(); } /** * @param p the point to check for terminals */ public boolean isTerminalAt(Point p) { int i = getOutputAt(p); if (i!=-1) return true; i = getInputAt(p); return (i!=-1); } public void clicked(MouseEvent e) { this.getModel().getControl().Clicked(e); } }
package studio.baka.originiumcraft.client.gui; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.resources.I18n; import studio.baka.originiumcraft.util.ReferenceConsts; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiScreen; import net.minecraft.util.ResourceLocation; import java.io.IOException; public class GuiPRTSTerminal extends GuiScreen { int guiWidth = 256; int guiHeight = 144; GuiButton closeButton; @Override public void drawScreen(int mouthX, int mouthY, float partialTicks) { drawDefaultBackground(); int guiX = (width - guiWidth) / 2; int guiY = (height - guiHeight) / 2; GlStateManager.pushMatrix(); { GlStateManager.color(1, 1, 1, 1); Minecraft.getMinecraft().renderEngine.bindTexture(OCGuiResources.GUI_PRTS); drawTexturedModalRect(guiX, guiY, 0, 0, guiWidth, guiHeight); } GlStateManager.popMatrix(); closeButton.draw(mouthX, mouthY); drawCenteredString(fontRenderer, I18n.format("gui.prts_terminal.title"), width / 2, guiY + 5, 0x000000); super.drawScreen(mouthX, mouthY, partialTicks); } @Override protected void mouseClicked(int mouseX, int mouseY, int mouseButton) throws IOException { closeButton.parentClicked(mouseX, mouseY); super.mouseClicked(mouseX, mouseY, mouseButton); } @Override public void initGui() { // init buttons closeButton = new studio.baka.originiumcraft.client.gui.GuiButton( this, (width + guiWidth) / 2 - 8, (height - guiHeight) / 2, 8, 8 ); closeButton.init( OCGuiResources.GUI_PRTS, 0, 144, 8, 144 ); closeButton.setClickedExecution(() -> { Minecraft.getMinecraft().displayGuiScreen(null); }); super.initGui(); } @Override protected void keyTyped(char typedChar, int keyCode) throws IOException { super.keyTyped(typedChar, keyCode); } @Override public boolean doesGuiPauseGame() { return false; } @Override public void onGuiClosed() { super.onGuiClosed(); } }
package com.eb.controller; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.eb.dao.CalBoardDAO; import com.eb.dto.CalBoardDTO; import com.eb.service.CalBoardService; import com.lol.comm.Action; import com.lol.comm.ForwardAction; public class EBListAction implements Action { @Override public ForwardAction execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { CalBoardService service=CalBoardService.getService(); List<CalBoardDTO> list=service.list(); request.setAttribute("list", list); ForwardAction forward=new ForwardAction(); forward.setForward(true); forward.setUrl("main.jsp?page=calboard/CALList.jsp"); return forward; } }
package com.lnpc.common.utils; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Serializable; import java.io.UnsupportedEncodingException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 文件操作类 * * @author changjq * */ public class FileUtils { private static Logger logger = LoggerFactory.getLogger(FileUtils.class); /** * 判断文件是否存在 * * @param file * @return true 存在;false 不存在 */ public static boolean isExistFile(String file) { return (new File(file)).exists(); } /** * 获取文件最后保存时间 * * @param file * @return 文件modified */ public static long getLastModified(String file) { return new File(file).lastModified(); } /** * 读取文件 * * @param file * @return 文件内容 * @throws Exception */ public static String readFile(String file) throws Exception { File f = new File(file); if (f.exists()) { FileInputStream fis = new FileInputStream(f); int size = fis.available(); if (size < 1 * 1024 * 1024) { logger.info("The files's size is {}",size); byte[] buffer = new byte[size]; int readLength = fis.read(buffer); fis.close(); return new String(buffer, 0, readLength); } else { fis.close(); logger.error("The File is too large!"); return null; } } else { logger.error("The File does not exist!"); return null; } } /** * 拷贝文件 * * @param is * @param os */ public static void copyFile(InputStream is, OutputStream os) { BufferedInputStream bis = null; BufferedOutputStream bos = null; try { bis = new BufferedInputStream(is); bos = new BufferedOutputStream(os); int len = 0; byte[] bytes = new byte[1024 * 2]; while ((len = bis.read(bytes)) != -1) { bos.write(bytes, 0, len); } bos.flush(); } catch (FileNotFoundException e) { logger.error("The source file does not exists..."); e.printStackTrace(); } catch (IOException e) { logger.error("Error occurs when copy file..."); e.printStackTrace(); } finally { if (bis != null) { try { bis.close(); } catch (IOException e) { logger.error("Error occurs when close inputstream..."); e.printStackTrace(); } } if (bos != null) { try { bos.close(); } catch (IOException e) { logger.error("Error occurs when close outputstream..."); e.printStackTrace(); } } } } /** * 文件重命名 * * @param srcFile * @param desFile * @return true 成功;false 失败 */ public static boolean renameFile(String srcFile, String desFile) { File src = new File(srcFile); File des = new File(desFile); return src.renameTo(des); } /** * 拷贝文件 * * @param srcFilePath * @param desFilePath */ public static void copyFile(String srcFilePath, String desFilePath) { File scrFile = new File(srcFilePath); if (scrFile.exists()) { File desFile = new File(desFilePath); if (scrFile.isFile()) { try { copyFile(new FileInputStream(scrFile), new FileOutputStream(desFile)); } catch (FileNotFoundException e) { logger.error("The source file does not exist..."); e.printStackTrace(); } } else if (scrFile.isDirectory()) { copyDirectiory(srcFilePath, desFilePath); } } else { } } /** * 拷贝文件夹 * * @param sourceDir * @param targetDir */ public static void copyDirectiory(String sourceDir, String targetDir) { (new File(targetDir)).mkdirs(); File[] file = (new File(sourceDir)).listFiles(); for (int i = 0; i < file.length; i++) { if (file[i].isFile()) { File sourceFile = file[i]; File targetFile = new File(new File(targetDir).getAbsolutePath() + File.separator + file[i].getName()); try { copyFile(new FileInputStream(sourceFile), new FileOutputStream(targetFile)); } catch (FileNotFoundException e) { logger.error("The source Directiory does not exist..."); e.printStackTrace(); } } if (file[i].isDirectory()) { String dir1 = sourceDir + "/" + file[i].getName(); String dir2 = targetDir + "/" + file[i].getName(); copyDirectiory(dir1, dir2); } } } /** * 写文件 UTF8编码 * * @param fileName * 文件路径 * @param fileContent * 文件内容 */ public static void write(String fileName, String fileContent) { write(fileName, fileContent, "UTF-8"); } /** * 写文件 * * @param fileName * 文件路径 * @param fileContent * 文件内容 * @param encoding * 编码 */ public static void write(String fileName, String fileContent, String encoding) { FileOutputStream fos = null; OutputStreamWriter osw = null; try { fos = new FileOutputStream(fileName); osw = new OutputStreamWriter(fos, encoding); osw.write(fileContent); osw.flush(); } catch (FileNotFoundException e) { logger.error("The file does not exist..."); e.printStackTrace(); } catch (UnsupportedEncodingException e1) { logger.error("Error occurs when write file..."); e1.printStackTrace(); } catch (IOException e) { logger.error("Error occurs when write file..."); e.printStackTrace(); } finally { if (fos != null) { try { fos.close(); fos = null; } catch (IOException e) { logger.error("Error occurs when close stream..."); e.printStackTrace(); } } if (osw != null) { try { osw.close(); } catch (IOException e) { logger.error("Error occurs when close stream..."); e.printStackTrace(); } } } } /** * 删除单一文件 * * @param filePath */ public static void deleteSingleFile(String filePath) { File f = new File(filePath); if (f.exists()) { f.delete(); } } /** * 删除文件或文件夹 * * @param path */ public static void deleteFile(String path) { File f = new File(path); if (!f.exists()) { return; } if (f.isFile()) { deleteSingleFile(path); } else { deleteDirectory(path); } } /** * 删除文件夹 * * @param path */ private static void deleteDirectory(String path) { String dirPath = path; if (!dirPath.endsWith(File.separator)) { dirPath = dirPath + File.separator; } File file = new File(dirPath); if (!file.isDirectory()) { return; } File[] files = file.listFiles(); for (int i = 0; i < files.length; i++) { deleteFile(files[i].getAbsolutePath()); } file.delete(); } /** * 创建文件夹 * * @param filePath */ public static void makeDir(String filePath) { File f = new File(filePath); if (!f.exists()) { f.mkdirs(); } } /** * 获取文件名 * * @author changjq * @date 2015年6月5日 * @param filePath * 文件路径 * @return 文件名 */ public static String getFileNameByPath(String filePath) { String name = ""; if (filePath != null && !"".equals(filePath)) { int pos = filePath.lastIndexOf(File.separator); name = filePath.substring(pos + 1); } return name; } /** * 序列化到指定文件 * * @author changjq * @date 2014年12月2日 * @param filePath * 文件路径 * @param obj * 待写入的对象 */ public static void serializeToFile(String filePath, Object obj) { if (obj instanceof Serializable) { try { FileOutputStream fos = new FileOutputStream(filePath); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(obj); oos.flush(); oos.close(); fos.close(); } catch (FileNotFoundException e) { logger.error("The source file does not exists..."); e.printStackTrace(); } catch (IOException e) { logger.error("Error occurs when serializeToFile..."); e.printStackTrace(); } } } /** * 反序列化 * * @author changjq * @date 2014年12月2日 * @param filePath * @return specified对象 */ public static Object deserialize(String filePath) { Object retObj = null; if(new File(filePath).exists()){ ObjectInputStream ois = null; FileInputStream fis = null; try { fis = new FileInputStream(filePath); ois = new ObjectInputStream(fis); retObj = ois.readObject(); } catch (IOException e) { logger.error("Error occurs when deserialize..."); logger.error("The filepath is:"+filePath); e.printStackTrace(); } catch (ClassNotFoundException e) { logger.error("Error occurs when readObject..."); e.printStackTrace(); } finally { try { ois.close(); fis.close(); } catch (IOException e) { e.printStackTrace(); } } } return retObj; } }
package ru.android.messenger.model.utils.http; import java.util.List; import ru.android.messenger.model.dto.Dialog; public interface OnDialogsListLoadedListener { void onDialogListLoadedListener(List<Dialog> dialogList); }
package com.gokuai.base; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.core.appender.ConsoleAppender; import org.apache.logging.log4j.core.config.Configurator; import org.apache.logging.log4j.core.config.builder.api.*; import org.apache.logging.log4j.core.config.builder.impl.BuiltConfiguration; import static com.gokuai.base.DebugConfig.*; /** * 输出日志 System.out.println */ public class LogPrint { private static final String TAG = "LogPrint"; public static final String INFO = "info"; public static final String ERROR = "error"; public static final String WARN = "warn"; private static DebugConfig.LogDetector mDetector; public static void setLogDetector(DebugConfig.LogDetector detector) { mDetector = detector; } static { logConfiguration(); } /** * 打印 INFO 级别以下的日志 * * @param logTag * @param log */ public static void info(String logTag, String log) { print(logTag, INFO, log); } /** * 打印 ERROR 级别以下的日志 * * @param logTag * @param log */ public static void error(String logTag, String log) { print(logTag, ERROR, log); } /** * 打印 WARN 级别以下的日志 * * @param logTag * @param log */ public static void warn(String logTag, String log) { print(logTag, WARN, log); } private static void print(String logTag, String level, String log) { if (DebugConfig.PRINT_LOG) { Logger logger = LogManager.getLogger(logTag); switch (level) { case INFO: logger.info(log); break; case ERROR: logger.error(log); break; case WARN: logger.warn(log); break; } if (PRINT_LOG_TYPE == LOG_TYPE_DETECTOR) { if (mDetector != null) { mDetector.getLog(level, log); } else { print(TAG, ERROR, "DebugConfig.setListener should call when PRINT_LOG_TYPE=LOG_TYPE_DETECTOR"); } } } } /** * 日志打印配置信息 */ private static void logConfiguration() { if (DebugConfig.PRINT_LOG) { ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory.newConfigurationBuilder(); builder.setStatusLevel(org.apache.logging.log4j.Level.INFO); builder.setConfigurationName("RollingBuilder"); AppenderComponentBuilder appenderBuilder = builder.newAppender("Stdout", "CONSOLE") .addAttribute("target", ConsoleAppender.Target.SYSTEM_OUT); appenderBuilder.add(builder.newLayout("PatternLayout") .addAttribute("pattern", LOG_PRINT_PATTERN)); builder.add(appenderBuilder); switch (PRINT_LOG_TYPE) { case PRINT_LOG_TO_CONSOLE: builder.add(builder.newLogger("YunKuJavaSDK", org.apache.logging.log4j.Level.INFO) .add(builder.newAppenderRef("Stdout"))); builder.add(builder.newRootLogger(org.apache.logging.log4j.Level.INFO) .add(builder.newAppenderRef("Stdout"))); Configurator.initialize(builder.build()); break; case PRINT_LOG_IN_FILE: LayoutComponentBuilder layoutBuilder = builder.newLayout("PatternLayout") .addAttribute("pattern", LOG_PRINT_PATTERN); ComponentBuilder triggeringPolicy = builder.newComponent("Policies") .addComponent(builder.newComponent("CronTriggeringPolicy").addAttribute("schedule", "0 0 0 * * ?")) .addComponent(builder.newComponent("SizeBasedTriggeringPolicy").addAttribute("size", PRINT_LOG_FILE_SIZE)); ComponentBuilder defaultRolloverStrategy = builder.newComponent("DefaultRolloverStrategy") .addAttribute("fileIndex", "min") .addAttribute("min", 1) .addAttribute("max", 1024); appenderBuilder = builder.newAppender("rolling", "RollingFile") .addAttribute("fileName", LOG_PATH + "YunkuJavaSDK.log") .addAttribute("filePattern", LOG_PATH + "YunkuJavaSDK-%d{yyyy-MM}-%i.log") .add(layoutBuilder) .addComponent(triggeringPolicy) .addComponent(defaultRolloverStrategy); builder.add(appenderBuilder); builder.add(builder.newLogger("YunKuJavaSDK", org.apache.logging.log4j.Level.INFO) .add(builder.newAppenderRef("Stdout")) .add(builder.newAppenderRef("rolling")) .addAttribute("additivity", false)); builder.add(builder.newRootLogger(org.apache.logging.log4j.Level.INFO) .add(builder.newAppenderRef("Stdout")) .add(builder.newAppenderRef("rolling"))); Configurator.initialize(builder.build()); break; } } } }
package com.tencent.mm.ui.widget; import android.annotation.TargetApi; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.ColorFilter; import android.graphics.Matrix; import android.graphics.Matrix.ScaleToFit; import android.graphics.Paint; import android.graphics.PaintFlagsDrawFilter; import android.graphics.PorterDuff.Mode; import android.graphics.PorterDuffColorFilter; import android.graphics.RectF; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.graphics.drawable.PictureDrawable; import android.net.Uri; import android.util.AttributeSet; import android.view.View; import android.view.View.MeasureSpec; import android.widget.RemoteViews.RemoteView; import com.tencent.mm.sdk.platformtools.x; @RemoteView public class QImageView extends View { private static final a[] uHJ = new a[]{a.MATRIX, a.FIT_XY, a.FIT_START, a.FIT_CENTER, a.FIT_END, a.CENTER, a.CENTER_CROP, a.CENTER_INSIDE}; private static final ScaleToFit[] uHK = new ScaleToFit[]{ScaleToFit.FILL, ScaleToFit.START, ScaleToFit.CENTER, ScaleToFit.END}; private int AA; private boolean OQ; private Uri aMJ; private int gg; private ColorFilter jN; private Context mContext; private Drawable mDrawable; private Matrix mMatrix; private int qMj; private int[] uHA; private boolean uHB; private int uHC; private int uHD; private int uHE; private Matrix uHF; private final RectF uHG; private final RectF uHH; private boolean uHI; private int uHu; private a uHv; private boolean uHw; private boolean uHx; private int uHy; private boolean uHz; public enum a { MATRIX(0), FIT_XY(1), FIT_START(2), FIT_CENTER(3), FIT_END(4), CENTER(5), CENTER_CROP(6), CENTER_INSIDE(7); final int uHT; private a(int i) { this.uHT = i; } } public QImageView(Context context, AttributeSet attributeSet) { this(context, attributeSet, 0); this.mContext = context; cAA(); } public QImageView(Context context, AttributeSet attributeSet, int i) { super(context, attributeSet, i); this.uHu = 0; this.uHw = false; this.uHx = false; this.gg = Integer.MAX_VALUE; this.qMj = Integer.MAX_VALUE; this.AA = 255; this.uHy = 256; this.uHz = false; this.mDrawable = null; this.uHA = null; this.uHB = false; this.uHC = 0; this.uHF = null; this.uHG = new RectF(); this.uHH = new RectF(); this.OQ = false; this.mContext = context; cAA(); this.OQ = false; setAdjustViewBounds(false); setMaxWidth(Integer.MAX_VALUE); setMaxHeight(Integer.MAX_VALUE); this.uHI = false; } private void cAA() { this.mMatrix = new Matrix(); this.uHv = a.FIT_CENTER; } protected boolean verifyDrawable(Drawable drawable) { return this.mDrawable == drawable || super.verifyDrawable(drawable); } public void invalidateDrawable(Drawable drawable) { if (drawable == this.mDrawable) { invalidate(); } else { super.invalidateDrawable(drawable); } } protected boolean onSetAlpha(int i) { if (getBackground() != null) { return false; } int i2 = (i >> 7) + i; if (this.uHy == i2) { return true; } this.uHy = i2; this.uHz = true; cAE(); return true; } public void setAdjustViewBounds(boolean z) { this.uHx = z; if (z) { setScaleType(a.FIT_CENTER); } } public void setMaxWidth(int i) { this.gg = i; } public void setMaxHeight(int i) { this.qMj = i; } public Drawable getDrawable() { return this.mDrawable; } public void setImageResource(int i) { if (this.aMJ != null || this.uHu != i) { u(null); this.uHu = i; this.aMJ = null; cAB(); invalidate(); } } @TargetApi(11) public void setLayerType(int i, Paint paint) { if (!(getDrawable() instanceof PictureDrawable) || i == 1) { super.setLayerType(i, paint); } } public void setImageURI(Uri uri) { if (this.uHu == 0) { if (this.aMJ == uri) { return; } if (!(uri == null || this.aMJ == null || !uri.equals(this.aMJ))) { return; } } u(null); this.uHu = 0; this.aMJ = uri; cAB(); invalidate(); } public void setImageDrawable(Drawable drawable) { if (this.mDrawable != drawable) { this.uHu = 0; this.aMJ = null; u(drawable); invalidate(); } } public void setBackgroundDrawable(Drawable drawable) { super.setBackgroundDrawable(drawable); } public void setImageBitmap(Bitmap bitmap) { setImageDrawable(new BitmapDrawable(this.mContext.getResources(), bitmap)); } private void cAB() { Drawable drawable = null; if (this.mDrawable == null) { Resources resources = getResources(); if (resources != null) { if (this.uHu != 0) { try { drawable = resources.getDrawable(this.uHu); } catch (Exception e) { x.w("ImageView", "Unable to find resource: " + this.uHu, new Object[]{e}); this.aMJ = drawable; } } else if (this.aMJ == null) { return; } u(drawable); } } } public void setSelected(boolean z) { super.setSelected(z); cAC(); } public void setImageLevel(int i) { this.uHC = i; if (this.mDrawable != null) { this.mDrawable.setLevel(i); cAC(); } } public void setScaleType(a aVar) { if (aVar == null) { throw new NullPointerException(); } else if (this.uHv != aVar) { this.uHv = aVar; setWillNotCacheDrawing(this.uHv == a.CENTER); requestLayout(); invalidate(); } } public a getScaleType() { return this.uHv; } public Matrix getImageMatrix() { return this.mMatrix; } public void setImageMatrix(Matrix matrix) { if (matrix != null && matrix.isIdentity()) { matrix = null; } if ((matrix == null && !this.mMatrix.isIdentity()) || (matrix != null && !this.mMatrix.equals(matrix))) { this.mMatrix.set(matrix); cAD(); invalidate(); } } public int[] onCreateDrawableState(int i) { if (this.uHA == null) { return super.onCreateDrawableState(i); } if (this.uHB) { return mergeDrawableStates(super.onCreateDrawableState(this.uHA.length + i), this.uHA); } return this.uHA; } private void u(Drawable drawable) { if (this.mDrawable != null) { this.mDrawable.setCallback(null); unscheduleDrawable(this.mDrawable); } this.mDrawable = drawable; if (drawable != null) { drawable.setCallback(this); if (drawable.isStateful()) { drawable.setState(getDrawableState()); } drawable.setLevel(this.uHC); this.uHD = drawable.getIntrinsicWidth(); this.uHE = drawable.getIntrinsicHeight(); cAE(); cAD(); } } private void cAC() { Drawable drawable = this.mDrawable; if (drawable != null) { int intrinsicWidth = drawable.getIntrinsicWidth(); if (intrinsicWidth < 0) { intrinsicWidth = this.uHD; } int intrinsicHeight = drawable.getIntrinsicHeight(); if (intrinsicHeight < 0) { intrinsicHeight = this.uHE; } if (intrinsicWidth != this.uHD || intrinsicHeight != this.uHE) { this.uHD = intrinsicWidth; this.uHE = intrinsicHeight; requestLayout(); } } } public void onMeasure(int i, int i2) { int i3; int i4; int i5; int mode; cAB(); float f = 0.0f; Object obj = null; Object obj2 = null; if (this.mDrawable == null) { this.uHD = -1; this.uHE = -1; i3 = 0; i4 = 0; } else { i5 = this.uHD; i3 = this.uHE; if (i5 <= 0) { i5 = 1; } if (i3 <= 0) { i3 = 1; } if (this.uHx) { mode = MeasureSpec.getMode(i); int mode2 = MeasureSpec.getMode(i2); obj = mode != 1073741824 ? 1 : null; obj2 = mode2 != 1073741824 ? 1 : null; f = ((float) i5) / ((float) i3); i4 = i5; } else { i4 = i5; } } int paddingLeft = getPaddingLeft(); int paddingRight = getPaddingRight(); int paddingTop = getPaddingTop(); int paddingBottom = getPaddingBottom(); if (obj == null && obj2 == null) { i3 += paddingTop + paddingBottom; mode = Math.max((paddingLeft + paddingRight) + i4, getSuggestedMinimumWidth()); i3 = Math.max(i3, getSuggestedMinimumHeight()); mode = resolveSize(mode, i); i3 = resolveSize(i3, i2); } else { i4 = am((i4 + paddingLeft) + paddingRight, this.gg, i); i5 = am((i3 + paddingTop) + paddingBottom, this.qMj, i2); if (f == 0.0f || ((double) Math.abs((((float) ((i4 - paddingLeft) - paddingRight)) / ((float) ((i5 - paddingTop) - paddingBottom))) - f)) <= 1.0E-7d) { i3 = i5; mode = i4; } else { int i6; Object obj3 = null; if (obj != null) { i6 = (((int) (((float) ((i5 - paddingTop) - paddingBottom)) * f)) + paddingLeft) + paddingRight; if (i6 <= i4) { obj3 = 1; if (obj3 == null && obj2 != null) { i3 = (((int) (((float) ((i6 - paddingLeft) - paddingRight)) / f)) + paddingTop) + paddingBottom; if (i3 <= i5) { mode = i6; } } i3 = i5; mode = i6; } } i6 = i4; i3 = (((int) (((float) ((i6 - paddingLeft) - paddingRight)) / f)) + paddingTop) + paddingBottom; if (i3 <= i5) { mode = i6; } i3 = i5; mode = i6; } } setMeasuredDimension(mode, i3); } private static int am(int i, int i2, int i3) { int mode = MeasureSpec.getMode(i3); int size = MeasureSpec.getSize(i3); switch (mode) { case Integer.MIN_VALUE: return Math.min(Math.min(i, size), i2); case 0: return Math.min(i, i2); case 1073741824: return size; default: return i; } } public void onLayout(boolean z, int i, int i2, int i3, int i4) { this.uHw = true; cAD(); } private void cAD() { if (this.mDrawable != null && this.uHw) { int i = this.uHD; int i2 = this.uHE; int width = (getWidth() - getPaddingLeft()) - getPaddingRight(); int height = (getHeight() - getPaddingTop()) - getPaddingBottom(); int i3 = ((i < 0 || width == i) && (i2 < 0 || height == i2)) ? 1 : 0; if (i <= 0 || i2 <= 0 || a.FIT_XY == this.uHv) { this.mDrawable.setBounds(0, 0, width, height); this.uHF = null; return; } this.mDrawable.setBounds(0, 0, i, i2); float f; float f2; if (a.MATRIX == this.uHv) { if (this.mMatrix.isIdentity()) { this.uHF = null; } else { this.uHF = this.mMatrix; } } else if (i3 != 0) { this.uHF = null; } else if (a.CENTER == this.uHv) { this.uHF = this.mMatrix; this.uHF.setTranslate((float) ((int) ((((float) (width - i)) * 0.5f) + 0.5f)), (float) ((int) ((((float) (height - i2)) * 0.5f) + 0.5f))); } else if (a.CENTER_CROP == this.uHv) { float f3; this.uHF = this.mMatrix; if (i * height > width * i2) { f3 = ((float) height) / ((float) i2); f = (((float) width) - (((float) i) * f3)) * 0.5f; f2 = 0.0f; } else { f3 = ((float) width) / ((float) i); f2 = (((float) height) - (((float) i2) * f3)) * 0.5f; f = 0.0f; } this.uHF.setScale(f3, f3); this.uHF.postTranslate((float) ((int) (f + 0.5f)), (float) ((int) (f2 + 0.5f))); } else if (a.CENTER_INSIDE == this.uHv) { this.uHF = this.mMatrix; if (i > width || i2 > height) { f2 = Math.min(((float) width) / ((float) i), ((float) height) / ((float) i2)); } else { f2 = 1.0f; } float f4 = (float) ((int) (((((float) width) - (((float) i) * f2)) * 0.5f) + 0.5f)); f = (float) ((int) (((((float) height) - (((float) i2) * f2)) * 0.5f) + 0.5f)); this.uHF.setScale(f2, f2); this.uHF.postTranslate(f4, f); } else { this.uHG.set(0.0f, 0.0f, (float) i, (float) i2); this.uHH.set(0.0f, 0.0f, (float) width, (float) height); this.uHF = this.mMatrix; this.uHF.setRectToRect(this.uHG, this.uHH, uHK[this.uHv.uHT - 1]); } } } protected void drawableStateChanged() { super.drawableStateChanged(); Drawable drawable = this.mDrawable; if (drawable != null && drawable.isStateful()) { drawable.setState(getDrawableState()); } } public void onDraw(Canvas canvas) { canvas.setDrawFilter(new PaintFlagsDrawFilter(0, 3)); super.onDraw(canvas); if (this.mDrawable != null && this.uHD != 0 && this.uHE != 0) { if (this.uHF == null && getPaddingTop() == 0 && getPaddingLeft() == 0) { this.mDrawable.draw(canvas); return; } int saveCount = canvas.getSaveCount(); canvas.save(); if (this.uHI) { int scrollX = getScrollX(); int scrollY = getScrollY(); canvas.clipRect(getPaddingLeft() + scrollX, getPaddingTop() + scrollY, ((scrollX + getRight()) - getLeft()) - getPaddingRight(), ((scrollY + getBottom()) - getTop()) - getPaddingBottom()); } canvas.translate((float) getPaddingLeft(), (float) getPaddingTop()); if (this.uHF != null) { canvas.concat(this.uHF); } this.mDrawable.draw(canvas); canvas.restoreToCount(saveCount); } } public int getBaseline() { return this.OQ ? getMeasuredHeight() : -1; } public final void setColorFilter(int i) { setColorFilter(new PorterDuffColorFilter(i, Mode.SRC_ATOP)); } public void setColorFilter(ColorFilter colorFilter) { if (this.jN != colorFilter) { this.jN = colorFilter; this.uHz = true; cAE(); invalidate(); } } public void setAlpha(int i) { int i2 = i & 255; if (this.AA != i2) { this.AA = i2; this.uHz = true; cAE(); invalidate(); } } private void cAE() { if (this.mDrawable != null && this.uHz) { this.mDrawable = this.mDrawable.mutate(); this.mDrawable.setColorFilter(this.jN); this.mDrawable.setAlpha((this.AA * this.uHy) >> 8); } } public void onDetachedFromWindow() { super.onDetachedFromWindow(); } }
package p3.control; import java.util.*; import p3.logic.game.*; import p3.Exceptions.*; /** Class "Controller": * * Controls the execution of the game. * Receives the commands from the user and executes the corresponding actions, calls for the updates of the board and prints the game. * * */ public class Controller { private Game game; private Scanner in; private Boolean print; private Boolean exit; private Boolean update; private Command command; private GamePrinter GPrinter; /** Receives the game and assigns the default values for the control variables of the game */ public Controller(Game game) { this.game = game; this.in = new Scanner(System.in); this.print = true; this.exit = false; this.update = true; this.GPrinter = new ReleasePrinter(); this.game.setController(this); } /** Receives the command input, calls for the parse of the command and checks if it is a valid input. Then executes the corresponding actions * May or may not print & update the game * Checks if the game keeps going or is ended * */ public void Run () { String[] command; this.game.update(); printGame(this.game); do { System.out.print("Command > "); this.print = true; this.update = true; command = in.nextLine().trim().toLowerCase().split("\\s+"); try { this.command = CommandParser.parseCommand(command); this.command.execute(this.game); if (this.update) this.game.update(); if (this.print) printGame(this.game); if (!exit) exit = game.endGame(); } catch (CommandParseException | CommandExecuteException | NumberFormatException ex) { System.out.format(ex.getMessage() + "%n%n"); } } while (!exit); } /** Calls for the game print */ public void printGame(Game game) { this.GPrinter.printGame(this.game); } /** Avoids printing the game this turn */ public void setNoPrintGameState() { this.print = false; } /** Avoids updating the game this turn */ public void setNoUpdateGameState() { this.update = false; } /** Receives the desired printing mode and assigns the new GamePrinter * @throws CommandExecuteException */ public void setPrintMode(String mode) throws CommandExecuteException { switch (mode) { case "debug": case "d": this.GPrinter = new DebugPrinter(); break; case "release": case "r": this.GPrinter = new ReleasePrinter(); break; default: throw new CommandExecuteException("[ERROR]: Unknown print mode. Avaliable modes are < release (r) | debug (d) >.\n"); } } /** Ends the game */ public void exit () { this.exit = true; } }
package kodlamaio.hrms.core.verifications; public interface VerificationService { void sendEmail(String email,String code); }
public class NBody { public static double readRadius(String planetFile) { In in = new In(planetFile); int numPlanet = in.readInt(); double radius = in.readDouble(); return radius; } public static Body[] readBodies(String planetFile) { In in = new In(planetFile); int numPlanet = in.readInt(); double radius = in.readDouble(); Body[] bodies = new Body[numPlanet]; for (int i = 0; i < numPlanet; i++) { bodies[i] = new Body(in.readDouble(), in.readDouble(), in.readDouble(), in.readDouble(), in.readDouble(), in.readString()); } return bodies; } public static void main(String[] args) { double T = Double.parseDouble(args[0]); double dt = Double.parseDouble(args[1]); double t = 0.0; String filename = args[2]; double radius = readRadius(filename); Body[] bodies = readBodies(filename); int numPlanet = bodies.length; String backImg = "./images/starfield.jpg"; StdDraw.enableDoubleBuffering(); StdDraw.setScale(-radius, radius); double[] xForce = new double[numPlanet]; double[] yForce = new double[numPlanet]; while (t <= T) { for (int i = 0; i < numPlanet; i++) { xForce[i] = bodies[i].calcNetForceExertedByX(bodies); yForce[i] = bodies[i].calcNetForceExertedByY(bodies); } for (int i = 0; i < numPlanet; i++) { bodies[i].update(dt, xForce[i], yForce[i]); } StdDraw.clear(); StdDraw.picture(0, 0, backImg); for (int i = 0; i < bodies.length; i++) { bodies[i].draw(); } StdDraw.show(); StdDraw.pause(10); t += dt; } } }
/** * OpenKM, Open Document Management System (http://www.openkm.com) * Copyright (c) 2006-2015 Paco Avila & Josep Llort * * No bytes were intentionally harmed during the development of this application. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package com.openkm.module.jcr; import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.Map; import javax.jcr.Session; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.openkm.bean.form.FormElement; import com.openkm.bean.workflow.ProcessDefinition; import com.openkm.bean.workflow.ProcessInstance; import com.openkm.bean.workflow.TaskInstance; import com.openkm.bean.workflow.Token; import com.openkm.core.DatabaseException; import com.openkm.core.ParseException; import com.openkm.core.RepositoryException; import com.openkm.core.WorkflowException; import com.openkm.module.WorkflowModule; import com.openkm.module.common.CommonWorkflowModule; import com.openkm.module.jcr.stuff.JCRUtils; import com.openkm.module.jcr.stuff.JcrSessionManager; import com.openkm.util.UserActivity; public class JcrWorkflowModule implements WorkflowModule { private static Logger log = LoggerFactory.getLogger(JcrWorkflowModule.class); @Override public void registerProcessDefinition(String token, InputStream is) throws ParseException, RepositoryException, WorkflowException, DatabaseException, IOException { log.debug("registerProcessDefinition({}, {})", token, is); Session session = null; try { if (token == null) { session = JCRUtils.getSession(); } else { session = JcrSessionManager.getInstance().get(token); } CommonWorkflowModule.registerProcessDefinition(is); // Activity log UserActivity.log(session.getUserID(), "REGISTER_PROCESS_DEFINITION", null, null, null); } catch (javax.jcr.RepositoryException e) { throw new RepositoryException(e.getMessage(), e); } finally { if (token == null) { JCRUtils.logout(session); } } log.debug("registerProcessDefinition: void"); } @Override public void deleteProcessDefinition(String token, long processDefinitionId) throws RepositoryException, DatabaseException, WorkflowException { log.debug("deleteProcessDefinition({}, {})", token, processDefinitionId); Session session = null; try { if (token == null) { session = JCRUtils.getSession(); } else { session = JcrSessionManager.getInstance().get(token); } CommonWorkflowModule.deleteProcessDefinition(processDefinitionId); // Activity log UserActivity.log(session.getUserID(), "DELETE_PROCESS_DEFINITION", "" + processDefinitionId, null, null); } catch (javax.jcr.RepositoryException e) { throw new RepositoryException(e.getMessage(), e); } finally { if (token == null) { JCRUtils.logout(session); } } log.debug("deleteProcessDefinition: void"); } @Override public ProcessDefinition getProcessDefinition(String token, long processDefinitionId) throws RepositoryException, DatabaseException, WorkflowException { log.debug("getProcessDefinition({}, {})", token, processDefinitionId); ProcessDefinition vo = null; Session session = null; try { if (token == null) { session = JCRUtils.getSession(); } else { session = JcrSessionManager.getInstance().get(token); } vo = CommonWorkflowModule.getProcessDefinition(processDefinitionId); // Activity log UserActivity.log(session.getUserID(), "GET_PROCESS_DEFINITION", "" + processDefinitionId, null, null); } catch (javax.jcr.RepositoryException e) { throw new RepositoryException(e.getMessage(), e); } finally { if (token == null) { JCRUtils.logout(session); } } log.debug("getProcessDefinition: {}", vo); return vo; } @Override public byte[] getProcessDefinitionImage(String token, long processDefinitionId, String node) throws RepositoryException, DatabaseException, WorkflowException { log.debug("getProcessDefinitionImage({}, {}, {})", new Object[] { token, processDefinitionId, node }); byte[] image = null; Session session = null; try { if (token == null) { session = JCRUtils.getSession(); } else { session = JcrSessionManager.getInstance().get(token); } image = CommonWorkflowModule.getProcessDefinitionImage(processDefinitionId, node); // Activity log UserActivity.log(session.getUserID(), "GET_PROCESS_DEFINITION_IMAGE", "" + processDefinitionId, null, null); } catch (javax.jcr.RepositoryException e) { throw new RepositoryException(e.getMessage(), e); } finally { if (token == null) { JCRUtils.logout(session); } } log.debug("getProcessDefinitionImage: {}", image); return image; } @Override public Map<String, List<FormElement>> getProcessDefinitionForms(String token, long processDefinitionId) throws ParseException, RepositoryException, DatabaseException, WorkflowException { log.debug("getProcessDefinitionForms({}, {})", token, processDefinitionId); Map<String, List<FormElement>> forms = null; Session session = null; try { if (token == null) { session = JCRUtils.getSession(); } else { session = JcrSessionManager.getInstance().get(token); } forms = CommonWorkflowModule.getProcessDefinitionForms(processDefinitionId); // Activity log UserActivity.log(session.getUserID(), "GET_PROCESS_DEFINITION_FORMS", processDefinitionId + "", null, null); } catch (javax.jcr.RepositoryException e) { throw new RepositoryException(e.getMessage(), e); } finally { if (token == null) { JCRUtils.logout(session); } } log.debug("getProcessDefinitionForms: {}", forms); return forms; } @Override public ProcessInstance runProcessDefinition(String token, long processDefinitionId, String uuid, List<FormElement> variables) throws RepositoryException, DatabaseException, WorkflowException { log.debug("runProcessDefinition({}, {}, {})", new Object[] { token, processDefinitionId, variables }); ProcessInstance vo = null; Session session = null; try { if (token == null) { session = JCRUtils.getSession(); } else { session = JcrSessionManager.getInstance().get(token); } vo = CommonWorkflowModule.runProcessDefinition(session.getUserID(), processDefinitionId, uuid, variables); // Activity log UserActivity.log(session.getUserID(), "RUN_PROCESS_DEFINITION", "" + processDefinitionId, null, variables.toString()); } catch (javax.jcr.RepositoryException e) { throw new RepositoryException(e.getMessage(), e); } finally { if (token == null) { JCRUtils.logout(session); } } log.debug("runProcessDefinition: {}", vo); return vo; } @Override public ProcessInstance sendProcessInstanceSignal(String token, long processInstanceId, String transitionName) throws RepositoryException, DatabaseException, WorkflowException { log.debug("sendProcessInstanceSignal({}, {}, {})", new Object[] { token, processInstanceId, transitionName }); ProcessInstance vo = null; Session session = null; try { if (token == null) { session = JCRUtils.getSession(); } else { session = JcrSessionManager.getInstance().get(token); } vo = CommonWorkflowModule.sendProcessInstanceSignal(processInstanceId, transitionName); // Activity log UserActivity.log(session.getUserID(), "SEND_PROCESS_INSTANCE_SIGNAL", "" + processInstanceId, null, transitionName); } catch (javax.jcr.RepositoryException e) { throw new RepositoryException(e.getMessage(), e); } finally { if (token == null) { JCRUtils.logout(session); } } log.debug("sendProcessInstanceSignal: {}", vo); return vo; } @Override public void endProcessInstance(String token, long processInstanceId) throws RepositoryException, DatabaseException, WorkflowException { log.debug("endProcessInstance({}, {})", token, processInstanceId); Session session = null; try { if (token == null) { session = JCRUtils.getSession(); } else { session = JcrSessionManager.getInstance().get(token); } CommonWorkflowModule.endProcessInstance(processInstanceId); // Activity log UserActivity.log(session.getUserID(), "END_PROCESS_INSTANCE", "" + processInstanceId, null, null); } catch (javax.jcr.RepositoryException e) { throw new RepositoryException(e.getMessage(), e); } finally { if (token == null) { JCRUtils.logout(session); } } log.debug("endProcessInstance: void"); } @Override public void deleteProcessInstance(String token, long processInstanceId) throws RepositoryException, DatabaseException, WorkflowException { log.debug("deleteProcessInstance({}, {})", token, processInstanceId); Session session = null; try { if (token == null) { session = JCRUtils.getSession(); } else { session = JcrSessionManager.getInstance().get(token); } CommonWorkflowModule.deleteProcessInstance(processInstanceId); // Activity log UserActivity.log(session.getUserID(), "DELETE_PROCESS_INSTANCE", "" + processInstanceId, null, null); } catch (javax.jcr.RepositoryException e) { throw new RepositoryException(e.getMessage(), e); } finally { if (token == null) { JCRUtils.logout(session); } } log.debug("deleteProcessInstance: void"); } @Override public List<ProcessInstance> findProcessInstances(String token, long processDefinitionId) throws RepositoryException, DatabaseException, WorkflowException { log.debug("findProcessInstances({}, {})", token, processDefinitionId); List<ProcessInstance> al = null; Session session = null; try { if (token == null) { session = JCRUtils.getSession(); } else { session = JcrSessionManager.getInstance().get(token); } al = CommonWorkflowModule.findProcessInstances(processDefinitionId); // Activity log UserActivity.log(session.getUserID(), "FIND_PROCESS_INSTANCES", "" + processDefinitionId, null, null); } catch (javax.jcr.RepositoryException e) { throw new RepositoryException(e.getMessage(), e); } finally { if (token == null) { JCRUtils.logout(session); } } log.debug("findProcessInstances: {}", al); return al; } @Override public List<ProcessDefinition> findAllProcessDefinitions(String token) throws RepositoryException, DatabaseException, WorkflowException { log.debug("findAllProcessDefinitions({})", token); List<ProcessDefinition> al = null; Session session = null; try { if (token == null) { session = JCRUtils.getSession(); } else { session = JcrSessionManager.getInstance().get(token); } al = CommonWorkflowModule.findAllProcessDefinitions(); // Activity log UserActivity.log(session.getUserID(), "FIND_ALL_PROCESS_DEFINITIONS", null, null, null); } catch (javax.jcr.RepositoryException e) { throw new RepositoryException(e.getMessage(), e); } finally { if (token == null) { JCRUtils.logout(session); } } log.debug("findAllProcessDefinitions: {}", al); return al; } @Override public List<ProcessDefinition> findLatestProcessDefinitions(String token) throws RepositoryException, DatabaseException, WorkflowException { log.debug("findLatestProcessDefinitions({})", token); List<ProcessDefinition> al = null; Session session = null; try { if (token == null) { session = JCRUtils.getSession(); } else { session = JcrSessionManager.getInstance().get(token); } al = CommonWorkflowModule.findLatestProcessDefinitions(); // Activity log UserActivity.log(session.getUserID(), "FIND_LATEST_PROCESS_DEFINITIONS", null, null, null); } catch (javax.jcr.RepositoryException e) { throw new RepositoryException(e.getMessage(), e); } finally { if (token == null) { JCRUtils.logout(session); } } log.debug("findLatestProcessDefinitions: {}", al); return al; } @Override public ProcessDefinition findLastProcessDefinition(String token, String name) throws RepositoryException, DatabaseException, WorkflowException { log.debug("findLastProcessDefinition({}, {})", token, name); ProcessDefinition pd = null; Session session = null; try { if (token == null) { session = JCRUtils.getSession(); } else { session = JcrSessionManager.getInstance().get(token); } pd = CommonWorkflowModule.findLastProcessDefinition(name); // Activity log UserActivity.log(session.getUserID(), "FIND_LAST_PROCESS_DEFINITION", name, null, null); } catch (javax.jcr.RepositoryException e) { throw new RepositoryException(e.getMessage(), e); } finally { if (token == null) { JCRUtils.logout(session); } } log.debug("findLatestProcessDefinitions: {}", pd); return pd; } @Override public List<ProcessDefinition> findAllProcessDefinitionVersions(String token, String name) throws RepositoryException, DatabaseException, WorkflowException { log.debug("findAllProcessDefinitionVersions({}, {})", token, name); List<ProcessDefinition> al = null; Session session = null; try { if (token == null) { session = JCRUtils.getSession(); } else { session = JcrSessionManager.getInstance().get(token); } al = CommonWorkflowModule.findAllProcessDefinitionVersions(name); // Activity log UserActivity.log(session.getUserID(), "FIND_ALL_PROCESS_DEFINITION_VERSIONS", name, null, null); } catch (javax.jcr.RepositoryException e) { throw new RepositoryException(e.getMessage(), e); } finally { if (token == null) { JCRUtils.logout(session); } } log.debug("findAllProcessDefinitionVersions: {}", al); return al; } @Override public ProcessInstance getProcessInstance(String token, long processInstanceId) throws RepositoryException, DatabaseException, WorkflowException { log.debug("getProcessInstance({}, {})", token, processInstanceId); ProcessInstance vo = null; Session session = null; try { if (token == null) { session = JCRUtils.getSession(); } else { session = JcrSessionManager.getInstance().get(token); } vo = CommonWorkflowModule.getProcessInstance(processInstanceId); // Activity log UserActivity.log(session.getUserID(), "GET_PROCESS_INSTANCE", "" + processInstanceId, null, null); } catch (javax.jcr.RepositoryException e) { throw new RepositoryException(e.getMessage(), e); } finally { if (token == null) { JCRUtils.logout(session); } } log.debug("getProcessInstance: {}", vo); return vo; } @Override public void suspendProcessInstance(String token, long processInstanceId) throws RepositoryException, DatabaseException, WorkflowException { log.debug("suspendProcessInstance({}, {})", token, processInstanceId); Session session = null; try { if (token == null) { session = JCRUtils.getSession(); } else { session = JcrSessionManager.getInstance().get(token); } CommonWorkflowModule.suspendProcessInstance(processInstanceId); // Activity log UserActivity.log(session.getUserID(), "SUSPEND_PROCESS_INSTANCE", "" + processInstanceId, null, null); } catch (javax.jcr.RepositoryException e) { throw new RepositoryException(e.getMessage(), e); } finally { if (token == null) { JCRUtils.logout(session); } } log.debug("suspendProcessInstance: void"); } @Override public void resumeProcessInstance(String token, long processInstanceId) throws RepositoryException, DatabaseException, WorkflowException { log.debug("resumeProcessInstance({}, {})", token, processInstanceId); Session session = null; try { if (token == null) { session = JCRUtils.getSession(); } else { session = JcrSessionManager.getInstance().get(token); } CommonWorkflowModule.resumeProcessInstance(processInstanceId); // Activity log UserActivity.log(session.getUserID(), "RESUME_PROCESS_INSTANCE", "" + processInstanceId, null, null); } catch (javax.jcr.RepositoryException e) { throw new RepositoryException(e.getMessage(), e); } finally { if (token == null) { JCRUtils.logout(session); } } log.debug("resumeProcessInstance: void"); } @Override public void addProcessInstanceVariable(String token, long processInstanceId, String name, Object value) throws RepositoryException, DatabaseException, WorkflowException { log.debug("addProcessInstanceVariable({}, {}, {}, {})", new Object[] { token, processInstanceId, name, value }); Session session = null; try { if (token == null) { session = JCRUtils.getSession(); } else { session = JcrSessionManager.getInstance().get(token); } CommonWorkflowModule.addProcessInstanceVariable(processInstanceId, name, value); // Activity log UserActivity.log(session.getUserID(), "ADD_PROCESS_INSTANCE_VARIABLE", "" + processInstanceId, null, name + ", " + value); } catch (javax.jcr.RepositoryException e) { throw new RepositoryException(e.getMessage(), e); } finally { if (token == null) { JCRUtils.logout(session); } } log.debug("addProcessInstanceVariable: void"); } @Override public void deleteProcessInstanceVariable(String token, long processInstanceId, String name) throws RepositoryException, DatabaseException, WorkflowException { log.debug("deleteProcessInstanceVariable({}, {}, {})", new Object[] { token, processInstanceId, name }); Session session = null; try { if (token == null) { session = JCRUtils.getSession(); } else { session = JcrSessionManager.getInstance().get(token); } CommonWorkflowModule.deleteProcessInstanceVariable(processInstanceId, name); // Activity log UserActivity.log(session.getUserID(), "DELETE_PROCESS_INSTANCE_VARIABLE", "" + processInstanceId, null, name); } catch (javax.jcr.RepositoryException e) { throw new RepositoryException(e.getMessage(), e); } finally { if (token == null) { JCRUtils.logout(session); } } log.debug("deleteProcessInstanceVariable: void"); } @Override public List<TaskInstance> findUserTaskInstances(String token) throws RepositoryException, DatabaseException, WorkflowException { log.debug("findUserTaskInstances({})", token); List<TaskInstance> al = null; Session session = null; try { if (token == null) { session = JCRUtils.getSession(); } else { session = JcrSessionManager.getInstance().get(token); } al = CommonWorkflowModule.findUserTaskInstances(session.getUserID()); // Activity log UserActivity.log(session.getUserID(), "FIND_USER_TASK_INSTANCES", null, null, null); } catch (javax.jcr.RepositoryException e) { throw new RepositoryException(e.getMessage(), e); } finally { if (token == null) { JCRUtils.logout(session); } } log.debug("findUserTaskInstances: {}", al); return al; } @Override public List<TaskInstance> findPooledTaskInstances(String token) throws RepositoryException, DatabaseException, WorkflowException { log.debug("findPooledTaskInstances({})", token); List<TaskInstance> al = null; Session session = null; try { if (token == null) { session = JCRUtils.getSession(); } else { session = JcrSessionManager.getInstance().get(token); } al = CommonWorkflowModule.findPooledTaskInstances(session.getUserID()); // Activity log UserActivity.log(session.getUserID(), "FIND_POOLED_TASK_INSTANCES", null, null, null); } catch (javax.jcr.RepositoryException e) { throw new RepositoryException(e.getMessage(), e); } finally { if (token == null) { JCRUtils.logout(session); } } log.debug("findPooledTaskInstances: {}", al); return al; } @Override public List<TaskInstance> findTaskInstances(String token, long processInstanceId) throws RepositoryException, DatabaseException, WorkflowException { log.debug("findTaskInstances({}, {})", token, processInstanceId); List<TaskInstance> al = null; Session session = null; try { if (token == null) { session = JCRUtils.getSession(); } else { session = JcrSessionManager.getInstance().get(token); } al = CommonWorkflowModule.findTaskInstances(processInstanceId); // Activity log UserActivity.log(session.getUserID(), "FIND_TASK_INSTANCES", "" + processInstanceId, null, null); } catch (javax.jcr.RepositoryException e) { throw new RepositoryException(e.getMessage(), e); } finally { if (token == null) { JCRUtils.logout(session); } } log.debug("findTaskInstances: {}", al); return al; } @Override public void setTaskInstanceValues(String token, long taskInstanceId, String transitionName, List<FormElement> values) throws RepositoryException, DatabaseException, WorkflowException { log.debug("setTaskInstanceValues({}, {}, {}, {})", new Object[] { token, taskInstanceId, transitionName, values }); Session session = null; try { if (token == null) { session = JCRUtils.getSession(); } else { session = JcrSessionManager.getInstance().get(token); } CommonWorkflowModule.setTaskInstanceValues(taskInstanceId, transitionName, values); // Activity log UserActivity.log(session.getUserID(), "SET_TASK_INSTANCE_VALUES", "" + taskInstanceId, null, transitionName); } catch (javax.jcr.RepositoryException e) { throw new RepositoryException(e.getMessage(), e); } finally { if (token == null) { JCRUtils.logout(session); } } log.debug("setTaskInstanceValues: void"); } @Override public void addTaskInstanceComment(String token, long taskInstanceId, String message) throws RepositoryException, DatabaseException, WorkflowException { log.debug("addTaskInstanceComment({}, {}, {})", new Object[] { token, taskInstanceId, message }); Session session = null; try { if (token == null) { session = JCRUtils.getSession(); } else { session = JcrSessionManager.getInstance().get(token); } CommonWorkflowModule.addTaskInstanceComment(session.getUserID(), taskInstanceId, message); // Activity log UserActivity.log(session.getUserID(), "ADD_TASK_INSTANCE_COMMENT", "" + taskInstanceId, null, message); } catch (javax.jcr.RepositoryException e) { throw new RepositoryException(e.getMessage(), e); } finally { if (token == null) { JCRUtils.logout(session); } } log.debug("addTaskInstanceComment: void"); } @Override public TaskInstance getTaskInstance(String token, long taskInstanceId) throws RepositoryException, DatabaseException, WorkflowException { log.debug("getTaskInstance({}, {})", token, taskInstanceId); TaskInstance vo = null; Session session = null; try { if (token == null) { session = JCRUtils.getSession(); } else { session = JcrSessionManager.getInstance().get(token); } vo = CommonWorkflowModule.getTaskInstance(taskInstanceId); // Activity log UserActivity.log(session.getUserID(), "GET_TASK_INSTANCE", "" + taskInstanceId, null, null); } catch (javax.jcr.RepositoryException e) { throw new RepositoryException(e.getMessage(), e); } finally { if (token == null) { JCRUtils.logout(session); } } log.debug("getTaskInstance: {}", vo); return vo; } @Override public void setTaskInstanceActorId(String token, long taskInstanceId, String actorId) throws RepositoryException, DatabaseException, WorkflowException { log.debug("setTaskInstanceActorId({}, {}, {})", new Object[] { token, taskInstanceId, actorId }); Session session = null; try { if (token == null) { session = JCRUtils.getSession(); } else { session = JcrSessionManager.getInstance().get(token); } CommonWorkflowModule.setTaskInstanceActorId(taskInstanceId, actorId); // Activity log UserActivity.log(session.getUserID(), "SET_TASK_INSTANCE_ACTOR_ID", "" + taskInstanceId, null, actorId); } catch (javax.jcr.RepositoryException e) { throw new RepositoryException(e.getMessage(), e); } finally { if (token == null) { JCRUtils.logout(session); } } log.debug("setTaskInstanceActorId: void"); } @Override public void addTaskInstanceVariable(String token, long taskInstanceId, String name, Object value) throws RepositoryException, DatabaseException, WorkflowException { log.debug("addTaskInstanceVariable({}, {}, {}, {})", new Object[] { token, taskInstanceId, name, value }); Session session = null; try { if (token == null) { session = JCRUtils.getSession(); } else { session = JcrSessionManager.getInstance().get(token); } CommonWorkflowModule.addTaskInstanceVariable(taskInstanceId, name, value); // Activity log UserActivity.log(session.getUserID(), "ADD_TASK_INSTANCE_VARIABLE", "" + taskInstanceId, null, name + ", " + value); } catch (javax.jcr.RepositoryException e) { throw new RepositoryException(e.getMessage(), e); } finally { if (token == null) { JCRUtils.logout(session); } } log.debug("addTaskInstanceVariable: void"); } @Override public void deleteTaskInstanceVariable(String token, long taskInstanceId, String name) throws RepositoryException, DatabaseException, WorkflowException { log.debug("deleteTaskInstanceVariable({}, {}, {})", new Object[] { token, taskInstanceId, name }); Session session = null; try { if (token == null) { session = JCRUtils.getSession(); } else { session = JcrSessionManager.getInstance().get(token); } CommonWorkflowModule.deleteTaskInstanceVariable(taskInstanceId, name); // Activity log UserActivity.log(session.getUserID(), "DELETE_TASK_INSTANCE_VARIABLE", "" + taskInstanceId, null, name); } catch (javax.jcr.RepositoryException e) { throw new RepositoryException(e.getMessage(), e); } finally { if (token == null) { JCRUtils.logout(session); } } log.debug("deleteTaskInstanceVariable: void"); } @Override public void startTaskInstance(String token, long taskInstanceId) throws RepositoryException, DatabaseException, WorkflowException { log.debug("startTaskInstance({}, {})", token, taskInstanceId); Session session = null; try { if (token == null) { session = JCRUtils.getSession(); } else { session = JcrSessionManager.getInstance().get(token); } CommonWorkflowModule.startTaskInstance(taskInstanceId); // Activity log UserActivity.log(session.getUserID(), "START_TASK_INSTANCE", "" + taskInstanceId, null, null); } catch (javax.jcr.RepositoryException e) { throw new RepositoryException(e.getMessage(), e); } finally { if (token == null) { JCRUtils.logout(session); } } log.debug("startTaskInstance: void"); } @Override public void endTaskInstance(String token, long taskInstanceId, String transitionName) throws RepositoryException, DatabaseException, WorkflowException { log.debug("endTaskInstance({}, {}, {})", new Object[] { token, taskInstanceId, transitionName }); Session session = null; try { if (token == null) { session = JCRUtils.getSession(); } else { session = JcrSessionManager.getInstance().get(token); } CommonWorkflowModule.endTaskInstance(taskInstanceId, transitionName); // Activity log UserActivity.log(session.getUserID(), "END_TASK_INSTANCE", "" + taskInstanceId, null, null); } catch (javax.jcr.RepositoryException e) { throw new RepositoryException(e.getMessage(), e); } finally { if (token == null) { JCRUtils.logout(session); } } log.debug("endTaskInstance: void"); } @Override public void suspendTaskInstance(String token, long taskInstanceId) throws RepositoryException, DatabaseException, WorkflowException { log.debug("suspendTaskInstance({}, {})", token, taskInstanceId); Session session = null; try { if (token == null) { session = JCRUtils.getSession(); } else { session = JcrSessionManager.getInstance().get(token); } CommonWorkflowModule.suspendTaskInstance(taskInstanceId); // Activity log UserActivity.log(session.getUserID(), "SUSPEND_TASK_INSTANCE", "" + taskInstanceId, null, null); } catch (javax.jcr.RepositoryException e) { throw new RepositoryException(e.getMessage(), e); } finally { if (token == null) { JCRUtils.logout(session); } } log.debug("suspendTaskInstance: void"); } @Override public void resumeTaskInstance(String token, long taskInstanceId) throws RepositoryException, DatabaseException, WorkflowException { log.debug("resumeTaskInstance({}, {})", token, taskInstanceId); Session session = null; try { if (token == null) { session = JCRUtils.getSession(); } else { session = JcrSessionManager.getInstance().get(token); } CommonWorkflowModule.resumeTaskInstance(taskInstanceId); // Activity log UserActivity.log(session.getUserID(), "RESUME_TASK_INSTANCE", "" + taskInstanceId, null, null); } catch (javax.jcr.RepositoryException e) { throw new RepositoryException(e.getMessage(), e); } finally { if (token == null) { JCRUtils.logout(session); } } log.debug("resumeTaskInstance: void"); } @Override public Token getToken(String token, long tokenId) throws RepositoryException, DatabaseException, WorkflowException { log.debug("getToken({}, {})", token, tokenId); Token vo = null; Session session = null; try { if (token == null) { session = JCRUtils.getSession(); } else { session = JcrSessionManager.getInstance().get(token); } vo = CommonWorkflowModule.getToken(tokenId); // Activity log UserActivity.log(session.getUserID(), "GET_TOKEN", "" + tokenId, null, null); } catch (javax.jcr.RepositoryException e) { throw new RepositoryException(e.getMessage(), e); } finally { if (token == null) { JCRUtils.logout(session); } } log.debug("getToken: " + vo); return vo; } @Override public void addTokenComment(String token, long tokenId, String message) throws RepositoryException, DatabaseException, WorkflowException { log.debug("addTokenComment({}, {}, {})", new Object[] { token, tokenId, message }); Session session = null; try { if (token == null) { session = JCRUtils.getSession(); } else { session = JcrSessionManager.getInstance().get(token); } CommonWorkflowModule.addTokenComment(session.getUserID(), tokenId, message); // Activity log UserActivity.log(session.getUserID(), "ADD_TOKEN_COMMENT", "" + tokenId, null, message); } catch (javax.jcr.RepositoryException e) { throw new RepositoryException(e.getMessage(), e); } finally { if (token == null) { JCRUtils.logout(session); } } log.debug("addTokenComment: void"); } @Override public void suspendToken(String token, long tokenId) throws RepositoryException, DatabaseException, WorkflowException { log.debug("suspendToken({}, {})", token, tokenId); Session session = null; try { if (token == null) { session = JCRUtils.getSession(); } else { session = JcrSessionManager.getInstance().get(token); } CommonWorkflowModule.suspendToken(tokenId); // Activity log UserActivity.log(session.getUserID(), "SUSPEND_TOKEN", "" + tokenId, null, null); } catch (javax.jcr.RepositoryException e) { throw new RepositoryException(e.getMessage(), e); } finally { if (token == null) { JCRUtils.logout(session); } } log.debug("suspendToken: void"); } @Override public void resumeToken(String token, long tokenId) throws RepositoryException, DatabaseException, WorkflowException { log.debug("resumeToken({}, {})", token, tokenId); Session session = null; try { if (token == null) { session = JCRUtils.getSession(); } else { session = JcrSessionManager.getInstance().get(token); } CommonWorkflowModule.resumeToken(tokenId); // Activity log UserActivity.log(session.getUserID(), "RESUME_TOKEN", "" + tokenId, null, null); } catch (javax.jcr.RepositoryException e) { throw new RepositoryException(e.getMessage(), e); } finally { if (token == null) { JCRUtils.logout(session); } } log.debug("resumeToken: void"); } @Override public Token sendTokenSignal(String token, long tokenId, String transitionName) throws RepositoryException, DatabaseException, WorkflowException { log.debug("sendTokenSignal({}, {}, {})", new Object[] { token, tokenId, transitionName }); Token vo = null; Session session = null; try { if (token == null) { session = JCRUtils.getSession(); } else { session = JcrSessionManager.getInstance().get(token); } CommonWorkflowModule.sendTokenSignal(tokenId, transitionName); // Activity log UserActivity.log(session.getUserID(), "SEND_TOKEN_SIGNAL", "" + tokenId, null, transitionName); } catch (javax.jcr.RepositoryException e) { throw new RepositoryException(e.getMessage(), e); } finally { if (token == null) { JCRUtils.logout(session); } } log.debug("sendTokenSignal: {}", vo); return vo; } @Override public void setTokenNode(String token, long tokenId, String nodeName) throws RepositoryException, DatabaseException, WorkflowException { log.debug("setTokenNode({}, {}, {})", new Object[] { token, tokenId, nodeName }); Session session = null; try { if (token == null) { session = JCRUtils.getSession(); } else { session = JcrSessionManager.getInstance().get(token); } CommonWorkflowModule.setTokenNode(tokenId, nodeName); // Activity log UserActivity.log(session.getUserID(), "SEND_TOKEN_NODE", "" + tokenId, null, nodeName); } catch (javax.jcr.RepositoryException e) { throw new RepositoryException(e.getMessage(), e); } finally { if (token == null) { JCRUtils.logout(session); } } log.debug("setTokenNode: void"); } @Override public void endToken(String token, long tokenId) throws RepositoryException, DatabaseException, WorkflowException { log.debug("endToken({}, {})", token, tokenId); Session session = null; try { if (token == null) { session = JCRUtils.getSession(); } else { session = JcrSessionManager.getInstance().get(token); } CommonWorkflowModule.endToken(tokenId); // Activity log UserActivity.log(session.getUserID(), "END_TOKEN", "" + tokenId, null, null); } catch (javax.jcr.RepositoryException e) { throw new RepositoryException(e.getMessage(), e); } finally { if (token == null) { JCRUtils.logout(session); } } log.debug("endToken: void"); } }
package cn.jboa.action; import java.util.List; import javax.servlet.http.HttpSession; import org.apache.struts2.ServletActionContext; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import com.opensymphony.xwork2.ActionSupport; import cn.jboa.entity.Employee; import cn.jboa.entity.Position; @Controller("baseAction") @Scope("prototype") public class BaseAction extends ActionSupport{ /** * */ private static final long serialVersionUID = 1L; public Employee getSessionEmployee() throws Exception{ HttpSession session = ServletActionContext.getRequest().getSession(); Employee employee = (Employee)session.getAttribute("employee"); return employee; } public Integer getSessionPositionId() throws Exception{ HttpSession session = ServletActionContext.getRequest().getSession(); Employee employee = (Employee)session.getAttribute("employee"); if(employee!=null){ Position position = employee.getSysPosition(); if(position!=null){ return position.getId(); } } return null; } public List<Employee> getEmployeeMannager() throws Exception{ HttpSession session = ServletActionContext.getRequest().getSession(); @SuppressWarnings("unchecked") List<Employee> manager= (List<Employee>) session.getAttribute("manager"); return manager; } }
package tunbridge; import java.lang.InterruptedException; import java.util.concurrent.Semaphore; public class Bridge { private Semaphore lock; public Bridge() { /** * We can simply use a mutex semaphore to keep farmers from different * directions from entering. It isn't the most efficient, since * potentially multiple farmers from the same direction would be waiting * unnecessarily, but it works. */ this.lock = new Semaphore(1); } public void enter() throws InterruptedException { this.lock.acquire(); } public void leave() { this.lock.release(); } }
package mvd.pension; import android.app.Activity; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.database.sqlite.SQLiteException; import android.os.Bundle; import android.os.Handler; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.view.Window; import android.widget.Toast; import java.util.Calendar; import java.util.Date; //заставка public class PCalcSplashActivity extends AppCompatActivity { /** Duration of wait **/ private final int SPLASH_DISPLAY_LENGTH = 3000; private Context mContext; private String mes = null; //проверка пришло ли новое сообшение от FireBase @Override protected void onCreate(Bundle savedInstanceState) { setTheme(R.style.AppTheme_NoActionBar); super.onCreate(savedInstanceState); //requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_splash_pens); //обработка сообщений от Notification FireBase отправляется сообщение с параметром mess_1 в консоле FireBase //нужно отправлять через расширенные параметры сообщения используя mess_1 mes = getIntent().getStringExtra("mess_1"); if (mes != null) {//если не пустой записываем в БД PCalcMessageSQLite.get(this).insertSQLiteMessage("",mes); } mContext = this; new Handler().postDelayed(new Runnable(){ @Override public void run() { /* Create an Intent that will start the Menu-Activity. */ Intent mainIntent = new Intent(PCalcSplashActivity.this,PCalcPensActivity.class); if (mes != null) { mainIntent.putExtra("bol_mes",true); //передаем в PCalcPensActivity true при вызове интента что бы открыть сразу фрагмент с сообщениями } PCalcSplashActivity.this.startActivity(mainIntent); PCalcSplashActivity.this.finish(); } }, SPLASH_DISPLAY_LENGTH); } }
/* */ package datechooser.beans.editor; /* */ /* */ import datechooser.beans.editor.descriptor.DescriptionManager; /* */ import java.awt.Color; /* */ import java.awt.Graphics; /* */ import java.awt.Rectangle; /* */ import java.util.HashSet; /* */ import java.util.Set; /* */ import javax.swing.JColorChooser; /* */ import javax.swing.JComponent; /* */ import javax.swing.colorchooser.ColorSelectionModel; /* */ import javax.swing.event.ChangeEvent; /* */ import javax.swing.event.ChangeListener; /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public class SimpleColorEditor /* */ extends VisualEditorCashed /* */ implements ColorSelectionModel /* */ { /* */ private Set<ChangeListener> changeListeners; /* */ /* */ public SimpleColorEditor() {} /* */ /* */ protected JComponent createEditor() /* */ { /* 31 */ this.changeListeners = new HashSet(); /* 32 */ JColorChooser editorPane = new JColorChooser(this); /* 33 */ return editorPane; /* */ } /* */ /* */ public Color getSelectedColor() { /* 37 */ return (Color)getValue(); /* */ } /* */ /* */ public void setSelectedColor(Color color) { /* 41 */ setValue(color); /* 42 */ fireStateChange(); /* */ } /* */ /* */ public void addChangeListener(ChangeListener listener) { /* 46 */ this.changeListeners.add(listener); /* */ } /* */ /* */ public void removeChangeListener(ChangeListener listener) { /* 50 */ this.changeListeners.remove(listener); /* */ } /* */ /* */ public void fireStateChange() { /* 54 */ ChangeEvent e = new ChangeEvent(this); /* 55 */ for (ChangeListener listener : this.changeListeners) { /* 56 */ listener.stateChanged(e); /* */ } /* */ } /* */ /* */ public String getJavaInitializationString() { /* 61 */ return DescriptionManager.describeJava(getValue(), Color.class); /* */ } /* */ /* */ public boolean isPaintable() { /* 65 */ return true; /* */ } /* */ /* */ public void paintValue(Graphics gfx, Rectangle box) { /* 69 */ Color color = (Color)getValue(); /* 70 */ gfx.setColor(color); /* 71 */ gfx.fillRect(2, 2, box.height - 4, box.height - 4); /* 72 */ gfx.setColor(Color.BLACK); /* 73 */ gfx.drawRect(2, 2, box.height - 4, box.height - 4); /* 74 */ gfx.drawString("[" + color.getRed() + ", " + color.getGreen() + ", " + color.getBlue() + "]", box.height + 2, box.height - 4); /* */ } /* */ } /* Location: /home/work/vm/shared-folder/reverse/ketonix/KetonixUSB-20170310.jar!/datechooser/beans/editor/SimpleColorEditor.class * Java compiler version: 5 (49.0) * JD-Core Version: 0.7.1 */
package it.usi.xframe.xas.bfimpl.a2psms.providers.vodafonepop; import it.usi.xframe.xas.bfimpl.a2psms.configuration.CustomizationBasic; public class Customization extends CustomizationBasic { public boolean isSupportDeliveryReport() { return false; } public boolean isSupportMobileOriginated() { return false; } public boolean isSupportReplaceMap() { return false; } }
package com.supconit.kqfx.web.util; import hc.business.dic.domains.FlatData; import hc.business.dic.entities.Data; import hc.business.dic.services.DataDictionaryService; import java.util.HashMap; import java.util.LinkedHashMap; /** *数据字典工具包 * @author hebingting * */ public class DictionaryUtil { /** * 根据字典 code获取该字典下字典项的映射关系 * @author hebingting * @param code * @param dataDictionaryService * @return */ public static HashMap<String, String> dictionary(String code,DataDictionaryService dataDictionaryService){ LinkedHashMap<String, String> map = new LinkedHashMap<String, String>(); FlatData flatData = (FlatData) dataDictionaryService.getByCode(code); if(null != flatData){ for (Data data : flatData) { map.put(new String(data.getCode()), new String(data.getName())); } } return map; } }
package com.storytime.client.changevieweventhandlers; import com.google.gwt.event.shared.EventHandler; public interface StartGameLocalEventHandler extends EventHandler { public void onStartGame(); }
package ict.kosovo.growth.detyraIfElse; public class ThreeSort { public static void main(String[] args) { int a = 1234; int b = 99; int c = 1; if (a<b){ System.out.println(c=a); } System.out.println(a); System.out.println(b); System.out.println(c); } }