text
stringlengths
10
2.72M
package io.meksula.persister.domain; import lombok.*; import javax.persistence.Column; @Data @ToString @Builder @NoArgsConstructor @AllArgsConstructor public class TransformerDto { private TransformerTypes from; private TransformerTypes to; @Column(columnDefinition = "TEXT") private String encodedData; /** * Processed by app running on hostname * */ private String hostname; }
package com.examples.peoplemanager.service.mock; import java.util.*; import com.examples.peoplemanager.model.Person; import com.examples.peoplemanager.service.ConfigService; import com.examples.peoplemanager.service.PeopleService; import com.google.inject.Inject; import com.google.inject.Singleton; import org.joda.time.Days; @Singleton public class MockPeopleService implements PeopleService<Person> { private static int numberOfMales; private Map<String,Person> people; private static Person oldest; private ConfigService cs; @Inject public MockPeopleService(ConfigService cs) { this.cs = cs; people = new HashMap<String,Person>(); numberOfMales = 0; load(); } @Override public Person add(Person p) { people.put(p.getName(), p); if (p.isAMale()) numberOfMales++; if (oldest == null || p.getDateOfBirth().isBefore(oldest.getDateOfBirth())) oldest = p; return p; } @Override public int getNumberOfMales() { return numberOfMales; } @Override public int daysBetween(Person i1, Person i2) { Days d = Days.daysBetween(i1.getDateOfBirth(), i2.getDateOfBirth()); return d.getDays(); } public int daysBetweenByName(String name1, String name2) { Person p1 = people.get(name1); Person p2 = people.get(name2); return daysBetween(p1, p2); } /** * Load configuration from Mock data. */ @Override public void load() { for (Person p: cs.load()) add(p); } @Override public Person getOldestPerson() { return oldest; } }
package br.com.helpdev.quaklog.dataprovider.entity; import lombok.Builder; import lombok.Data; @Data @Builder public class KillHistoryEntity { private String gameTime; private String killMode; private int playerID; private int modID; }
package com.av.client.frames; import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.beans.PropertyVetoException; import java.text.NumberFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JDesktopPane; import javax.swing.JFormattedTextField; import javax.swing.JFrame; import javax.swing.JInternalFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.ListSelectionModel; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.table.AbstractTableModel; import javax.swing.text.DateFormatter; import javax.swing.text.NumberFormatter; import org.jdesktop.swingx.JXDatePicker; import org.jdesktop.swingx.JXErrorPane; import org.jdesktop.swingx.error.ErrorInfo; import com.av.client.util.idioma.Error; import com.av.client.util.idioma.Etiqueta; import com.av.client.util.idioma.ManejadorIdiomas; import com.av.client.util.idioma.ManejadorIdiomas.IdiomaEvent; import com.av.client.util.idioma.ManejadorIdiomas.IdiomaEventListener; import com.av.client.util.sesion.AdministradorSesion; import com.av.db.dataobjects.Abono; import com.av.db.dataobjects.Tarjeta; import com.av.exceptions.AvException; import com.av.rmi.CatalogoAcciones; import com.av.rmi.Parametro; import com.av.rmi.Parametro.Tipo; @SuppressWarnings("serial") public class AbonoFrame extends JInternalFrame { private static final int WIDTH = 700; private static final int HEIGHT = 300; private JLabel lblMonto; private JLabel lblTarjeta; private JLabel lblFecha; private JLabel lblHora; private JComboBox cboTarjeta; private JFormattedTextField txtMonto; private JXDatePicker dtFecha; private JFormattedTextField txtHora; private JTable tblAbonos; private JButton btnAgregar; private JButton btnActualizar; private JButton btnEliminar; private JButton btnCerrar; private JButton btnObtener; private AbonosModel im; private ManejadorIdiomas mi; private BotonHandler bh = new BotonHandler(); private Abono abono; private Abono[] abonos; public AbonoFrame() { super(); mi = ManejadorIdiomas.getInstance(); initComponents(); addListeners(); cargarPermisos(); cargarAbonos(); limpiarTextos(); }// AbonoFrame private void cargarPermisos() { if (AdministradorSesion.getInstance().getSesionActiva() != null) { switch (AdministradorSesion.getInstance().getSesionActiva() .getUsuario().getRol()) { case CONDU: txtMonto.setEditable(true); btnAgregar.setEnabled(true); btnActualizar.setEnabled(false); btnEliminar.setEnabled(false); break; case ADMIN: txtMonto.setEditable(true); btnAgregar.setEnabled(true); btnActualizar.setEnabled(true); btnEliminar.setEnabled(true); break; } } }// cargarPermisos private void addListeners() { mi.addIdiomaEventListener(new IdiomaEventListener() { @Override public void changedIdiomaEvent(IdiomaEvent evt) { setLabels(); } }); tblAbonos.getSelectionModel().addListSelectionListener( new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { if (abonos != null && tblAbonos.getSelectedRow() >= 0 && tblAbonos.getSelectedRow() < abonos.length) { setAbono(abonos[tblAbonos.getSelectedRow()]); } } }); btnAgregar.addActionListener(bh); btnEliminar.addActionListener(bh); btnActualizar.addActionListener(bh); btnCerrar.addActionListener(bh); btnObtener.addActionListener(bh); }// addListeners /** * Funcion que restablece las etiquetas para todos los componentes */ private void setLabels() { setTitle(mi.obtenerEtiqueta(Etiqueta.ABONO_FRAME_TITLE)); lblMonto.setText(mi.obtenerEtiqueta(Etiqueta.ABONO_FRAME_LBL_MONTO)); lblTarjeta .setText(mi.obtenerEtiqueta(Etiqueta.ABONO_FRAME_LBL_TARJETA)); lblFecha.setText(mi.obtenerEtiqueta(Etiqueta.ABONO_FRAME_LBL_FECHA)); txtMonto.setLocale(mi.getIdioma().getLocale()); dtFecha.setLocale(mi.getIdioma().getLocale()); lblHora.setText(mi.obtenerEtiqueta(Etiqueta.ABONO_FRAME_LBL_HORA)); btnAgregar .setText(mi.obtenerEtiqueta(Etiqueta.ABONO_FRAME_BTN_AGREGAR)); btnEliminar.setText(mi .obtenerEtiqueta(Etiqueta.ABONO_FRAME_BTN_ELIMINAR)); btnActualizar.setText(mi .obtenerEtiqueta(Etiqueta.ABONO_FRAME_BTN_ACTUALIZAR)); btnCerrar.setText(mi.obtenerEtiqueta(Etiqueta.ABONO_FRAME_BTN_CERRAR)); btnObtener .setText(mi.obtenerEtiqueta(Etiqueta.ABONO_FRAME_BTN_OBTENER)); String[] headers = (mi .obtenerEtiqueta(Etiqueta.ABONO_FRAME_TBL_ELEMENTOS_COLUMN_NAMES)) .split(","); if (headers != null && tblAbonos.getColumnCount() == headers.length) { for (int i = 0; i < tblAbonos.getColumnCount(); i++) { tblAbonos.getColumnModel().getColumn(i).setHeaderValue( headers[i]); } } }// setLabels /** * Funcion que configura todos los componentes y su correcta colocacion */ private void initComponents() { setTitle(mi.obtenerEtiqueta(Etiqueta.ABONO_FRAME_TITLE)); setSize(new Dimension()); setLayout(new GridBagLayout()); GridBagConstraints gc = new GridBagConstraints(); gc.insets = new Insets(5, 5, 5, 5); gc.fill = GridBagConstraints.HORIZONTAL; // Fecha gc.gridy = 0; gc.gridx = 0; lblFecha = new JLabel(mi .obtenerEtiqueta(Etiqueta.ABONO_FRAME_LBL_FECHA)); add(lblFecha, gc); gc.gridx = 1; dtFecha = new JXDatePicker(); dtFecha.setLocale(mi.getIdioma().getLocale()); add(dtFecha, gc); // Hora gc.gridx = 2; lblHora = new JLabel(mi.obtenerEtiqueta(Etiqueta.ABONO_FRAME_LBL_HORA)); add(lblHora, gc); gc.gridx = 3; txtHora = new JFormattedTextField(new DateFormatter( new SimpleDateFormat("HH:mm"))); add(txtHora, gc); // Monto gc.gridy = 1; gc.gridx = 0; lblMonto = new JLabel(mi .obtenerEtiqueta(Etiqueta.ABONO_FRAME_LBL_MONTO)); add(lblMonto, gc); gc.gridx = 1; txtMonto = new JFormattedTextField(new NumberFormatter(NumberFormat .getNumberInstance(mi.getIdioma().getLocale()))); add(txtMonto, gc); // Tarjeta gc.gridy = 2; gc.gridx = 0; lblTarjeta = new JLabel(mi .obtenerEtiqueta(Etiqueta.ABONO_FRAME_LBL_TARJETA)); add(lblTarjeta, gc); gc.gridx = 1; gc.gridwidth = 3; cboTarjeta = new JComboBox(obtenerTarjetasActivas()); add(cboTarjeta, gc); gc.gridwidth = 1; // Botones JPanel jpnl = new JPanel(new FlowLayout()); btnAgregar = new JButton(mi .obtenerEtiqueta(Etiqueta.ABONO_FRAME_BTN_AGREGAR)); jpnl.add(btnAgregar); btnEliminar = new JButton(mi .obtenerEtiqueta(Etiqueta.ABONO_FRAME_BTN_ELIMINAR)); jpnl.add(btnEliminar); btnActualizar = new JButton(mi .obtenerEtiqueta(Etiqueta.ABONO_FRAME_BTN_ACTUALIZAR)); jpnl.add(btnActualizar); btnCerrar = new JButton(mi .obtenerEtiqueta(Etiqueta.ABONO_FRAME_BTN_CERRAR)); jpnl.add(btnCerrar); btnObtener = new JButton(mi .obtenerEtiqueta(Etiqueta.ABONO_FRAME_BTN_OBTENER)); jpnl.add(btnObtener); gc.gridy = 3; gc.gridx = 0; gc.gridwidth = 4; add(jpnl, gc); gc.gridwidth = 1; // Tabla de resultados gc.gridy = 4; gc.gridwidth = 4; gc.weightx = 1.0; gc.weighty = 1.0; gc.fill = GridBagConstraints.BOTH; im = new AbonosModel(0); tblAbonos = new JTable(im); tblAbonos .setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION); add(new JScrollPane(tblAbonos), gc); setClosable(false); setSize(WIDTH, HEIGHT); }// initComponents private class AbonosModel extends AbstractTableModel { private Map<Point, Object> lookup; private final int rows; private final int columns; private final String headers[]; public AbonosModel(int rows) { this.rows = rows; this.headers = mi.obtenerEtiqueta( Etiqueta.ABONO_FRAME_TBL_ELEMENTOS_COLUMN_NAMES).split(","); this.columns = headers.length; lookup = new HashMap<Point, Object>(); } public int getColumnCount() { return columns; } public int getRowCount() { return rows; } public String getColumnName(int column) { return headers[column]; } public Object getValueAt(int row, int column) { return lookup.get(new Point(row, column)); } public void setValueAt(Object value, int row, int column) { if ((rows < 0) || (columns < 0)) { throw new IllegalArgumentException("Invalid row/column setting"); } if ((row < rows) && (column < columns)) { lookup.put(new Point(row, column), value); } } } /** * Funcion que valida que los campos requeridos del formulario * * @throws AvException */ private void validarTextos() throws AvException { if (cboTarjeta.getSelectedIndex() < 0) { cboTarjeta.requestFocus(); throw new AvException(mi.obtenerError(Error.ABONO_TXT_TARJETA_NULL)); } if (txtMonto.getText() == null || txtMonto.getText().trim().length() == 0) { txtMonto.requestFocus(); throw new AvException(mi.obtenerError(Error.ABONO_TXT_MONTO)); } }// validarTextos private Abono getAbono() { if (abono == null) { abono = new Abono(); } abono.setTarjeta((Tarjeta) cboTarjeta.getSelectedItem()); // abono.setMonto((Double) txtMonto.getValue()); abono.setMonto(new Double(txtMonto.getText())); abono.setFecha(obtenerFecha()); return abono; }// getAbono private void setAbono(Abono a) { if (a != null) { abono = a; cboTarjeta.setSelectedItem(a.getTarjeta()); txtMonto.setValue(a.getMonto()); dtFecha.setDate(a.getFecha()); txtHora.setValue(a.getFecha()); } }// setAbono private void limpiarTextos() { txtMonto.setText(""); cboTarjeta.setSelectedIndex(-1); dtFecha.setDate(new Date()); txtHora.setValue(new Date()); }// limpiarTextos /** * Clase creada para la administracion de acciones * * @author J Francisco Ruvalcaba C * */ private class BotonHandler implements ActionListener { @Override public void actionPerformed(ActionEvent ev) { Object o = ev.getSource(); if (o instanceof JButton) { if (o == btnCerrar) { dispose(); } else if (o == btnActualizar) { try { validarTextos(); actualizarAbono(); } catch (AvException e) { ErrorInfo info = new ErrorInfo(getTitle() + " - ERROR", e.getMessage(), null, null, e, Level.WARNING, null); JXErrorPane .setDefaultLocale(mi.getIdioma().getLocale()); JXErrorPane.showDialog(getParent(), info); } } else if (o == btnEliminar) { try { validarTextos(); eliminarAbono(); } catch (AvException e) { ErrorInfo info = new ErrorInfo(getTitle() + " - ERROR", e.getMessage(), null, null, e, Level.WARNING, null); JXErrorPane .setDefaultLocale(mi.getIdioma().getLocale()); JXErrorPane.showDialog(getParent(), info); } } else if (o == btnAgregar) { try { dtFecha.setDate(new Date()); txtHora.setValue(new Date()); validarTextos(); agregarAbono(); } catch (AvException e) { ErrorInfo info = new ErrorInfo(getTitle() + " - ERROR", e.getMessage(), null, null, e, Level.WARNING, null); JXErrorPane .setDefaultLocale(mi.getIdioma().getLocale()); JXErrorPane.showDialog(getParent(), info); } } else if (o == btnObtener) { cargarAbonos(); } } }// actionPerformed }// BotonHandler /** * Funcion que agrega un abono a partir de los datos capturados * * @throws AvException */ private void agregarAbono() throws AvException { Parametro p = new Parametro(); p.setAccion(CatalogoAcciones.AGREGAR_ABONO); abono = new Abono(); p.setValor(Tipo.INPUT, getAbono()); AdministradorSesion.getInstance().getSesionActiva().ejecutar(p); limpiarTextos(); cargarAbonos(); }// agregarAbono /** * Funcion que actualiza un abono con los datos capturados * * @throws AvException */ private void actualizarAbono() throws AvException { Parametro p = new Parametro(); p.setAccion(CatalogoAcciones.ACTUALIZAR_ABONO); p.setValor(Tipo.INPUT, getAbono()); AdministradorSesion.getInstance().getSesionActiva().ejecutar(p); limpiarTextos(); cargarAbonos(); }// actualizarAbono /** * Funcion que elimina el abono seleccionado * * @throws AvException */ private void eliminarAbono() throws AvException { Parametro p = new Parametro(); p.setAccion(CatalogoAcciones.ELIMINAR_ABONO); p.setValor(Tipo.INPUT, getAbono()); AdministradorSesion.getInstance().getSesionActiva().ejecutar(p); limpiarTextos(); cargarAbonos(); }// eliminarElementoCatalogo /** * Funcion que carga en la tabla todos los abonos registrados en el sistema */ private void cargarAbonos() { Parametro p = new Parametro(); if (AdministradorSesion.getInstance().getSesionActiva() != null) { try { p.setAccion(CatalogoAcciones.OBTENER_TODOS_ABONO); p = AdministradorSesion.getInstance().getSesionActiva() .ejecutar(p); if (p.getValor(Tipo.OUTPUT) != null) { abonos = (Abono[]) p.getValor(Tipo.OUTPUT); im = new AbonosModel(abonos.length); int row = 0; for (Abono a : abonos) { im.setValueAt(a.getTarjeta(), row, 0); im.setValueAt(a.getFecha(), row, 1); im.setValueAt(a.getMonto(), row, 2); row++; } tblAbonos.setModel(im); } } catch (AvException e) { ErrorInfo info = new ErrorInfo(getTitle() + " - ERROR", e .getMessage(), null, null, e, Level.INFO, null); JXErrorPane.setDefaultLocale(mi.getIdioma().getLocale()); JXErrorPane.showDialog(getParent(), info); } } }// cargarElementoCatalogo /** * Obtiene la fecha y hora que el usuario a ingresado * * @return Date */ private Date obtenerFecha() { Calendar c = Calendar.getInstance(); Calendar c2 = Calendar.getInstance(); c.setTime(dtFecha.getDate()); c2.setTime((Date) txtHora.getValue()); c.set(Calendar.HOUR_OF_DAY, c2.get(Calendar.HOUR_OF_DAY)); c.set(Calendar.MINUTE, c2.get(Calendar.MINUTE)); return c.getTime(); }// obtenerFecha /** * Funcion que obtiene todas las tarjetas activas del sistema * * @return */ private Tarjeta[] obtenerTarjetasActivas() { Tarjeta[] tmp = new Tarjeta[1]; Parametro p = new Parametro(); if (AdministradorSesion.getInstance().getSesionActiva() != null) { try { p.setAccion(CatalogoAcciones.OBTENER_ACTIVOS_TARJETA); p = AdministradorSesion.getInstance().getSesionActiva() .ejecutar(p); if (p.getValor(Tipo.OUTPUT) != null) { tmp = (Tarjeta[]) p.getValor(Tipo.OUTPUT); } } catch (AvException e) { ErrorInfo info = new ErrorInfo(getTitle() + " - ERROR", e .getMessage(), null, null, e, Level.INFO, null); JXErrorPane.setDefaultLocale(mi.getIdioma().getLocale()); JXErrorPane.showDialog(getParent(), info); } } return tmp; }// obtenerTarjetasActivas public static void main(String[] args) { JFrame tmp = new JFrame("AbonosFrame"); tmp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JDesktopPane desktop = new JDesktopPane(); desktop.setBackground(Color.GRAY); desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE); tmp.setContentPane(desktop); AbonoFrame ecf = new AbonoFrame(); ecf.setVisible(true); desktop.add(ecf); try { ecf.setSelected(true); } catch (PropertyVetoException e) { } tmp.setSize(new Dimension(ecf.getWidth() + 100, ecf.getHeight() + 100)); tmp.setVisible(true); }// main }// AbonoFrame
package sample.artik.cloud.healthbook; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; public class PedometerActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_pedometer); if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .add(R.id.container, new PedometerFragment()) .commit(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_pedometer_fragment, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_update) { Intent intent = new Intent(this, MessagesActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); String steps = ((EditText) this.findViewById(R.id.steps_text)).getText().toString(); String distance = ((EditText) this.findViewById(R.id.distance_text)).getText().toString(); intent.putExtra("steps", steps); intent.putExtra("distance", distance); startActivity(intent); finish(); return true; } return super.onOptionsItemSelected(item); } /** * A placeholder fragment containing a simple view. */ public static class PedometerFragment extends Fragment { private static final String TAG = PedometerFragment.class.getSimpleName(); public PedometerFragment() { setHasOptionsMenu(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_pedometer, container, false); return rootView; } } }
package pingpong; import java.io.IOException; import java.net.InetSocketAddress; import java.util.Scanner; import rmi.RMIException; import rmi.Skeleton; import rmi.*; public class PingPongServer implements PingPongInterface{ public String ping(int idNumber) throws RMIException{ return "Pong " + idNumber; } public static void main(String[] args) { int portNumber; Scanner reader = new Scanner(System.in); System.out.println("Enter the port number for the server to bind(>50000): "); portNumber = Integer.parseInt(reader.nextLine()); // = 55790; PingPongInterface remoteInterface = PingServerFactory.makePingServer(); InetSocketAddress address = new InetSocketAddress(portNumber); System.out.println("Server port number is " + portNumber); Skeleton<PingPongInterface> skeletonServer = new Skeleton<PingPongInterface> (PingPongInterface.class, remoteInterface, address); try { skeletonServer.start(); System.out.println("Server has started"); } catch (RMIException | IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
/** * Where all the events and their handlers locate. * <p> * {@link org.alienideology.jcord.event.handler.EventHandler} are handlers that handle events fired by * {@link org.alienideology.jcord.internal.gateway.GatewayAdaptor}, which are general events such as GuildUpdateEvent. The * {@link org.alienideology.jcord.event.handler.EventHandler} breaks down the gateway event and fire normal * {@link org.alienideology.jcord.event.Event} properly. * {@link org.alienideology.jcord.event.Event} are events that are used firing in {@link org.alienideology.jcord.event.DispatcherAdaptor}. * * </p> * @since 0.0.1 * @author AlienIdeology */ package org.alienideology.jcord.event;
package clientProfileApplication; import javafx.scene.control.ComboBox; import javafx.scene.control.DatePicker; import javafx.scene.control.TextField; import javafx.scene.layout.GridPane; public class ClientProfileBillFilter extends GridPane{ private ComboBox<String> itemCB ; private TextField priceMinFld , priceMaxFld; private DatePicker dateMinFld , dateMaxFld; // constructor public ClientProfileBillFilter() { //children nodes //itemCb itemCB = new ComboBox<String>(); //style itemCB.setPromptText("Désignations"); //priceMin priceMinFld = new TextField(); //style priceMinFld.setPromptText("Total H.T (Min)"); //priceMax priceMaxFld = new TextField(); //Style priceMaxFld.setPromptText("Total H.t (Max)"); //dateMin dateMinFld = new DatePicker(); //Style dateMinFld.setPromptText("Date (Min)"); //date max dateMaxFld = new DatePicker(); //Style dateMaxFld.setPromptText("date (Max)"); // Adding children add(itemCB , 0,0,1,1); add(priceMinFld , 1,0,1,1); add(priceMaxFld , 2,0,1,1); add(dateMinFld , 1,1,1,1); add(dateMaxFld , 2,1,1,1); //Styling layoutS setHgap(10); setVgap(10); } }
package com.wenqiao.redisluttuce; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class RedisLuttuceApplication { public static void main(String[] args) { SpringApplication.run(RedisLuttuceApplication.class, args); } }
package definitions; import com.GeneralMethods; import io.cucumber.java.After; import io.cucumber.java.Before; import org.openqa.selenium.WebDriver; public class Hooks { @Before public void beforeTest() { GeneralMethods.createDriver(); } @After public void afterTest() { WebDriver driver = GeneralMethods.getDriver(); if (driver != null) driver.close(); } }
package com.test; public interface Event { public void action(); }
package vlad.fp.services.synchronous.api; import vlad.fp.services.model.EmailAddress; import vlad.fp.services.model.ReportID; public interface EmailService { void sendReport(EmailAddress emailAddress, ReportID reportID); }
import java.awt.Panel; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPasswordField; import javax.swing.JTextField; @SuppressWarnings("serial") class LoginPanel extends Panel { private JLabel idLabel; private JTextField idTextField; private JLabel pwLabel; private JPasswordField pwField; private JButton loginButton; //private boolean isLogin = false; public LoginPanel() { // ID 세팅 idLabel = new JLabel("ID : "); idTextField = new JTextField(8); // PW 세팅 pwLabel = new JLabel("PASSWORD : "); pwField = new JPasswordField(10); // 로그인 버튼 세팅 loginButton = new JButton("Login"); add(idLabel); add(idTextField); add(pwLabel); add(pwField); add(loginButton); LoginPanel myJPanel = this; // 4번. PreparedStatement 사용 // (SQL Injection을 막기 위함) loginButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { String idS = idTextField.getText(); String pwS = new String(pwField.getPassword()); PreparedStatement pstmt = MainRdp.getInstance().getDbc().con.prepareStatement ("SELECT * " + "FROM 사용자 " + "WHERE 사용자ID=? AND 비밀번호=?"); pstmt.setString(1, idS); pstmt.setString(2, pwS); ResultSet rs = pstmt.executeQuery(); if(rs.next()) { // 로그인 성공 myJPanel.removeAll(); myJPanel.add(new JLabel(rs.getString("닉네임")+"님 환영합니다!!")); myJPanel.revalidate(); myJPanel.repaint(); MainRdp.getInstance().setUsrId(idS); MainRdp.getInstance().setUsrName(rs.getString("닉네임")); System.out.println("로그인 성공"); } else { // 로그인 실패 JOptionPane.showMessageDialog(null, "로그인 실패.", "로그인 실패.", JOptionPane.ERROR_MESSAGE); System.out.println("로그인 실패"); } pstmt.close(); } catch(SQLException e2) { e2.printStackTrace();} } }); } }
class PalindromeNumber { public static boolean isPalindrome1(int x) { String original = String.valueOf(x); String reversed = ""; for (int i=(original.length() - 1); i >= 0; i--) { reversed = reversed + original.charAt(i); } return reversed.equals(original); } public static boolean isPalindrome2(int x){ if(x < 0) return false; int reversed = 0, original = x; while(x != 0) { reversed = reversed * 10 + x % 10; x /= 10; } return original == reversed; } public static void main(String[] args) { System.out.println(isPalindrome1(121)); System.out.println(isPalindrome2(-121)); } }
package org.fhcrc.honeycomb.metapop.stop; import org.fhcrc.honeycomb.metapop.World; /** * Doesn't stop. * * Created on 12 May, 2013 * @author Adam Waite * @version $Rev: 2300 $, $Date: 2013-08-16 12:21:32 -0700 (Fri, 16 Aug 2013) $, $Author: ajwaite $ * */ public class NoStop extends StopCondition { public boolean isMet() { return false; } }
package com.landa.datatypes; import java.io.File; public class PasteFile { public PasteFile(File file, boolean status) { this.file = file; this.status = status; } public static final boolean STATUS_CUT = true; public static final boolean STATUS_COPY = false; File file; public File getFile() { return file; } public void setFile(File file) { this.file = file; } //copy - 0, cut - 1 boolean status; public boolean getStatus() { return status; } public void setStatus(boolean status) { this.status = status; } }
package visitors.design.pattern.example; public interface RouterVisitor { public void visit(BelkinRouter router); public void visit(NetgearRouter router); public void visit(CiscoRouter router); }
package com.store.controller; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.store.pojo.SysPermission; import com.store.service.PermissionService; import com.store.service.PermissionServiceImpl; /** * Servlet implementation class PerAddServlet */ @WebServlet("/PerAddServlet") public class PerAddServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); String name = request.getParameter("permission_name"); String type = request.getParameter("permission_type"); String url = request.getParameter("permission_url"); String sort = request.getParameter("permission_sort"); SysPermission sysPermission = new SysPermission(); sysPermission.setName(name); sysPermission.setType(type); sysPermission.setUrl(url); sysPermission.setSortstring(sort); PermissionService p = new PermissionServiceImpl(); p.addSysPermission(sysPermission); request.getRequestDispatcher("perIndex").forward(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
package net.minecraft.world.storage; import java.io.File; import javax.annotation.Nullable; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.MinecraftException; import net.minecraft.world.WorldProvider; import net.minecraft.world.chunk.storage.IChunkLoader; import net.minecraft.world.gen.structure.template.TemplateManager; public interface ISaveHandler { @Nullable WorldInfo loadWorldInfo(); void checkSessionLock() throws MinecraftException; IChunkLoader getChunkLoader(WorldProvider paramWorldProvider); void saveWorldInfoWithPlayer(WorldInfo paramWorldInfo, NBTTagCompound paramNBTTagCompound); void saveWorldInfo(WorldInfo paramWorldInfo); IPlayerFileData getPlayerNBTManager(); void flush(); File getWorldDirectory(); File getMapFileFromName(String paramString); TemplateManager getStructureTemplateManager(); } /* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\net\minecraft\world\storage\ISaveHandler.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
package com.example.lkplaces.web.validation; public interface ExistingG { }
package collage; import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; import java.text.ParseException; import java.util.Arrays; public class RTSPRequestPacket extends RTSPPacket { private Method method = null; private Integer rtspSeqNum = null; private Integer sessionNum = null; private String url = null; private String rawData = null; // Transport private TransportProtocol transportProtocol = null; private Integer[] clientPorts = {}; private TransportMode transportMode = null; private boolean isStarted = false; private boolean isDone = false; protected RTSPRequestPacket() {} public static RTSPRequestPacket make() { return new RTSPRequestPacket(); } /** * Create and encode a new <code>RTSPRequestPacket</code>. * @return the encoded <code>RTSPRequestPacket</code> * @throws IllegalArgumentException if invalid arguments to encode */ public static RTSPRequestPacket encode(Method reqType, String url, Integer rtspSeqNum, Integer sessionNum) throws IllegalArgumentException { RTSPRequestPacket packet = new RTSPRequestPacket(); packet.method = reqType; packet.rtspSeqNum = rtspSeqNum; packet.sessionNum = sessionNum; packet.url = url; packet.encode(); return packet; } /** * Create and encode a new <code>RTSPRequestPacket</code>. * For a SETUP request, additional parameters are needed. * @return the encoded <code>RTSPRequestPacket</code> * @throws IllegalArgumentException if invalid arguments to encode */ public static RTSPRequestPacket encode(Method method, String url, Integer rtspSeqNum, Integer sessionNum, TransportProtocol transportProtocol, TransportMode transportMode, Integer[] clientPorts) throws IllegalArgumentException { RTSPRequestPacket packet = new RTSPRequestPacket(); packet.method = method; packet.rtspSeqNum = rtspSeqNum; packet.sessionNum = sessionNum; packet.url = url; packet.transportProtocol = transportProtocol; packet.transportMode = transportMode; packet.clientPorts = clientPorts; packet.encode(); return packet; } public static void main(String argv[]) throws Exception { if (argv.length < 1) throw new RuntimeException("Usage: <filename>"); String url = argv[0]; RTSPRequestPacket request; RTSPRequestPacket decoded; StringReader stringReader; BufferedReader reader; // OPTIONS test request = RTSPRequestPacket.encode(Method.OPTIONS, "*", 0, null); decoded = RTSPRequestPacket.make(); stringReader = new StringReader(request.rawData()); reader = new BufferedReader(stringReader); while (!decoded.isDone()) decoded.decode(reader); if (!request.equals(decoded)) System.err.println(request.reqType() + " test failed"); else System.out.println(request.reqType() + " test passed"); // DESCRIBE test request = RTSPRequestPacket.encode(Method.DESCRIBE, url, 1, null); decoded = RTSPRequestPacket.make(); stringReader = new StringReader(request.rawData()); reader = new BufferedReader(stringReader); while (!decoded.isDone()) decoded.decode(reader); if (!request.equals(decoded)) System.err.println(request.reqType() + " test failed"); else System.out.println(request.reqType() + " test passed"); // SETUP test request = RTSPRequestPacket.encode(Method.SETUP, url, 2, null, TransportProtocol.RTP, TransportMode.MULTICAST, new Integer[] {554}); decoded = RTSPRequestPacket.make(); stringReader = new StringReader(request.rawData()); reader = new BufferedReader(stringReader); while (!decoded.isDone()) decoded.decode(reader); if (!request.equals(decoded)) System.err.println(request.reqType() + " test failed"); else System.out.println(request.reqType() + " test passed"); // PLAY test request = RTSPRequestPacket.encode(Method.PLAY, url, 3, 123456); decoded = RTSPRequestPacket.make(); stringReader = new StringReader(request.rawData()); reader = new BufferedReader(stringReader); while (!decoded.isDone()) decoded.decode(reader); if (!request.equals(decoded)) System.err.println(request.reqType() + " test failed"); else System.out.println(request.reqType() + " test passed"); // PAUSE test request = RTSPRequestPacket.encode(Method.PAUSE, url, 4, 123456); decoded = RTSPRequestPacket.make(); stringReader = new StringReader(request.rawData()); reader = new BufferedReader(stringReader); while (!decoded.isDone()) decoded.decode(reader); if (!request.equals(decoded)) System.err.println(request.reqType() + " test failed"); else System.out.println(request.reqType() + " test passed"); // TEARDOWN test request = RTSPRequestPacket.encode(Method.TEARDOWN, url, 5, 123456); decoded = RTSPRequestPacket.make(); stringReader = new StringReader(request.rawData()); reader = new BufferedReader(stringReader); while (!decoded.isDone()) decoded.decode(reader); if (!request.equals(decoded)) System.err.println(request.reqType() + " test failed"); else System.out.println(request.reqType() + " test passed"); } private void decodeMethod(String line) throws ParseException { String[] tokens = line.split("\\s+"); if (tokens.length != 3) throw new ParseException("Invalid method line: " + line, 0); method = Method.valueOf(tokens[0]); try { url = URLDecoder.decode(tokens[1],CHAR_ENCODING); } catch (UnsupportedEncodingException e) { throw new ParseException("Incorrectly encoded url: " + tokens[1], 0); } if (!tokens[2].equals(RTSP_VERSION)) throw new IllegalArgumentException("Unsupported RTSP Version: " + tokens[2]); } private void decodeSeqNum(String line) throws ParseException { String[] tokens = line.split(":"); if (tokens.length != 2) throw new ParseException("Invalid sequence num line: " + line, 0); try { rtspSeqNum = Integer.parseInt(tokens[1].trim()); } catch (NumberFormatException e) { throw new ParseException("Invalid sequence num: " + tokens[1], 0); } } private void decodeSessionNum(String line) throws ParseException { String[] tokens = line.split(":"); if (tokens.length != 2) throw new ParseException("Invalid session num line: " + line, 0); try { sessionNum = Integer.parseInt(tokens[1].trim()); } catch (NumberFormatException e) { throw new ParseException("Invalid session num: " + tokens[1], 0); } } public void decodeTransport(String line) throws ParseException { String[] tokens = line.split(":",2); if (tokens.length != 2) throw new ParseException("Invalid transport line: " + line, 0); String[] params = tokens[1].trim().split(";"); for (int i=0; i<params.length; i++) { boolean found = false; try { if (params[i].contains("client_port")) { String[] paramPair = params[i].split("="); if (paramPair.length != 2) throw new ParseException("Invalid param in transport line: " + params[i], 0); paramPair = paramPair[1].split("-"); clientPorts = new Integer[paramPair.length]; for (int j=0; j<paramPair.length; j++) clientPorts[j] = Integer.parseInt(paramPair[j]); found = true; } else { for (int j=0; j<TransportProtocol.values().length; j++) if (TransportProtocol.values()[j].name().equals(params[i])) { transportProtocol = TransportProtocol.values()[j]; found = true; } for (int j=0; j<TransportMode.values().length; j++) if (TransportMode.values()[j].rtspName().equals(params[i])) { transportMode = TransportMode.values()[j]; found = true; } } } catch (Exception e) { throw new ParseException("Invalid param in transport line: " + params[i], 0); } if (!found) throw new ParseException("Unknown transport parameter: " + params[i], 0); } } public void decode(String line) throws ParseException { if (line.length() == 0 && !isStarted) return; if (rawData == null) rawData = ""; rawData += line + CRLF; if (!isStarted) { decodeMethod(line); isStarted = true; return; } if (line.length() == 0) { isDone = true; return; } String[] pair = line.split(":",2); if (pair.length != 2) throw new IllegalArgumentException("Invalid header line: " + line); switch (pair[0]) { case "CSeq": decodeSeqNum(line); break; case "Session": decodeSessionNum(line); break; case "Transport": decodeTransport(line); break; default: throw new IllegalArgumentException("Unsupported header type: " + pair[0]); } } /** * Call repeatedly on same <code>BufferedReader</code>. Check <code>isDone()</code> for response completeness. * @param reader already open <code>BufferedReader</code> * @throws IOException if failed to read line from <code>reader</code> * @throws ParseException if error parsing input format * @throws IllegalArgumentException if correctly formatted invalid input */ public void decode(BufferedReader reader) throws IOException, ParseException, IllegalArgumentException { if (isDone) throw new RuntimeException("Packet already complete"); String line = reader.readLine(); decode(line); } private String encodeMethod() throws UnsupportedEncodingException { String ret = method.toString() + " "; ret += URLEncoder.encode(url,CHAR_ENCODING); ret += " " + RTSP_VERSION + CRLF; return ret; } private String encodeSeqNum() { return "CSeq: " + rtspSeqNum + CRLF; } private String encodeSessionNum() { String ret = ""; if (sessionNum != null) ret = "Session: " + sessionNum + CRLF; return ret; } private String encodeTransport() { String ret = ""; if (transportProtocol != null || clientPorts.length > 0 || transportMode != null) { ret += "Transport: "; if (transportProtocol != null) { for (int i=0; i<TransportProtocol.values().length-1; i++) ret += TransportProtocol.values()[i] + "/"; ret += TransportProtocol.values()[TransportProtocol.values().length-1] + ";"; } if (clientPorts.length > 0) { ret += "client_port=" + clientPorts[0]; if (clientPorts.length > 1) ret += "-" + clientPorts[1]; ret += ";"; } if (transportMode != null) { ret += transportMode.rtspName() + ";"; } ret += CRLF; } return ret; } private void encode() { String encodedPacket = ""; try { encodedPacket += encodeMethod(); } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException("Failed to encode url: " + url); } encodedPacket += encodeSeqNum(); encodedPacket += encodeSessionNum(); encodedPacket += encodeTransport(); encodedPacket += CRLF; this.rawData = encodedPacket; } @Override public int hashCode() { int code = 1; code = code * 31 + method.ordinal(); code = code * 17 + rtspSeqNum; code = code * 31 + sessionNum; code = code * 17 + url.hashCode(); code = code * 31 + transportProtocol.ordinal(); code = code * 17 + Arrays.hashCode(clientPorts); code = code * 31 + transportMode.ordinal(); return code; } @Override public boolean equals(Object obj) { if (!(obj instanceof RTSPRequestPacket)) return false; RTSPRequestPacket other = (RTSPRequestPacket)obj; if (method != other.method) return false; if (rtspSeqNum != other.rtspSeqNum && !(rtspSeqNum != null && rtspSeqNum.equals(other.rtspSeqNum))) return false; if (sessionNum != other.sessionNum && !(sessionNum != null && sessionNum.equals(other.sessionNum))) return false; if (!url.equals(other.url)) return false; if (transportProtocol != other.transportProtocol) return false; if (clientPorts.length != 0 && !Arrays.equals(clientPorts, other.clientPorts)) return false; if (transportMode != other.transportMode) return false; return true; } @Override public String toString() { String out = ""; if (method != null) out += "Method: " + method + CRLF; if (rtspSeqNum != null) out += "CSeq: " + rtspSeqNum + CRLF; if (sessionNum != null) out += "Session: " + sessionNum + CRLF; if (url != null) out += "Url: " + url + CRLF; if (transportProtocol != null) out += "Transport Protocol: " + transportProtocol + CRLF; if (clientPorts.length > 0) out += "Client Ports: " + clientPorts + CRLF; if (transportMode != null) out += "Transport Mode: " + transportMode + CRLF; if (rawData != null) out += rawData + CRLF; return out; } public Method reqType() { return method; } public Integer rtspSeqNum() { return rtspSeqNum; } public Integer sessionNum() { return sessionNum; } public String url() { return url; } public TransportProtocol transportProtocol() { return transportProtocol; } public Integer[] clientPorts() { return clientPorts; } public TransportMode transportMode() { return transportMode; } public String rawData() { return rawData; } public boolean isStarted() { return isStarted; } public boolean isDone() { return isDone; } }
package com.github.ovchingus.core; public class Options { private static int searchLimit = 30; private static int foundResults; private static boolean autoCorrect = false; private static int cachedFiles = 50; private static String cachePath = "src/main/java/com/github/ovchingus/cache/"; static String getAPIKey() { return "681a7e3b8f399718fdf98338420653d7"; } static String getAPIRootURL() { return "http://ws.audioscrobbler.com/2.0/"; } static int getSearchLimit() { return searchLimit; } public static void setSearchLimit(int searchLimit) { Options.searchLimit = searchLimit; } static int getFoundResults() { return foundResults; } static void setFoundResults(int foundResults) { Options.foundResults = foundResults; } static int isAutoCorrect() { if (autoCorrect) return 1; else return 0; } public static void setAutoCorrect(boolean autoCorrect) { Options.autoCorrect = autoCorrect; } static int getCachedFiles() { return cachedFiles; } public static void setCachedFiles(int cachedFiles) { Options.cachedFiles = cachedFiles; } static String getCachePath() { return cachePath; } static void setCachePath(String cachePath) { Options.cachePath = cachePath; } }
package com.gepengjun.learn.service.role; import com.gepengjun.learn.model.Role; public interface RoleService { Role findById(Long roleId); }
package com.kingbbode.bot.common.base.api; import com.kingbbode.bot.common.request.BrainRequest; import com.kingbbode.bot.common.result.BrainResult; /** * Created by YG on 2017-01-26. */ public abstract class AbstractBotApi<T extends ApiData> implements BotApi<T> { public BrainResult execute(BrainRequest brainRequest) { T api = getRequest(brainRequest.getCommand()); return new BrainResult.Builder() .room(brainRequest.getRoom()) .result(get(api)) .type(api.response()) .build(); } }
package com.services.utils.collection; import com.services.utils.object.FieldUtil; import java.util.LinkedHashMap; import java.util.Map; public class MapUtil { public static Map<String, Object> parseMap(Object obj) { if (null == obj) { return null; } Map<String, Object> map = new LinkedHashMap<String, Object>(); String[] pros = FieldUtil.propertys(obj.getClass()); for (String pro : pros) { map.put(pro, FieldUtil.get(obj, pro)); } return map; } public static Map<String, String> parseStringMap(Object obj) { if (null == obj) { return null; } Map<String, String> map = new LinkedHashMap<String, String>(); String[] pros = FieldUtil.propertys(obj.getClass()); Object o; for (String pro : pros) { o = FieldUtil.get(obj, pro); if (null == o) map.put(pro, null); else map.put(pro, o.toString()); } return map; } public static Map<String, String> parseStringMapNoNullValue(Object obj) { if (null == obj) { return null; } Map<String, String> map = new LinkedHashMap<String, String>(); String[] pros = FieldUtil.propertys(obj.getClass()); Object o; for (String pro : pros) { o = FieldUtil.get(obj, pro); if (null != o) map.put(pro, o.toString()); } return map; } public static <T> T parseObject(Map map, Class<T> objClass) { if (null == map) { return null; } T t; try { t = objClass.newInstance(); } catch (Exception e) { throw new RuntimeException(e); } if (Map.class.isAssignableFrom(objClass)) { ((Map) t).putAll(map); } else { String[] pros = FieldUtil.propertys(objClass); for (String pro : pros) { FieldUtil.set(t, pro, map.get(pro)); } } return t; } public static void fillObject(Map map, Object obj) { if (null == map || null == obj) { return; } if (obj instanceof Map) { ((Map) obj).putAll(map); } else { String[] pros = FieldUtil.propertys(obj.getClass()); for (String pro : pros) { if (map.get(pro) instanceof Map) { fillObject((Map) map.get(pro), FieldUtil.get(obj, pro)); } FieldUtil.set(obj, pro, map.get(pro)); } } } public static class Obj { private String name; private Obj son; public String getName() { return name; } public void setName(String name) { this.name = name; } public Obj getSon() { return son; } public void setSon(Obj son) { this.son = son; } } }
package com.tencent.mm.plugin.sns; import com.tencent.mm.ab.e; import com.tencent.mm.ab.l; import com.tencent.mm.g.a.hr; import com.tencent.mm.g.a.ob; import com.tencent.mm.kernel.g; import com.tencent.mm.plugin.sns.model.af; import com.tencent.mm.plugin.sns.model.aj; import com.tencent.mm.plugin.sns.model.q; import com.tencent.mm.plugin.sns.storage.n; import com.tencent.mm.protocal.c.boy; import com.tencent.mm.protocal.c.boz; import com.tencent.mm.sdk.b.a; import com.tencent.mm.sdk.b.c; import com.tencent.mm.sdk.platformtools.al; import com.tencent.mm.sdk.platformtools.x; public final class d extends c<hr> implements e { private int nha; private boy nhb; private n nhc; private al nhd; public d() { this.sFo = hr.class.getName().hashCode(); } private boolean a(hr hrVar) { if (hrVar instanceof hr) { this.nha = hrVar.bRa.bMQ; this.nhc = af.byo().xd(this.nha); this.nhb = aj.m(this.nhc); if (this.nhb == null || ((this.nhb.rXx != 3 || this.nhb.smW == null || this.nhb.smW.size() <= 0) && (this.nhb.rXx != 5 || this.nhb.rWm == null || this.nhb.rWm.size() <= 0))) { q qVar = new q(this.nhc.field_snsId); ((boz) qVar.diG.dID.dIL).snc = 1; g.Ek(); g.Eh().dpP.a(210, this); g.Ek(); g.Eh().dpP.a(qVar, 0); this.nhd = new al(new 1(this), false); this.nhd.J(10000, 10000); return true; } hrVar.bRb.bRc = this.nhb; return true; } x.f("MicroMsg.GetSnsObjectDetailListener", "mismatched event"); return false; } public final void a(int i, int i2, String str, l lVar) { x.i("MicroMsg.GetSnsObjectDetailListener", "dz:[onSceneEnd]errType:%d errCode:%d errMsg:%s", new Object[]{Integer.valueOf(i), Integer.valueOf(i2), str}); this.nhd.SO(); if (i == 0 && i2 == 0) { n fi = af.byo().fi(this.nhc.field_snsId); ob obVar = new ob(); obVar.bYX.bRc = aj.m(fi); a.sFg.m(obVar); return; } ob obVar2 = new ob(); obVar2.bYX.bRc = null; a.sFg.m(obVar2); } }
package com.zhongkk.spi.video.tencent.player; import com.zhongkk.spi.video.player.VideoPlayer; /** * Description 腾讯播放器 * * @author Created by 叶半仙 on 2019/7/3. */ public class TencentVideoPlayer implements VideoPlayer { /** * 播放 * * @param url * @return */ @Override public String play(String url) { return playerName()+": "+url; } /** * 获取对应时长 * * @param url */ @Override public long duration(String url) { return url.length(); } /** * 播放器名称 * * @return */ @Override public String playerName() { return "腾讯视频"; } /** * 播放器版本 */ @Override public String playerVersion() { return "1.0.0-SNAPSHOT"; } }
package engines; import bots.MotherBot; import java.util.ArrayList; public class Statistic { private ArrayList<Game> gameList = new ArrayList<>(); private MotherBot[] botList; private int[] nbWin = {0, 0, 0, 0}; private double[] ratio = {0, 0, 0, 0}; private double[] ecartType = {0 , 0, 0 ,0}; private int[] moyenneNbtour = {0, 0, 0, 0}; private float[] moyenneScore = {0, 0, 0, 0}; private int egaliteNb = 0; private int errorNb = 0; public Statistic(MotherBot[] botList){ this.botList = botList; } /**Ajoute la partie g à la liste des parties dont on étudies les stats. * @param g la partie terminé. */ public void addGame(Game g) { gameList.add(g); } /** * Affiche les satistiques des parties jouées : parties gagnées, égalités, non finies, scores moyens. */ public void displayStatistic(){ for (Game g: gameList) { boolean egalite = false; for(int i = 0; i<botList.length; i++) { if (g.getBotList()[i].getWinner() && egalite) egaliteNb++; if (g.getBotList()[i].getWinner()) { egalite = true; this.nbWin[i]++; moyenneScore[i] += g.getBotList()[i].getTotalScore(); } } if(g.getError()) errorNb++; } for(int i = 0; i<botList.length; i++) { moyenneScore[i] /= gameList.size(); } for(int i = 0; i<botList.length; i++) ratio[i] = (double) nbWin[i]/gameList.size(); for(int i = 0; i<botList.length; i++) ecartType[i] = Math.rint(Math.sqrt(Math.pow((1-ratio[i]), 2.0) * nbWin[i])); System.out.println("\n// Statistiques \\\\\n "); System.out.println("Sur " + gameList.size() + " parties : \n"); for(int i = 0; i<botList.length; i++) { System.out.println("- "+botList[i] + " a gagne " + nbWin[i] + " parties, soit " + Math.round(ratio[i]*100) + "% des parties. Il a obtenu un score moyen de " + Math.round(moyenneScore[i]) + " points par partie."); } System.out.println("\n- Il y a eu "+ egaliteNb + " egalite(s), soit "+(egaliteNb*100)/gameList.size()+"% des parties."); System.out.println("- "+errorNb + " partie(s) ne se sont pas terminees en moins de 300 tours, soit "+(errorNb*100)/gameList.size()+"% des parties.\n"); } }
package org.apache.commons.net.smtp; import java.util.Enumeration; import java.util.Vector; public final class RelayPath { Vector<String> _path; String _emailAddress; public RelayPath(String emailAddress) { this._path = new Vector<>(); this._emailAddress = emailAddress; } public void addRelay(String hostname) { this._path.addElement(hostname); } public String toString() { StringBuilder buffer = new StringBuilder(); buffer.append('<'); Enumeration<String> hosts = this._path.elements(); if (hosts.hasMoreElements()) { buffer.append('@'); buffer.append(hosts.nextElement()); while (hosts.hasMoreElements()) { buffer.append(",@"); buffer.append(hosts.nextElement()); } buffer.append(':'); } buffer.append(this._emailAddress); buffer.append('>'); return buffer.toString(); } } /* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\org\apache\commons\net\smtp\RelayPath.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
/* * Copyright (C) 2019-2023 Hedera Hashgraph, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hedera.mirror.importer.parser.record.transactionhandler; import com.hedera.mirror.common.domain.entity.Entity; import com.hedera.mirror.common.domain.entity.EntityId; import com.hedera.mirror.common.domain.schedule.Schedule; import com.hedera.mirror.common.domain.transaction.RecordItem; import com.hedera.mirror.common.domain.transaction.Transaction; import com.hedera.mirror.common.domain.transaction.TransactionType; import com.hedera.mirror.common.util.DomainUtils; import com.hedera.mirror.importer.domain.EntityIdService; import com.hedera.mirror.importer.parser.record.entity.EntityListener; import com.hedera.mirror.importer.parser.record.entity.EntityProperties; import jakarta.inject.Named; @Named class ScheduleCreateTransactionHandler extends AbstractEntityCrudTransactionHandler { private final EntityProperties entityProperties; ScheduleCreateTransactionHandler( EntityIdService entityIdService, EntityListener entityListener, EntityProperties entityProperties) { super(entityIdService, entityListener, TransactionType.SCHEDULECREATE); this.entityProperties = entityProperties; } @Override public EntityId getEntity(RecordItem recordItem) { return EntityId.of(recordItem.getTransactionRecord().getReceipt().getScheduleID()); } @Override protected void doUpdateEntity(Entity entity, RecordItem recordItem) { var transactionBody = recordItem.getTransactionBody().getScheduleCreate(); if (transactionBody.hasAdminKey()) { entity.setKey(transactionBody.getAdminKey().toByteArray()); } entity.setMemo(transactionBody.getMemo()); entityListener.onEntity(entity); } @Override protected void doUpdateTransaction(Transaction transaction, RecordItem recordItem) { if (!recordItem.isSuccessful() || !entityProperties.getPersist().isSchedules()) { return; } var body = recordItem.getTransactionBody().getScheduleCreate(); long consensusTimestamp = recordItem.getConsensusTimestamp(); var creatorAccount = recordItem.getPayerAccountId(); var expirationTime = body.hasExpirationTime() ? DomainUtils.timestampInNanosMax(body.getExpirationTime()) : null; var payerAccount = body.hasPayerAccountID() ? EntityId.of(body.getPayerAccountID()) : creatorAccount; var scheduleId = EntityId.of(recordItem.getTransactionRecord().getReceipt().getScheduleID()); Schedule schedule = new Schedule(); schedule.setConsensusTimestamp(consensusTimestamp); schedule.setCreatorAccountId(creatorAccount); schedule.setExpirationTime(expirationTime); schedule.setPayerAccountId(payerAccount); schedule.setScheduleId(scheduleId); schedule.setTransactionBody(body.getScheduledTransactionBody().toByteArray()); schedule.setWaitForExpiry(body.getWaitForExpiry()); entityListener.onSchedule(schedule); recordItem.addEntityId(payerAccount); } }
/* * 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 producercustomer; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Insets; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; /** * * @author holiyo */ public class PCPanel extends JPanel{ public JLabel progressLabel1; public JLabel progressLabel2; public JLabel progressLabel3; public JLabel progressLabel4; public JLabel progressLabel5; public JLabel progressLabel6; public JTextField proField; JButton bt_start1; JButton bt_stop1; JButton bt_start2; JButton bt_stop2; public PCPanel() { BufferedImage img0=null,img1=null,img2=null,img3=null,img4=null; try{ img0=ImageIO.read(new File("./image/工厂.jpg")); // img1=ImageIO.read(new File("./image/购物车.jpg")); img2=ImageIO.read(new File("./image/仓库.jpg")); img3=ImageIO.read(new File("./image/顾客.jpg")); img4=ImageIO.read(new File("./image/苹果.jpg")); }catch(IOException e) { e.printStackTrace(); } int width=Toolkit.getDefaultToolkit().getScreenSize().width; int height=Toolkit.getDefaultToolkit().getScreenSize().height; setLayout(null); // System.out.println(img0.getWidth()/2); // System.out.println(img2.getWidth()/2); // System.out.println(img3.getWidth()/2); proField=new JTextField(); progressLabel1=new JLabel(); progressLabel2=new JLabel(); progressLabel3=new JLabel(); progressLabel4=new JLabel(); progressLabel5=new JLabel(); progressLabel6=new JLabel(); bt_start1=new Button("开始生产"); bt_stop1=new Button("暂停生产"); bt_start2=new Button("开始消费"); bt_stop2=new Button("暂停消费"); proField.setBounds(width/2-380, height/2+250,800,40); proField.setBackground(new Color(230,237,165)); add(proField); progressLabel5.setIcon(new ImageIcon(img4)); progressLabel5.setBounds(width/2-800, height/2-img0.getWidth()/2,img0.getWidth(),img0.getHeight()); System.out.println(progressLabel5.getX()+" "+progressLabel5.getY()); // progressLabel6.setIcon(new ImageIcon(img4)); // progressLabel6.setBounds(width/2+600, height/2-img3.getHeight()/2,img3.getWidth(),img3.getHeight()); add(progressLabel5); // add(progressLabel6); progressLabel1.setIcon(new ImageIcon(img0)); progressLabel1.setBounds(width/2-800, height/2-img0.getWidth()/2,img0.getWidth(),img0.getHeight()); bt_start1.setMargin(new Insets(0,0,0,0)); bt_start1.setBounds(width/2-780, height/2+110, 80, 40); bt_stop1.setMargin(new Insets(0,0,0,0)); bt_stop1.setBounds(width/2-700, height/2+110, 80, 40); add(progressLabel1); add(bt_start1); add(bt_stop1); bt_start1.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { producer.flag=true; } }); bt_stop1.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { producer.flag=false; } }); progressLabel2.setIcon(new ImageIcon(img2)); progressLabel2.setBounds(width/2-100, height/2-img2.getWidth()/2+13,img2.getWidth(),img2.getHeight()); add(progressLabel2); bt_start2.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { consumer.flag=true; } }); bt_stop2.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { consumer.flag=false; } }); progressLabel3.setIcon(new ImageIcon(img3)); progressLabel3.setBounds(width/2+600, height/2-img3.getHeight()/2,img3.getWidth(),img3.getHeight()); bt_start2.setMargin(new Insets(0,0,0,0)); bt_start2.setBounds(width/2+630,height/2+110, 80, 40); bt_stop2.setMargin(new Insets(0,0,0,0)); bt_stop2.setBounds(width/2+710, height/2+110,80, 40); add(progressLabel3); add(bt_start2); add(bt_stop2); // progressLabel4.setIcon(new ImageIcon(img1)); // progressLabel4.setBounds(width/2-img1.getWidth()/2, height/2-400,img1.getWidth(),img1.getHeight()); // // add(progressLabel4); } }
package com.koreait.dao; import java.util.Map; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import com.koreait.dto.MemberDto; import com.koreait.mybatis.config.DBService; public class MDao { // Field private SqlSessionFactory factory = null; // Singleton private MDao() { factory = DBService.getFactory(); } private static MDao dao = new MDao(); public static MDao getInstance() { return dao; } // Method public MemberDto getMemberBymIdmPw(MemberDto mDto) { SqlSession sqlSession = factory.openSession(); MemberDto dto = sqlSession.selectOne("select_by_mId_mPw", mDto); sqlSession.close(); return dto; } public MemberDto getMemberBymEmail(String mEmail) { SqlSession sqlSession = factory.openSession(); MemberDto dto = sqlSession.selectOne("select_by_mEail", mEmail); sqlSession.close(); return dto; } public MemberDto getMemberBymIdmPhone(Map<String, String> map) { SqlSession sqlSession = factory.openSession(); MemberDto dto = sqlSession.selectOne("select_by_mId_mPhone", map); sqlSession.close(); return dto; } public int getUpdatemPw(Map<String, String> map) { SqlSession sqlSession = factory.openSession(false); int result = sqlSession.update("update_mPw",map); if(result > 0 ) { sqlSession.commit(); } sqlSession.close(); return result; } public MemberDto getMemberBymId(String mId) { SqlSession sqlSession = factory.openSession(); MemberDto dto = sqlSession.selectOne("select_by_mId", mId); sqlSession.close(); return dto; } public int getInsertJoin(MemberDto mDto) { SqlSession sqlSession = factory.openSession(false); int result = sqlSession.update("insert_join",mDto); if(result > 0 ) { sqlSession.commit(); } sqlSession.close(); return result; } public int getDeleteMember(String mId) { SqlSession sqlSession = factory.openSession(false); int result = sqlSession.delete("delete_member",mId); if(result > 0 ) { sqlSession.commit(); } sqlSession.close(); return result; } public int getUpdateMember(MemberDto mDto) { SqlSession sqlSession = factory.openSession(false); int result = sqlSession.update("update_member",mDto); if(result > 0 ) { sqlSession.commit(); } sqlSession.close(); return result; } }
package com.github.hippo.zipkin; /** * zipkin 通用工具类 */ public class ZipkinUtils { public static ZipkinResp zipkinRecordStart(ZipkinReq zipkinReq, ZipkinRecordService zipkinRecordService) { if (zipkinRecordService == null) { return null; } return zipkinRecordService.start(zipkinReq); } public static void zipkinRecordFinish(ZipkinResp zipkinResp, ZipkinRecordService zipkinRecordService) { if (zipkinRecordService == null) { return; } zipkinRecordService.finish(zipkinResp); } public static void zipkinRecordError(ZipkinResp zipkinResp, ZipkinRecordService zipkinRecordService, Throwable throwable) { if (zipkinRecordService == null) { return; } zipkinRecordService.error(zipkinResp,throwable); } public static void zipkinRecordFinish(ZipkinResp zipkinResp, ZipkinRecordService zipkinRecordService, Throwable throwable) { if (zipkinRecordService == null) { return; } zipkinRecordService.finish(zipkinResp,throwable); } }
package com.lis2.math; import java.util.ArrayList; public class Lesson5_1 { //已知有4中面额,求10元的组合 public static void main(String[] args) { get(10,new ArrayList<Long>()); } private static long[] reward = {1,2,5,10}; public static void get(long totalReward,ArrayList<Long> result) { if (totalReward==0) { System.out.println(result); return ; }else if (totalReward<0) { return ; }else { for (int i = 0; i < reward.length; i++) { ArrayList<Long> newResult = (ArrayList<Long>)result.clone(); newResult.add(reward[i]); get(totalReward-reward[i], newResult); } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hudi.table.action.commit; import org.apache.hudi.common.model.HoodieKey; import org.apache.hudi.common.model.HoodieRecord; import org.apache.hudi.common.model.HoodieRecordPayload; import org.apache.hudi.exception.HoodieUpsertException; import org.apache.hudi.index.HoodieIndex; import org.apache.hudi.table.HoodieTable; import org.apache.hudi.table.action.HoodieWriteMetadata; import org.apache.spark.api.java.JavaRDD; import org.apache.spark.api.java.JavaSparkContext; import java.time.Duration; import java.time.Instant; import scala.Tuple2; public class WriteHelper<T extends HoodieRecordPayload<T>> { public static <T extends HoodieRecordPayload<T>> HoodieWriteMetadata write(String instantTime, JavaRDD<HoodieRecord<T>> inputRecordsRDD, JavaSparkContext jsc, HoodieTable<T> table, boolean shouldCombine, int shuffleParallelism, CommitActionExecutor<T> executor, boolean performTagging) { try { // De-dupe/merge if needed JavaRDD<HoodieRecord<T>> dedupedRecords = combineOnCondition(shouldCombine, inputRecordsRDD, shuffleParallelism, table); Instant lookupBegin = Instant.now(); JavaRDD<HoodieRecord<T>> taggedRecords = dedupedRecords; if (performTagging) { // perform index loop up to get existing location of records taggedRecords = tag(dedupedRecords, jsc, table); } Duration indexLookupDuration = Duration.between(lookupBegin, Instant.now()); HoodieWriteMetadata result = executor.execute(taggedRecords); result.setIndexLookupDuration(indexLookupDuration); return result; } catch (Throwable e) { if (e instanceof HoodieUpsertException) { throw (HoodieUpsertException) e; } throw new HoodieUpsertException("Failed to upsert for commit time " + instantTime, e); } } private static <T extends HoodieRecordPayload<T>> JavaRDD<HoodieRecord<T>> tag( JavaRDD<HoodieRecord<T>> dedupedRecords, JavaSparkContext jsc, HoodieTable<T> table) { // perform index loop up to get existing location of records return table.getIndex().tagLocation(dedupedRecords, jsc, table); } public static <T extends HoodieRecordPayload<T>> JavaRDD<HoodieRecord<T>> combineOnCondition( boolean condition, JavaRDD<HoodieRecord<T>> records, int parallelism, HoodieTable<T> table) { return condition ? deduplicateRecords(records, table, parallelism) : records; } /** * Deduplicate Hoodie records, using the given deduplication function. * * @param records hoodieRecords to deduplicate * @param parallelism parallelism or partitions to be used while reducing/deduplicating * @return RDD of HoodieRecord already be deduplicated */ public static <T extends HoodieRecordPayload<T>> JavaRDD<HoodieRecord<T>> deduplicateRecords( JavaRDD<HoodieRecord<T>> records, HoodieTable<T> table, int parallelism) { return deduplicateRecords(records, table.getIndex(), parallelism); } public static <T extends HoodieRecordPayload<T>> JavaRDD<HoodieRecord<T>> deduplicateRecords( JavaRDD<HoodieRecord<T>> records, HoodieIndex<T> index, int parallelism) { boolean isIndexingGlobal = index.isGlobal(); return records.mapToPair(record -> { HoodieKey hoodieKey = record.getKey(); // If index used is global, then records are expected to differ in their partitionPath Object key = isIndexingGlobal ? hoodieKey.getRecordKey() : hoodieKey; return new Tuple2<>(key, record); }).reduceByKey((rec1, rec2) -> { @SuppressWarnings("unchecked") T reducedData = (T) rec1.getData().preCombine(rec2.getData()); // we cannot allow the user to change the key or partitionPath, since that will affect // everything // so pick it from one of the records. return new HoodieRecord<T>(rec1.getKey(), reducedData); }, parallelism).map(Tuple2::_2); } }
package domain.enums; public enum Shape { CIRCLE, X; }
/* * 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 telusko1; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; /** * * @author lenovo */ public class Telusko1 { /** * @param args the command line arguments */ public static void main(String[] args) { ApplicationContext context=new AnnotationConfigApplicationContext(AppConfig.class); Laptop l1=context.getBean(Laptop.class); Alien a1=context.getBean(Alien.class); a1.setComp(l1); a1.show(); } }
package FFSSM; import java.util.Calendar; import java.util.LinkedList; import java.util.List; public class Plongeur extends Personne{ private List<Licence> licences = new LinkedList<>(); private int niveau = 0; private GroupeSanguin groupe = GroupeSanguin.APLUS; public Plongeur(String numeroINSEE, String nom, String prenom, String adresse, String telephone, Calendar naissance, Licence l) { super(numeroINSEE, nom, prenom, adresse, telephone, naissance); licences.add(l); } public void ajouteLicence(Licence l) { if (null == l) throw new IllegalArgumentException("l is null"); licences.add(l); } public Licence derniereLicence() { return licences.get(licences.size() - 1); } /** * Get the value of groupe * * @return the value of groupe */ public GroupeSanguin getGroupe() { return groupe; } /** * Set the value of groupe * * @param groupe new value of groupe */ public void setGroupe(GroupeSanguin groupe) { this.groupe = groupe; } /** * Get the value of niveau * * @return the value of niveau */ public int getNiveau() { return niveau; } /** * Set the value of niveau * * @param niveau new value of niveau */ public void setNiveau(int niveau) { this.niveau = niveau; } }
package com.javasongkb.changgou.mapper; import com.javasongkb.changgou.model.OauthClientDetails; public interface OauthClientDetailsMapper { int deleteByPrimaryKey(String clientId); int insert(OauthClientDetails record); int insertSelective(OauthClientDetails record); OauthClientDetails selectByPrimaryKey(String clientId); int updateByPrimaryKeySelective(OauthClientDetails record); int updateByPrimaryKey(OauthClientDetails record); }
package com.cg.hcs.service; import java.util.List; import com.cg.hcs.entity.DiagnosticCenter; import com.cg.hcs.entity.Test; import com.cg.hcs.exception.HCSException; public interface IAdminService { public String addCenter(DiagnosticCenter center); public List<DiagnosticCenter> viewAllCenters(); public String addTest(Test test); public boolean deleteCenter(DiagnosticCenter center); public boolean removeTest(Test test); public boolean approveAppointment(); }
package com.ibm.ive.tools.japt.obfuscation; import java.util.*; import com.ibm.jikesbt.*; import com.ibm.ive.tools.japt.*; /** * @author sfoley * <p> * The following class produces sets of methods and fields which can all have the same name * in order to maximize compression. * * Consider the following: * * class A { * int x; * } * * class B { * int y = A.x; * } * * In this example, we can rename x and y to have the same name, * which allows us to re-use the contant pool reference to x in B: * once to refer to the reference to B and once to refer to the field y. * In addition, the constant pool of B will contain a name-type entry for * A.A and for B.A. Since they both have the same name and they are * both the same type, this entry can be the same for both fields. * * * The following is the optimal solution: * class A { * int A; * } * * class B { * int A = A.A; * } * * * The sets constructed are as large as possible. This class employs an algorithm that attempts * to duplicate method and field names, overload method names, and duplicate method and field name-types, thus * reducing the size of the constant pools of the classes containing those methods. * * Special care must be taken not to alter the semantics of the classes. * For instance, if methods are overridden or are implementations of interface methods, then the names * must remain the same. Two methods in the same class with the same parameter lists cannot be given the same name. * Methods of child and parent classes with the same signatures but different * names cannot be given the same name in the event that one overrides the other. Fields of child and parent * classes cannot be given the same name in the event that a field lookup on a child that delegates to a field * in the parent must find the parent field, and not a child field that has been given the same name. * */ class ReferenceLinkedSetCreator { private final BT_ClassVector classes; private final NameHandler nameHandler; private final RelatedMethodMap relatedMethodMap; private final JaptRepository repository; private List linkedSetList = new LinkedList(); private final Map linkedSetMap = new HashMap(); //maps any field, or method to its corresponding linked set. private Set ownedItems = new HashSet(); //all fields and methods that have been assigned to a set public ReferenceLinkedSetCreator(JaptRepository repository, NameHandler nameHandler) { this.classes = repository.getClasses(); this.relatedMethodMap = repository.getRelatedMethodMap(); this.nameHandler = nameHandler; this.repository = repository; constructLinkedSets(); //allow for some garbage collection: ownedItems = null; } ReferenceLinkedSet getLinkedSet(BT_Item item) { return (ReferenceLinkedSet) linkedSetMap.get(item); } ReferenceLinkedSet[] getAllLinkedSets() { return (ReferenceLinkedSet[]) linkedSetList.toArray(new ReferenceLinkedSet[linkedSetList.size()]); } private void constructLinkedSets() { for(int i=0; i<classes.size(); i++) { BT_Class clazz = classes.elementAt(i); if(!clazz.isArray() && !clazz.isPrimitive()) { constructLinkedSets(clazz); } } //System.out.println("Total members: " + counter); //System.out.println("Total sets: " + setCounter); } //static int counter = 0; //static int setCounter; private void constructLinkedSets(BT_Class clazz) { BT_MethodVector methods = clazz.getMethods(); for(int i=0; i<methods.size(); i++) { //counter++; BT_Method method = methods.elementAt(i); if(!memberIsNotAvailable(method)) { ReferenceLinkedSet set = createReferenceLinkedSet(clazz, method); if(set != null) { linkedSetList.add(set); //setCounter++; //System.out.println("New set with size " + set.size()); } } } BT_FieldVector fields = clazz.getFields(); for(int i=0; i<fields.size(); i++) { BT_Field field = fields.elementAt(i); //counter++; if(!memberIsNotAvailable(field)) { ReferenceLinkedSet set = createReferenceLinkedSet(clazz, field); if(set != null) { linkedSetList.add(set); //setCounter++; //System.out.println("New set with size " + set.size()); } } } } /** * The ordering of this list is important. Name-types (not just names) are duplicated * as much as possible by choosing targets in a specific order. */ private void serviceList(ReferenceLinkedSet constructedSet, ReferenceLinkedSetList list) { topLoop: do { /* * these targets are used to attempt to duplicate method signatures. This allows * for the duplication of name-type and type constant pool entries, in addition to the UTF8 * string entries. */ do { ReferenceLinkedSetList.ClassMethodTarget target = list.getNextClassMethodTarget(); if(target == null) { break; } boolean foundLink = false; BT_Class clazz = target.clazz; BT_MethodVector targetClazzMethods = clazz.getMethods(); for(int k=0; k<targetClazzMethods.size(); k++) { BT_Method targetClazzMethod = targetClazzMethods.elementAt(k); if(RelatedMethodMap.signaturesMatch(targetClazzMethod.getSignature(), target.signature)) { if(tryLinkToClass(constructedSet, list, clazz, targetClazzMethod)) { foundLink = true; break; } } } if(!foundLink) { list.addClassTarget(clazz); } } while(true); /* * these targets are used to attempt to duplicate field type signatures. This allows * for the suplication of name-type and type constant pool entries, in addition to the UTF8 * string entries. */ do { ReferenceLinkedSetList.ClassFieldTarget target = list.getNextClassFieldTarget(); if(target == null) { break; } boolean foundLink = false; BT_Class accessorClass = target.clazz; BT_FieldVector accessorFields = accessorClass.getFields(); for(int i=0; i<accessorFields.size(); i++) { BT_Field accessorField = accessorFields.elementAt(i); if(accessorField.getFieldType().equals(target.fieldType)) { if(tryLinkToClass(constructedSet, list, accessorClass, accessorField)) { foundLink = true; break; } } } if(!foundLink) { list.addClassTarget(accessorClass); } if(list.hasClassMethodTargets()) { continue topLoop; } } while(true); /* * a class has a reference to a method in some other class, so we attempt to duplicate * names in both classes so as to double up on the UTF8 name in the constant pool of * the referring class, by adding the method to the set */ do { BT_Method method = list.getNextMethodTarget(); if(method == null) { break; } tryLinkToClass(constructedSet, list, method.getDeclaringClass(), method); if(list.hasClassFieldTargets() || list.hasClassMethodTargets()) { continue topLoop; } } while(true); /* * a class has a reference to a field in some other class, so we attempt to duplicate * names in both classes so as to double up on the UTF8 name in the constant pool of * the referring class, by adding the field to the set. */ do { BT_Field field = list.getNextFieldTarget(); if(field == null) { break; } tryLinkToClass(constructedSet, list, field.getDeclaringClass(), field); if(list.hasClassFieldTargets() || list.hasClassMethodTargets()) { continue topLoop; } } while(true); /* * a method in one class is called from another or a field in one class * is accessed by another, so we attempt to duplicate names in both classes, by * adding any member of the calling/referring class to the set. */ do { BT_Class clazz = list.getNextClassTarget(); if(clazz == null) { break; } tryLinkToClass(constructedSet, list, clazz); if(list.hasClassFieldTargets() || list.hasClassMethodTargets()) { continue topLoop; } } while(true); /* * these classes have a member in the set so we attempt to add more members from * the same class, doubling up on the UTF8 names. */ do { BT_Class clazz = list.getNextClassMemberTarget(); if(clazz == null) { break; } collectNewMembers(list, clazz, getRelatedClasses(clazz), constructedSet); } while(true); } while(!list.isEmpty()); } private ReferenceLinkedSet createReferenceLinkedSet(BT_Class clazz, BT_Field linkingField) { ReferenceLinkedSetList list = new ReferenceLinkedSetList(); list.addFieldTarget(linkingField); return createSet(list); } private ReferenceLinkedSet createReferenceLinkedSet(BT_Class clazz, BT_Method linkingMethod) { ReferenceLinkedSetList list = new ReferenceLinkedSetList(); list.addMethodTarget(linkingMethod); return createSet(list); } private ReferenceLinkedSet createSet(ReferenceLinkedSetList list) { ReferenceLinkedSet constructedSet = new ReferenceLinkedSet(); serviceList(constructedSet, list); if(constructedSet.classCount() <= 1) { //we dismantle this set, because RenameableClass has //more complex techniques for renaming members that are not accessed from //outside the declaring class Iterator iterator = constructedSet.iterator(); while(iterator.hasNext()) { Object next = iterator.next(); unrecordMember((BT_Member) next); } return null; } return constructedSet; } /** * Consider the following scenario: * class A { * int x() { * B.h(); * return B.g(); * } * } * class B { * int g() { * return 0; * } * void h() {} * } * * If A.x() is in out set, then it is also beneficial to include members of B in our set, * because the constant pool of A has method references to B.g() and B.h() and thus we can duplicate * the UTF8 name of these reference if the members of B have the same name. In addition, it * is best to first choose members of B that have the same signature, so it is best to choose * B.g for the set instead of B.h. That way the name-type of B.g and A.x can be duplicated * in the constant pool of A. * * The same holds true for fields, here is an example: * class A { * public int x; * } * class B extends A { * public short y; * } * class C { * int z; * void y() { * int g = A.x + B.y; * } * } * If C.y() is in the set, it is best to include A.x in the set as well, duplicating * both the UTF8 name and the identical name-types of A.x and C.z in the constant pool of C. * But we cannot add A.y as well because a reference to B.x (accessing A.x through B) would * look up the wrong field if we attempted to give A.x and B.y the same name. */ private void collectNewMembersFromCode(ReferenceLinkedSet constructedSet, ReferenceLinkedSetList list, BT_Class clazz) { BT_MethodVector methods = clazz.getMethods(); BT_FieldVector fields = clazz.getFields(); for (int i = 0; i < methods.size(); i++) { BT_Method method = methods.elementAt(i); BT_CodeAttribute code = method.getCode(); if (code == null) { continue; } List fieldTargetList = new ArrayList(); List methodTargetList = new ArrayList(); BT_InsVector inst = code.getInstructions(); for (int j = 0; j < inst.size(); j++) { BT_Ins instruction = inst.elementAt(j); if(instruction instanceof BT_MethodRefIns) { BT_MethodRefIns methodRefInstruction = (BT_MethodRefIns) instruction; BT_Method target = methodRefInstruction.getTarget(); BT_Class targetClass = target.getDeclaringClass(); if(!targetClass.equals(clazz) && !memberIsNotAvailable(target)) { //TODO we should have different lists instead of simply ordering the list //ie we call list.addMethodTarget(target) on favourable ones first and then //less favourable ones later //same goes for fields //TODO also, we are checking for methods -- in the class -- with the same signature first //instead of methods -- in the class and ALSO in the set -- because we have not yet added class members to the set, which we should do //check if we have a method in the current class with the same signature if(containsMethodWithSignature(methods, target.getSignature())) { list.addMethodTarget(target); } else { methodTargetList.add(target); } } } else if(instruction instanceof BT_FieldRefIns) { BT_FieldRefIns fieldRefInstruction = (BT_FieldRefIns) instruction; BT_Field target = fieldRefInstruction.getTarget(); BT_Class targetClass = target.getDeclaringClass(); if(!targetClass.equals(clazz) && !memberIsNotAvailable(target)) { //check if we have a field in the current class with the same field type if(containsFieldWithType(fields, target.getFieldType())) { list.addFieldTarget(target); } else { fieldTargetList.add(target); } } } } for(int j=0; j<methodTargetList.size(); j++) { list.addMethodTarget((BT_Method) methodTargetList.get(j)); } for(int j=0; j<fieldTargetList.size(); j++) { list.addFieldTarget((BT_Field) fieldTargetList.get(j)); } } } private static boolean containsMethodWithSignature(BT_MethodVector methods, BT_MethodSignature sig) { for(int i=0; i<methods.size(); i++) { BT_Method method = methods.elementAt(i); if(RelatedMethodMap.signaturesMatch(method.getSignature(), sig)) { return true; } } return false; } private static boolean containsFieldWithType(BT_FieldVector fields, BT_Class type) { for(int i=0; i<fields.size(); i++) { BT_Field field = fields.elementAt(i); if(field.getFieldType().equals(type)) { return true; } } return false; } /** * Consider the following scenario: * class A { * int x() {} * } * class B { * int y = A.x(); * int g() { * return A.x(); * } * void h() {} * } * * If A.x() is in our set, then it is also beneficial to include members of B in our set, * because the constant pool of B has a method reference to A.x() and thus we can duplicate * the UTF8 name of this reference if the members of B have the same name. In addition, it * is best to first choose members of B that have the same signature, so it is best to choose * B.g for the set instead of B.h. That way the name-type of B.g and A.x can be duplicated * in the constant pool of B. */ private void collectNewMembersFromCallSites(ReferenceLinkedSet constructedSet, ReferenceLinkedSetList list, BT_Class clazz) { BT_MethodVector methods = constructedSet.getNonPrivateMethodsFromClass(clazz); if(methods != null) { for (int i=0; i < methods.size(); i++) { BT_Method method = methods.elementAt(i); BT_MethodCallSiteVector callers = method.callSites; /* callers to each method must have access */ if(callers != null && callers.size() > 0) { for (int j = 0; j < callers.size(); j++) { BT_MethodCallSite callSite = callers.elementAt(j); BT_Class caller = callSite.getFrom().getDeclaringClass(); list.addClassTarget(caller, method.getSignature()); } } } } } /** * Consider the following scenario: * class A { * int x; * } * class B { * short b; * int y = A.x; * int g() { * return A.x; * } * * } * * If A.x is in out set, then it is also beneficial to include members of B in our set, * because the constant pool of B has a field reference to A.x and thus we can duplicate * the UTF8 name of this reference if the members of B have the same name. In addition, it * is best to first choose members of B that have the same field type, so it is best to choose * B.y for the set instead of B.b. That way the name-type of B.y and A.x can be duplicated * in the constant pool of B. */ private void collectNewMembersFromAccessors(ReferenceLinkedSet constructedSet, ReferenceLinkedSetList list, BT_Class clazz) { BT_Field field = constructedSet.getNonPrivateFieldFromClass(clazz); if(field != null) { BT_AccessorVector accessors = field.accessors; if(accessors != null && accessors.size() > 0) { for (int j = 0; j < accessors.size(); j++) { BT_Accessor accessor = accessors.elementAt(j); BT_Class accessorClass = accessor.getFrom().getDeclaringClass(); list.addClassTarget(accessorClass, field.getFieldType()); } } } } private void collectNewMembers(ReferenceLinkedSetList list, BT_Class clazz, BT_Class relatedClasses[], ReferenceLinkedSet constructedSet) { collectNewMembersFromCode(constructedSet, list, clazz); collectMembersFromClass(list, clazz, relatedClasses, constructedSet); if(constructedSet.containsFieldFromClass(clazz)) { collectNewMembersFromAccessors(constructedSet, list, clazz); } if(constructedSet.containsMethodFromClass(clazz)) { collectNewMembersFromCallSites(constructedSet, list, clazz); } } private void addMethod(ReferenceLinkedSet constructedSet, ReferenceLinkedSetList list, BT_Class clazz, BT_MethodVector relatedMethods) { for(int i=0; i<relatedMethods.size(); i++) { BT_Method relatedMethod = relatedMethods.elementAt(i); addMemberToConstructedSet(constructedSet, relatedMethod.getDeclaringClass(), relatedMethod); } for(int i=0; i<relatedMethods.size(); i++) { BT_Method relatedMethod = relatedMethods.elementAt(i); collectNewMembers(list, relatedMethod.getDeclaringClass(), getRelatedClasses(relatedMethod.getDeclaringClass()), constructedSet); } } private void addField(ReferenceLinkedSet constructedSet, ReferenceLinkedSetList list, BT_Class clazz, BT_Field linkingField, BT_Class relatedClasses[]) { addMemberToConstructedSet(constructedSet, clazz, linkingField); collectNewMembers(list, clazz, relatedClasses, constructedSet); } private void addMemberToConstructedSet(ReferenceLinkedSet constructedSet, BT_Class clazz, BT_Member member) { recordMemberSet(constructedSet, member); constructedSet.addMemberFromClass(clazz, member); } private void recordMemberSet(ReferenceLinkedSet constructedSet, BT_Member member) { ownedItems.add(member); linkedSetMap.put(member, constructedSet); } private void unrecordMember(BT_Member member) { linkedSetMap.remove(member); ownedItems.remove(member); } /** * find a member in clazz whose name can be duplicated */ private boolean tryLinkToClass(ReferenceLinkedSet constructedSet, ReferenceLinkedSetList list, BT_Class clazz) { BT_FieldVector accessorFields = clazz.getFields(); for(int i=0; i<accessorFields.size(); i++) { BT_Field accessorField = accessorFields.elementAt(i); if(tryLinkToClass(constructedSet, list, clazz, accessorField)) { return true; } } BT_MethodVector accessorMethods = clazz.getMethods(); for(int i=0; i<accessorMethods.size(); i++) { BT_Method accessorMethod = accessorMethods.elementAt(i); if(tryLinkToClass(constructedSet, list, clazz, accessorMethod)) { return true; } } return false; } private boolean isSuperClass(BT_Class testClass, BT_Class child) { return ((JaptClass) testClass).isClassAncestorOf(child); } // private boolean isSuperClass(BT_Class testClass, BT_Class child) { // BT_Class superClass = child; // while(true) { // superClass = superClass.getSuperClass(); // if(superClass == null) { // return false; // } // if(testClass.equals(superClass)) { // return true; // } // } // } private boolean tryLinkToClass(ReferenceLinkedSet constructedSet, ReferenceLinkedSetList list, BT_Class clazz, BT_Method linkingMethod) { if(memberIsNotAvailable(linkingMethod)) { return false; } BT_MethodVector relatedMethods = relatedMethodMap.getRelatedMethods(linkingMethod); if(methodIsAllowed(constructedSet, relatedMethods)) { addMethod(constructedSet, list, clazz, relatedMethods); return true; } return false; } private boolean fieldIsAllowed(ReferenceLinkedSet constructedSet, BT_Class clazz, BT_Class relatedClasses[]) { for(int i=0; i<relatedClasses.length; i++) { if(isSuperClass(relatedClasses[i], clazz)) { if(constructedSet.containsNonPrivateFieldFromClass(relatedClasses[i])) { return false; } } else { //is same or is child of relatedMethodClass if(constructedSet.containsFieldFromClass(relatedClasses[i])) { return false; } } } return true; } private boolean methodIsAllowed(ReferenceLinkedSet constructedSet, BT_MethodVector relatedMethods) { BT_MethodSignature sig = relatedMethods.firstElement().getSignature(); for(int k=0; k<relatedMethods.size(); k++) { BT_Method relatedMethod = relatedMethods.elementAt(k); BT_Class relatedMethodClass = relatedMethod.getDeclaringClass(); BT_Class relatedMethodClasses[] = getRelatedClasses(relatedMethod.getDeclaringClass()); for(int i=0; i<relatedMethodClasses.length; i++) { if(isSuperClass(relatedMethodClasses[i], relatedMethodClass)) { if(constructedSet.containsNonPrivateMethodFromClassWithParameters(relatedMethodClasses[i], sig)) { return false; } } else { //is same or is child of relatedMethodClass if(constructedSet.containsMethodFromClassWithParameters(relatedMethodClasses[i], sig)) { return false; } } } } return true; } private boolean tryLinkToClass(ReferenceLinkedSet constructedSet, ReferenceLinkedSetList list, BT_Class clazz, BT_Field linkingField) { if(memberIsNotAvailable(linkingField)) { return false; } BT_Class relatedClasses[] = getRelatedClasses(clazz); if(fieldIsAllowed(constructedSet, clazz, relatedClasses)) { addField(constructedSet, list, clazz, linkingField, relatedClasses); return true; } return false; } /** * Consider the following scenario: * class A { * int x; * A a; * void g() {} * void h() {} * int i(int h) {return 0;} * } * * If we have a member of A in the set, it is best to include as many other members of A * as possible, thus duplicating names in the constant pool of A. Note that we cannot * include both A.g() and A.h() because of their identical parameter lists (so we cannot * overload the same name) and we cannot include both A.x and A.a because we cannot * have two fields of the same name. An optimal solution is the following: * * class A { * int x; * A A; * void A() {} * void h() {} * int A(int h) {return 0;} * } * */ private void collectMembersFromClass(ReferenceLinkedSetList list, BT_Class clazz, BT_Class relatedClasses[], ReferenceLinkedSet constructedSet) { if(!constructedSet.containsFieldFromClass(clazz)) { //try to select a field for our collection, preferably private BT_FieldVector fields = clazz.getFields(); //try private fields BT_Field selectedField = null; for(int i=0; i<fields.size(); i++) { BT_Field field = fields.elementAt(i); if(memberIsNotAvailable(field)) { continue; } if(field.isPrivate()) { selectedField = field; break; } } //try any field if(selectedField == null) { for(int i=0; i<fields.size(); i++) { BT_Field field = fields.elementAt(i); if(memberIsNotAvailable(field)) { continue; } selectedField = field; break; } } if(selectedField != null && fieldIsAllowed(constructedSet, clazz, relatedClasses)) { addMemberToConstructedSet(constructedSet, clazz, selectedField); } } BT_MethodVector methods = clazz.getMethods(); for(int j=0; j<methods.size(); j++) { BT_Method method = methods.elementAt(j); if(memberIsNotAvailable(method)) { continue; } BT_MethodVector relatedMethods = relatedMethodMap.getRelatedMethods(method); if(methodIsAllowed(constructedSet, relatedMethods)) { for(int k=0; k<relatedMethods.size(); k++) { BT_Method relatedMethod = relatedMethods.elementAt(k); addMemberToConstructedSet(constructedSet, relatedMethod.getDeclaringClass(), relatedMethod); } for(int k=0; k<relatedMethods.size(); k++) { BT_Method relatedMethod = relatedMethods.elementAt(k); if(!method.equals(relatedMethod)) { list.addClassMemberTarget(relatedMethod.getDeclaringClass()); } } } } } private boolean memberIsNotAvailable(BT_Item item) { return nameHandler.nameIsFixed(item) //this member has a fixed name || ownedItems.contains(item); //member is already owned by some other set } private BT_Class[] getRelatedClasses(BT_Class clazz) { return repository.getRelatedClassCollector(clazz).getAllRelatedClasses(); } }
package collections; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.TreeSet; public class Sets { /* * Sets do not allow object duplicates, in a set every object appears only once * Relies on the equals() method to establish that objects are duplicates */ public static void main(String[] args) { Client c1 = new Client(1); Client c2 = new Client(2); Client c3 = new Client(3); /* * HashSet * unsorted & unordered * uses hashCode() to define where to store an object and where to fetch it */ HashSet<Client> hashSet = new HashSet<Client>(); hashSet.add(c1); hashSet.add(c2); hashSet.add(c3); System.out.println("Size of the Set: "+hashSet.size()); //hashSet.add(1, c2); // no concept of index //hashSet.get(0); // no concept of index System.out.println("attempt to add the same object again: "+hashSet.add(c1)); System.out.println("c1 is removed form the Set: "+hashSet.remove(c1)); System.out.println("c2 is removed form the Set: "+hashSet.remove(c2)); if(hashSet.contains(c3)) System.out.println("Set contains c3"); /* * LinkedHashSet * Ordered (objects are linked to one another) */ LinkedHashSet<Client> linkedHashSet = new LinkedHashSet<Client>() ; linkedHashSet.add(c2); linkedHashSet.add(c1); linkedHashSet.add(c3); System.out.println("\nSize of the Set: "+linkedHashSet.size()); System.out.println("attempt to add the same object again: "+linkedHashSet.add(c1)); // A linked set iterates faster than ones that are not linked !! Iterator<Client> it = (Iterator<Client>) linkedHashSet.iterator(); int i=0; for(Client v : linkedHashSet){ System.out.println("element "+i+" is c1 : "+v.equals(c1)); System.out.println("element "+i+" is c2 : "+v.equals(c2)); System.out.println("element "+i+" is c3 : "+v.equals(c3)); i++; } /* * TreeSet * Sorted * Requires elements to be Comparable to sort them * The developer can provide a Comparator to implement a custom order */ TreeSet<Client> treeSet = new TreeSet<Client>(); treeSet.add(c2); treeSet.add(c1); treeSet.add(c3); int k=0; for(Client v : treeSet){ System.out.println("\nelement "+i+" is c1 : "+v.equals(c1)); System.out.println("element "+i+" is c2 : "+v.equals(c2)); System.out.println("element "+i+" is c3 : "+v.equals(c3)); k++; } System.out.println("element lower than c2 in sort order is c3: "+treeSet.lower(c2).equals(c3)); System.out.println("is there an element higher than c2? "+treeSet.higher(c2)); /* * A TreeSet that uses a Comparator<Client> implementation */ // Using a Using a Comparator<Client> implementation TreeSet<Client> anotherTreeSet = new TreeSet<Client>(new ClientComparator()); anotherTreeSet.addAll(treeSet); i=0; for(Client v : anotherTreeSet){ System.out.println("\nelement "+i+" is c1 : "+v.equals(c1)); System.out.println("element "+i+" is c2 : "+v.equals(c2)); System.out.println("element "+i+" is c3 : "+v.equals(c3)); i++; } System.out.println("is there an elment lower than c2? "+anotherTreeSet.lower(c2)); System.out.println("is c3 the elment higher than c2? "+anotherTreeSet.higher(c2).equals(c3)); } }
/* * (C) Copyright 2014,2016 Hewlett Packard Enterprise Development LP * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package monasca.api; import ch.qos.logback.classic.Level; import io.dropwizard.db.DataSourceFactory; import io.dropwizard.jdbi.DBIFactory; import io.dropwizard.setup.Environment; import java.util.Arrays; import java.util.Properties; import javax.inject.Named; import javax.inject.Singleton; import kafka.javaapi.producer.Producer; import kafka.producer.ProducerConfig; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import org.skife.jdbi.v2.DBI; import com.codahale.metrics.MetricRegistry; import com.google.common.base.Joiner; import com.google.inject.AbstractModule; import com.google.inject.Provides; import com.google.inject.ProvisionException; import com.google.inject.name.Names; import monasca.api.app.ApplicationModule; import monasca.api.domain.DomainModule; import monasca.api.infrastructure.InfrastructureModule; import monasca.common.hibernate.db.AlarmActionDb; import monasca.common.hibernate.db.AlarmActionId; import monasca.common.hibernate.db.AlarmDb; import monasca.common.hibernate.db.AlarmDefinitionDb; import monasca.common.hibernate.db.AlarmMetricDb; import monasca.common.hibernate.db.AlarmMetricId; import monasca.common.hibernate.db.MetricDefinitionDb; import monasca.common.hibernate.db.MetricDefinitionDimensionsDb; import monasca.common.hibernate.db.MetricDimensionDb; import monasca.common.hibernate.db.NotificationMethodDb; import monasca.common.hibernate.db.NotificationMethodTypesDb; import monasca.common.hibernate.db.SubAlarmDb; import monasca.common.hibernate.db.SubAlarmDefinitionDb; import monasca.common.hibernate.db.SubAlarmDefinitionDimensionDb; /** * Monitoring API server bindings. */ public class MonApiModule extends AbstractModule { /** * <b>PostgresSQL</b> {@link javax.sql.DataSource} class name */ private static final String POSTGRES_DS_CLASS = "org.postgresql.ds.PGPoolingDataSource"; /** * <b>MySQL</b> {@link javax.sql.DataSource} class name */ private static final String MYSQL_DS_CLASS = "com.mysql.jdbc.jdbc2.optional.MysqlDataSource"; private final ApiConfig config; private final Environment environment; public MonApiModule(Environment environment, ApiConfig config) { this.environment = environment; this.config = config; } @Override protected void configure() { bind(ApiConfig.class).toInstance(config); bind(MetricRegistry.class).toInstance(environment.metrics()); if (!this.isHibernateEnabled()) { bind(DataSourceFactory.class).annotatedWith(Names.named("mysql")).toInstance(config.mysql); } bind(DataSourceFactory.class).annotatedWith(Names.named("vertica")).toInstance(config.vertica); install(new ApplicationModule()); install(new DomainModule()); install(new InfrastructureModule(this.config)); } @Provides @Singleton @Named("orm") public SessionFactory getSessionFactory() { if (config.hibernate == null) { throw new ProvisionException("Unable to provision ORM DBI, couldn't locate hibernate configuration"); } try { Configuration configuration = new Configuration(); configuration.addAnnotatedClass(AlarmDb.class); configuration.addAnnotatedClass(AlarmActionDb.class); configuration.addAnnotatedClass(AlarmActionId.class); configuration.addAnnotatedClass(AlarmDefinitionDb.class); configuration.addAnnotatedClass(AlarmMetricDb.class); configuration.addAnnotatedClass(AlarmMetricId.class); configuration.addAnnotatedClass(MetricDefinitionDb.class); configuration.addAnnotatedClass(MetricDefinitionDimensionsDb.class); configuration.addAnnotatedClass(MetricDimensionDb.class); configuration.addAnnotatedClass(SubAlarmDefinitionDb.class); configuration.addAnnotatedClass(SubAlarmDefinitionDimensionDb.class); configuration.addAnnotatedClass(SubAlarmDb.class); configuration.addAnnotatedClass(NotificationMethodDb.class); configuration.addAnnotatedClass(NotificationMethodTypesDb.class); configuration.setProperties(this.getORMProperties(this.config.hibernate.getDataSourceClassName())); ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); // builds a session factory from the service registry return configuration.buildSessionFactory(serviceRegistry); } catch (Throwable ex) { throw new ProvisionException("Failed to provision ORM DBI", ex); } } @Provides @Singleton @Named("mysql") public DBI getMySqlDBI() { try { return new DBIFactory().build(environment, config.mysql, "mysql"); } catch (ClassNotFoundException e) { throw new ProvisionException("Failed to provision MySQL DBI", e); } } @Provides @Singleton @Named("vertica") public DBI getVerticaDBI() { try { return new DBIFactory().build(environment, config.vertica, "vertica"); } catch (ClassNotFoundException e) { throw new ProvisionException("Failed to provision Vertica DBI", e); } } @Provides @Singleton public Producer<String, String> getProducer() { Properties props = new Properties(); props.put("metadata.broker.list", Joiner.on(',').join(config.kafka.brokerUris)); props.put("serializer.class", "kafka.serializer.StringEncoder"); props.put("request.required.acks", "1"); ProducerConfig config = new ProducerConfig(props); return new Producer<String, String>(config); } private Properties getORMProperties(final String dataSourceClassName) { final Properties properties = new Properties(); // different drivers requires different sets of properties switch (dataSourceClassName) { case POSTGRES_DS_CLASS: this.handlePostgresORMProperties(properties); break; case MYSQL_DS_CLASS: this.handleMySQLORMProperties(properties); break; default: throw new ProvisionException( String.format( "%s is not supported, valid data sources are %s", dataSourceClassName, Arrays.asList(POSTGRES_DS_CLASS, MYSQL_DS_CLASS) ) ); } // different drivers requires different sets of properties // driver agnostic properties this.handleCommonORMProperties(properties); // driver agnostic properties return properties; } private void handleCommonORMProperties(final Properties properties) { properties.put("hibernate.connection.provider_class", this.config.hibernate.getProviderClass()); properties.put("hibernate.hbm2ddl.auto", this.config.hibernate.getAutoConfig()); properties.put("show_sql", this.config.getLoggingFactory().getLevel().equals(Level.DEBUG)); properties.put("hibernate.hikari.dataSource.user", this.config.hibernate.getUser()); properties.put("hibernate.hikari.dataSource.password", this.config.hibernate.getPassword()); properties.put("hibernate.hikari.dataSourceClassName", this.config.hibernate.getDataSourceClassName()); } private void handleMySQLORMProperties(final Properties properties) { properties.put("hibernate.hikari.dataSource.url", this.config.hibernate.getDataSourceUrl()); } private void handlePostgresORMProperties(final Properties properties) { properties.put("hibernate.hikari.dataSource.serverName", this.config.hibernate.getServerName()); properties.put("hibernate.hikari.dataSource.portNumber", this.config.hibernate.getPortNumber()); properties.put("hibernate.hikari.dataSource.databaseName", this.config.hibernate.getDatabaseName()); properties.put("hibernate.hikari.dataSource.initialConnections", this.config.hibernate.getInitialConnections()); properties.put("hibernate.hikari.dataSource.maxConnections", this.config.hibernate.getMaxConnections()); properties.put("hibernate.hikari.connectionTestQuery", "SELECT 1"); properties.put("hibernate.hikari.connectionTimeout", "5000"); properties.put("hibernate.hikari.initializationFailFast", "false"); } private boolean isHibernateEnabled() { return this.config.hibernate != null && this.config.hibernate.getSupportEnabled(); } }
package com.duanxr.yith.easy; /** * @author 段然 2021/3/8 */ public class DeleteDuplicateEmails { /** * Write a SQL query to delete all duplicate email entries in a table named Person, keeping only unique emails based on its smallest Id. * * +----+------------------+ * | Id | Email | * +----+------------------+ * | 1 | john@example.com | * | 2 | bob@example.com | * | 3 | john@example.com | * +----+------------------+ * Id is the primary key column for this table. * For example, after running your query, the above Person table should have the following rows: * * +----+------------------+ * | Id | Email | * +----+------------------+ * | 1 | john@example.com | * | 2 | bob@example.com | * +----+------------------+ * Note: * * Your output is the whole Person table after executing your sql. Use delete statement. * * 编写一个 SQL 查询,来删除 Person 表中所有重复的电子邮箱,重复的邮箱里只保留 Id 最小 的那个。 * * +----+------------------+ * | Id | Email | * +----+------------------+ * | 1 | john@example.com | * | 2 | bob@example.com | * | 3 | john@example.com | * +----+------------------+ * Id 是这个表的主键。 * 例如,在运行你的查询语句之后,上面的 Person 表应返回以下几行: * * +----+------------------+ * | Id | Email | * +----+------------------+ * | 1 | john@example.com | * | 2 | bob@example.com | * +----+------------------+ *   * * 提示: * * 执行 SQL 之后,输出是整个 Person 表。 * 使用 delete 语句。 * */ private String solution = "DELETE P1 FROM Person P1,Person P2 WHERE P1.Email = P2.Email AND P1.Id > P2.Id"; }
package solution.cs3330.hw3; public class CreatureResponse { private String response; private boolean validAction; public CreatureResponse (String response, boolean validAction) { setResponse(response); setValidAction(validAction); } public boolean getValidAction() { return validAction; } public void setValidAction(boolean validAction) { this.validAction = validAction; } public String getResponse() { return response; } public void setResponse(String response) { this.response = response; } }
import java.util.Scanner; class ResultDeclaration{ public String declareResults( double subject1Marks, double subject2Marks, double subject3Marks) { double x,y,z; x=subject1Marks; y=subject2Marks; z=subject3Marks; if(x>60||y>60||z>60){ return ("failed"); } else if(x+y+z>60){ return("passed"); } else if(x+y>60 ||y+z>60||z+x>60){ return ("promoted"); } else{ return("failed"); } } } public class Assignment1Q4{ public static void main(String[] args) { Scanner sc=new Scanner(System.in); double subject1=sc.nextDouble(); double subject2=sc.nextDouble(); double subject3=sc.nextDouble(); ResultDeclaration obj=new ResultDeclaration(); System.out.println(obj.declareResults(subject1,subject2,subject3)); } }
package rontikeky.beraspakone.users; import com.google.gson.annotations.SerializedName; /** * Created by Acer on 2/12/2018. */ public class AddressReq { // Selama sama gausah make Serialiized Name public String action; public String id_user; public int id_district; public String address_name; public String first_name; public String last_name; public String address; public String phone; public String postal_code; public Double lat; @SerializedName("long") public Double longitude; public int place_id; public AddressReq(String action, String idUser, String alamatTujuan, String namaDepan, String namaBelakang, String alamat, String notelp, String nopos) { this.action = action; this.id_user = idUser; this.id_district = id_district; this.address_name = alamatTujuan; this.first_name = namaDepan; this.last_name = namaBelakang; this.address = alamat; this.phone = notelp; this.postal_code = nopos; this.lat = lat; this.longitude = longitude; this.place_id = place_id; } public String getAction() { return action; } public void setAction(String action) { this.action = action; } public String getId_user() { return id_user; } public void setId_user(String id_user) { this.id_user = id_user; } public int getId_district() { return id_district; } public void setId_district(int id_district) { this.id_district = id_district; } public String getAddress_name() { return address_name; } public void setAddress_name(String address_name) { this.address_name = address_name; } public String getFirst_name() { return first_name; } public void setFirst_name(String first_name) { this.first_name = first_name; } public String getLast_name() { return last_name; } public void setLast_name(String last_name) { this.last_name = last_name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getPostal_code() { return postal_code; } public void setPostal_code(String postal_code) { this.postal_code = postal_code; } public Double getLat() { return lat; } public void setLat(Double lat) { this.lat = lat; } public Double getLongitude() { return longitude; } public void setLongitude(Double longitude) { this.longitude = longitude; } public int getPlace_id() { return place_id; } public void setPlace_id(int place_id) { this.place_id = place_id; } public AddressReq(int id_user, int id_district, String address_name, String first_name, String last_name, String address, String phone, String postal_code, Double lat, Double longitude, int place_id) { } }
package com.fsoft.fa.interviewprocessmanagement.service; import com.fsoft.fa.interviewprocessmanagement.model.Candidate; import com.fsoft.fa.interviewprocessmanagement.repository.CandidateRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.acls.model.NotFoundException; import org.springframework.stereotype.Service; import java.util.List; @Service public class CandidateService { private CandidateRepository repository; @Autowired public void setRepository(CandidateRepository repository) { this.repository = repository; } public void deleteByRecruitmentId(int id) { repository.deleteByRecruitment_Id(id); } public List<Candidate> getPotentialCandidates() { return repository.findByPotential(true); } /*** * @see CandidateRepository#save(Object) */ public void save(Candidate candidate) { repository.save(candidate); } public Candidate getById(int id) { return repository.findById(id).orElseThrow(() -> new NotFoundException("Khong tim thay Candidate voi id " + id)); } public void deleteById(int id) { repository.deleteById(id); } /*** * @see CandidateRepository#findAll() */ public List<Candidate> getAllCandidates() { return repository.findAll(); } /*** * @see CandidateRepository#findByRecruitment_Id(int) */ public List<Candidate> getCandidatesByRecruitment(int recruitmentId) { return repository.findByRecruitment_Id(recruitmentId); } /*** * @see CandidateRepository#findByPositions_IdAndRecruitment_Id(int, int) */ public List<Candidate> getCandidatesByPositionAndRecruitment(int positionId, int recruitmentId) { return repository.findByPositions_IdAndRecruitment_Id(positionId, recruitmentId); } /*** * @see CandidateRepository#findBySkills_IdAndRecruitment_Id(int, int) */ public List<Candidate> getCandidatesBySkillAndRecruitment(int skillId, int recruitmentId) { return repository.findBySkills_IdAndRecruitment_Id(skillId, recruitmentId); } public Candidate getCandidateByName(String candidateName) { return repository.findOneByName(candidateName).orElseThrow(() -> new NotFoundException("Khong tim thay thi sinh " + candidateName)); } }
/* * 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 vasylts.blackjack.player.hand; import java.util.Collections; import java.util.List; import org.junit.Test; import static org.junit.Assert.*; import org.junit.Before; import vasylts.blackjack.deck.card.CardFactory; import vasylts.blackjack.deck.card.EnumCardSuit; import vasylts.blackjack.deck.card.EnumCardValue; import vasylts.blackjack.deck.card.ICard; /** * * @author VasylcTS */ public class PlayerHandTest { private ICard cardTwo; private ICard cardTen; private ICard cardAce; @Before public void setUp() { cardTwo = CardFactory.getCard(EnumCardSuit.CLUBS, EnumCardValue.TWO); cardTen = CardFactory.getCard(EnumCardSuit.CLUBS, EnumCardValue.TEN); cardAce = CardFactory.getCard(EnumCardSuit.CLUBS, EnumCardValue.ACE); } public PlayerHandTest() { } @Test public void testPlayerBlackjack() { PlayerHand hand = new PlayerHand(); hand.addCard(cardAce); assertFalse(hand.isBlackjack()); hand.addCard(cardTen); assertTrue(hand.isBlackjack()); } @Test public void testNullCards() { PlayerHand hand = new PlayerHand(); hand.addCard(null); hand.addCard(null); hand.addCard(null); hand.addCard(null); assertEquals(false, hand.isBlackjack()); assertEquals(0, hand.getScore()); } @Test(expected = UnsupportedOperationException.class) public void testChangingCardList() { PlayerHand hand = new PlayerHand(); hand.addCard(cardTen); hand.addCard(cardTen); hand.addCard(cardTen); assertEquals(cardTen.getCardValue().getScoreValue() * 3, hand.getScore()); // let`s cheat and make our score = 20. Should throw UnsupportedOperationException hand.getCardList().remove(cardTen); } /** * Test of addCard method, of class PlayerHand. */ @Test public void testAddCard() { PlayerHand instance = new PlayerHand(); instance.addCard(null); assertEquals(0, instance.getScore()); instance.addCard(cardAce); assertEquals(cardAce.getCardValue().getScoreValue(), instance.getScore()); } /** * Test of getCardList method, of class PlayerHand. */ @Test public void testGetCardList() { PlayerHand instance = new PlayerHand(); List expResult = Collections.EMPTY_LIST; List result = instance.getCardList(); assertEquals(expResult, result); } /** * Test of getScore method, of class PlayerHand. */ @Test public void testGetScore() { PlayerHand instance = new PlayerHand(); instance.addCard(cardTen); instance.addCard(cardAce); instance.addCard(cardAce); instance.addCard(cardTwo); int expResult = cardTen.getCardValue().getScoreValue() + cardTwo.getCardValue().getScoreValue() + 1 + 1; int result = instance.getScore(); assertEquals(expResult, result); } /** * Test of isStand method, of class PlayerHand. */ @Test public void testIsStand() { PlayerHand instance = new PlayerHand(); boolean expResult = false; boolean result = instance.isStand(); assertEquals(expResult, result); instance.setStand(); expResult = true; result = instance.isStand(); assertEquals(expResult, result); } }
package rent.api.service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import rent.api.utils.Constants; import rent.common.dtos.AccountCalculationDto; import rent.common.dtos.AccountServiceCalculationDto; import rent.common.entity.*; import rent.common.enums.CalculationType; import rent.common.enums.ParameterType; import rent.common.enums.RecalculationType; import rent.common.interfaces.IPeriod; import rent.common.repository.*; import java.math.BigDecimal; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.UUID; import java.util.concurrent.*; @Service public class CalculationService { private final Logger log = LoggerFactory.getLogger(getClass()); private final Integer appCalculationThreadsCount; private final String appLocale; private final AccountRepository accountRepository; private final WorkingPeriodRepository workingPeriodRepository; private final AccountAccrualRepository accountAccrualRepository; private final AccountRecalculationRepository accountRecalculationRepository; private final NormRepository normRepository; private final SystemPropertyService systemPropertyService; private final AccountOpeningBalanceRepository accountOpeningBalanceRepository; private final AccountPaymentRepository accountPaymentRepository; private final RecalculationTypeRepository recalculationTypeRepository; @Autowired public CalculationService(@Value("${app.calculation.threads.count}") Integer appCalculationThreadsCount, @Value("${app.locale}") String appLocale, AccountRepository accountRepository, WorkingPeriodRepository workingPeriodRepository, AccountAccrualRepository accountAccrualRepository, AccountRecalculationRepository accountRecalculationRepository, NormRepository normRepository, SystemPropertyService systemPropertyService, AccountOpeningBalanceRepository accountOpeningBalanceRepository, AccountPaymentRepository accountPaymentRepository, RecalculationTypeRepository recalculationTypeRepository) { this.appCalculationThreadsCount = appCalculationThreadsCount; this.appLocale = appLocale; this.accountRepository = accountRepository; this.workingPeriodRepository = workingPeriodRepository; this.accountAccrualRepository = accountAccrualRepository; this.accountRecalculationRepository = accountRecalculationRepository; this.normRepository = normRepository; this.systemPropertyService = systemPropertyService; this.accountOpeningBalanceRepository = accountOpeningBalanceRepository; this.accountPaymentRepository = accountPaymentRepository; this.recalculationTypeRepository = recalculationTypeRepository; if (systemPropertyService.getCalculationIsActive()) { systemPropertyService.setCalculationActive(false); } } public List<AccountCalculationDto> getAccountCalculations(String accountId, String workingPeriodId) { AccountEntity account = accountRepository.findOne(accountId); WorkingPeriodEntity workingPeriod = workingPeriodRepository.findOne(workingPeriodId); LocalDate accountDateClose = account.getDateClose(); List<AccountCalculationDto> list = new ArrayList<>(); if (accountDateClose == null || accountDateClose.compareTo(workingPeriod.getDateStart()) > 0) { List<AccountServiceEntity> accountServices = getListForPeriod(workingPeriod, account.getServices()); for (AccountServiceEntity accountService : accountServices) { AccountAccrualEntity accountAccrual = accountAccrualRepository.findByAccountServiceIdAndWorkingPeriodId(accountService.getId(), workingPeriod.getId()); if (accountAccrual != null) { Double openingBalance = accountOpeningBalanceRepository.getSumByAccountServiceIdAndWorkingPeriodId(accountService.getId(), workingPeriod.getId()); Double accrual = accountAccrual.getValue(); Double recalculation = accountRecalculationRepository.getSumByAccountServiceIdAndWorkingPeriodId(accountService.getId(), workingPeriod.getId()); Double payment = accountPaymentRepository.getSumByAccountServiceIdAndWorkingPeriodId(accountService.getId(), workingPeriod.getId()); if (openingBalance == null) openingBalance = 0D; if (recalculation == null) recalculation = 0D; if (payment == null) payment = 0D; Double closingBalance = roundHalfUp(openingBalance + accrual + recalculation - payment); AccountCalculationDto accountCalculationDto = new AccountCalculationDto(); accountCalculationDto.setAccountServiceId(accountService.getId()); accountCalculationDto.setService(accountService.getService()); accountCalculationDto.setTariff(accountAccrual.getTariff()); accountCalculationDto.setTariffCalculationType(accountAccrual.getTariffCalculationType()); accountCalculationDto.setTariffMeasurementUnit(accountAccrual.getTariffMeasurementUnit()); accountCalculationDto.setTariffValue(accountAccrual.getTariffValue()); accountCalculationDto.setConsumption(accountAccrual.getConsumption()); accountCalculationDto.setOpeningBalance(openingBalance); accountCalculationDto.setAccrual(accrual); accountCalculationDto.setRecalculation(recalculation); accountCalculationDto.setPayment(payment); accountCalculationDto.setClosingBalance(closingBalance); list.add(accountCalculationDto); } } } return list; } public WorkingPeriodEntity getCurrentWorkingPeriod() { return workingPeriodRepository.getFirstByIdIsNotNullOrderByDateStartDesc(); } private WorkingPeriodEntity createNewWorkPeriod(WorkingPeriodEntity currentWorkingPeriod) { DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("LLLL yyyy", Locale.forLanguageTag(appLocale)); WorkingPeriodEntity newWorkingPeriod = new WorkingPeriodEntity(); LocalDate dateStart = currentWorkingPeriod.getDateEnd().plusDays(1); LocalDate dateEnd = dateStart.withDayOfMonth(dateStart.lengthOfMonth()); newWorkingPeriod.setName(dateStart.format(dateTimeFormatter)); newWorkingPeriod.setDateStart(dateStart); newWorkingPeriod.setDateEnd(dateEnd); workingPeriodRepository.save(newWorkingPeriod); return newWorkingPeriod; } public void calculateAccount(String accountId, String periodStartId, String periodEndId) { log.debug("calculateAccount({}, {}, {})", accountId, periodStartId, periodEndId); AccountEntity account = accountRepository.findOne(accountId); WorkingPeriodEntity periodStart = workingPeriodRepository.findOne(periodStartId); WorkingPeriodEntity periodEnd = workingPeriodRepository.findOne(periodEndId); WorkingPeriodEntity currentWorkingPeriod = getCurrentWorkingPeriod(); LocalDate accountDateClose = account.getDateClose(); if (accountDateClose == null || accountDateClose.compareTo(currentWorkingPeriod.getDateStart()) > 0) { RecalculationTypeEntity recalculationTypeAuto = recalculationTypeRepository.findByCode(RecalculationType.AUTO.getCode()); List<WorkingPeriodEntity> workingPeriods = workingPeriodRepository.find(periodStart.getDateStart(), periodEnd.getDateStart()); for (WorkingPeriodEntity workingPeriod : workingPeriods) { String bundleId = UUID.randomUUID().toString(); LocalDateTime date = LocalDateTime.now(); List<AccountServiceEntity> accountServicesAll = account.getServices(); for (AccountServiceEntity accountService : accountServicesAll) { deleteCalculationsForPeriod(accountService.getId(), currentWorkingPeriod.getId(), workingPeriod.getId(), recalculationTypeAuto); } List<AccountServiceEntity> accountServices = getListForPeriod(workingPeriod, accountServicesAll); List<AccountServiceCalculationDto> accountCalculations = new ArrayList<>(); for (AccountServiceEntity accountService : accountServices) { TariffEntity tariff = accountService.getTariff(); if (tariff != null) { List<TariffValueEntity> tariffValues = getListForPeriod(workingPeriod, tariff.getValues()); if (tariffValues.size() > 0) { TariffValueEntity tariffValue = tariffValues.get(0); String calculationTypeCode = tariffValue.getCalculationType().getCode(); AccountServiceCalculationDto accountServiceCalculationDto = null; if (calculationTypeCode.equals(CalculationType.TOTAL_AREA.getCode())) { accountServiceCalculationDto = calculateByTotalArea(workingPeriod, account, accountService, tariffValue); } else if (calculationTypeCode.equals(CalculationType.PEOPLES.getCode())) { accountServiceCalculationDto = calculateByPeoples(workingPeriod, account, accountService, tariffValue); } else if (calculationTypeCode.equals(CalculationType.METER_READING.getCode())) { accountServiceCalculationDto = calculateByMeterReading(workingPeriod, account, accountService, tariffValue); } else if (calculationTypeCode.equals(CalculationType.METER_READING_WATER.getCode())) { accountServiceCalculationDto = calculateByMeterReadingWater(workingPeriod, account, accountService, tariffValue); } if (accountServiceCalculationDto != null) { accountServiceCalculationDto = calculateAccountServiceGivenDaysActive(workingPeriod, accountServiceCalculationDto); accountServiceCalculationDto.setTariff(tariff); accountServiceCalculationDto.setTariffCalculationType(tariffValue.getCalculationType()); accountServiceCalculationDto.setTariffMeasurementUnit(tariffValue.getMeasurementUnit()); accountServiceCalculationDto.setTariffValue(tariffValue.getValue()); if (!currentWorkingPeriod.getId().equals(workingPeriod.getId())) { accountServiceCalculationDto = calculateAccountServiceGivenPreviousRecalculation(workingPeriod, accountServiceCalculationDto, recalculationTypeAuto); } } if (accountServiceCalculationDto != null) { accountCalculations.add(accountServiceCalculationDto); } } } } saveAccountCalculations( accountCalculations, currentWorkingPeriod, workingPeriod, recalculationTypeAuto, bundleId, date ); } } } private AccountServiceCalculationDto calculateAccountServiceGivenPreviousRecalculation(WorkingPeriodEntity workingPeriod, AccountServiceCalculationDto accountServiceCalculationDto, RecalculationTypeEntity recalculationType) { String accountServiceId = accountServiceCalculationDto.getAccountService().getId(); Double sumAccruals = accountAccrualRepository.getSumByAccountServiceIdAndWorkingPeriodId(accountServiceId, workingPeriod.getId()); Double sumRecalculations = accountRecalculationRepository.getSumByAccountServiceIdAndForWorkingPeriodIdAndRecalculationTypeId(accountServiceId, workingPeriod.getId(), recalculationType.getId()); Double currentSum = roundHalfUp(accountServiceCalculationDto.getSum()); if (sumAccruals == null) sumAccruals = 0D; if (sumRecalculations == null) sumRecalculations = 0D; Double newSum = currentSum - (sumAccruals + sumRecalculations); accountServiceCalculationDto.setSum(newSum); return newSum == 0 ? null : accountServiceCalculationDto; } private AccountServiceCalculationDto calculateAccountServiceGivenDaysActive(WorkingPeriodEntity workingPeriod, AccountServiceCalculationDto accountServiceCalculationDto) { int workingPeriodDays = workingPeriod.getDateEnd().getDayOfMonth(); int accountServiceDaysActive = getAccountServiceDaysActiveForPeriod(workingPeriod, accountServiceCalculationDto.getAccountService()); accountServiceCalculationDto.setAccountServiceDaysActive(accountServiceDaysActive); if (accountServiceDaysActive < workingPeriodDays) { Double sum = accountServiceCalculationDto.getSum(); Double sumPerDay = sum / (double) workingPeriodDays; Double sumTotal = sumPerDay * (double) accountServiceDaysActive; accountServiceCalculationDto.setSum(sumTotal); } log.debug("workingPeriodDays: {}, accountServiceDaysActive: {}", workingPeriodDays, accountServiceDaysActive); return accountServiceCalculationDto; } private int getAccountServiceDaysActiveForPeriod(WorkingPeriodEntity workingPeriod, AccountServiceEntity accountService) { LocalDate periodStart = workingPeriod.getDateStart(); LocalDate periodEnd = workingPeriod.getDateEnd(); LocalDate serviceStart = accountService.getDateStart(); LocalDate serviceEnd = accountService.getDateEnd(); if (serviceStart.compareTo(periodStart) < 0) { serviceStart = periodStart; } if (serviceEnd == null) { serviceEnd = periodEnd; } else if (serviceEnd.compareTo(periodEnd) > 0) { serviceEnd = periodEnd; } return (int) ChronoUnit.DAYS.between(serviceStart, serviceEnd.plusDays(1)); } public <T> List<T> getListForPeriod(WorkingPeriodEntity workingPeriod, List<? extends IPeriod> list) { List<T> newList = new ArrayList<>(); for (IPeriod obj : list) { LocalDate dateStart = obj.getDateStart(); LocalDate dateEnd = obj.getDateEnd(); if (dateStart.compareTo(workingPeriod.getDateEnd()) <= 0 && (dateEnd == null || dateEnd.compareTo(workingPeriod.getDateStart()) >= 0)) { newList.add((T) obj); } } return newList; } private void deleteCalculationsForPeriod(String accountServiceId, String currentWorkingPeriodId, String forWorkingPeriodId, RecalculationTypeEntity recalculationType) { if (currentWorkingPeriodId.equals(forWorkingPeriodId)) { accountAccrualRepository.deleteByAccountServiceIdAndWorkingPeriodId(accountServiceId, currentWorkingPeriodId); } else { accountRecalculationRepository.deleteByAccountServiceIdAndWorkingPeriodIdAndRecalculationTypeId( accountServiceId, currentWorkingPeriodId, forWorkingPeriodId, recalculationType.getId() ); } } private AccountServiceCalculationDto calculateByTotalArea(WorkingPeriodEntity workingPeriod, AccountEntity account, AccountServiceEntity accountService, TariffValueEntity tariffValue) { AccountServiceCalculationDto accountServiceCalculationDto = new AccountServiceCalculationDto(); accountServiceCalculationDto.setAccountService(accountService); Double totalArea = getAccountTotalAreaForPeriod(account, workingPeriod); Double tariff = tariffValue.getValue(); accountServiceCalculationDto.setConsumption(totalArea); accountServiceCalculationDto.setSum(totalArea * tariff); log.debug("calculateByTotalArea() -> period: {}, service: {}, consumption: {}, tariff: {}", workingPeriod.getDateStart(), accountService.getService().getName(), totalArea, tariffValue.getValue()); return accountServiceCalculationDto; } private AccountServiceCalculationDto calculateByPeoples(WorkingPeriodEntity workingPeriod, AccountEntity account, AccountServiceEntity accountService, TariffValueEntity tariffValue) { AccountServiceCalculationDto accountServiceCalculationDto = new AccountServiceCalculationDto(); accountServiceCalculationDto.setAccountService(accountService); Double peoples = (double) getListForPeriod(workingPeriod, account.getRegistered()).size(); Double tariff = tariffValue.getValue(); accountServiceCalculationDto.setConsumption(peoples); accountServiceCalculationDto.setSum(peoples * tariff); log.debug("calculateByPeoples() -> period: {}, service: {}, consumption: {}, tariff: {}", workingPeriod.getDateStart(), accountService.getService().getName(), peoples, tariffValue.getValue()); return accountServiceCalculationDto; } private AccountServiceCalculationDto calculateByMeterReading(WorkingPeriodEntity workingPeriod, AccountEntity account, AccountServiceEntity accountService, TariffValueEntity tariffValue) { AccountServiceCalculationDto accountServiceCalculationDto = new AccountServiceCalculationDto(); accountServiceCalculationDto.setAccountService(accountService); Double consumption = 0D; Double tariff = tariffValue.getValue(); List<AccountMeterEntity> accountMeters = getListForPeriod(workingPeriod, account.getMeters()); List<AccountRegisteredEntity> accountRegistered = getListForPeriod(workingPeriod, account.getRegistered()); int accountRegisteredCount = accountRegistered.size(); boolean accountMeterIsNotExistsForService = true; Double normValue = getNormValueForPeriod(workingPeriod, accountService.getService()) * accountRegisteredCount; for (AccountMeterEntity accountMeter : accountMeters) { MeterEntity meter = accountMeter.getMeter(); ServiceEntity service = meter.getService(); if (service.getId().equals(accountService.getService().getId())) { accountMeterIsNotExistsForService = false; List<MeterValueEntity> meterValues = getMeterValuesForPeriod(meter, workingPeriod); for (MeterValueEntity meterValue : meterValues) { consumption += meterValue.getConsumption(); } if (meterValues.isEmpty() || consumption > normValue) { consumption = normValue; } } } if (accountMeterIsNotExistsForService) { consumption = normValue; } accountServiceCalculationDto.setConsumption(consumption); accountServiceCalculationDto.setSum(consumption * tariff); log.debug("calculateByMeterReading() -> period: {}, service: {}, consumption: {}, tariff: {}", workingPeriod.getDateStart(), accountService.getService().getName(), consumption, tariffValue.getValue()); return accountServiceCalculationDto; } private AccountServiceCalculationDto calculateByMeterReadingWater(WorkingPeriodEntity workingPeriod, AccountEntity account, AccountServiceEntity accountService, TariffValueEntity tariffValue) { AccountServiceCalculationDto accountServiceCalculationDto = new AccountServiceCalculationDto(); accountServiceCalculationDto.setAccountService(accountService); Double consumption = 0D; Double tariff = tariffValue.getValue(); List<ServiceEntity> servicesWater = getServicesWaterForPeriod(workingPeriod, account, tariffValue); List<String> servicesWaterIds = getServicesWaterIds(servicesWater); List<AccountMeterEntity> accountMeters = getListForPeriod(workingPeriod, account.getMeters()); List<AccountRegisteredEntity> accountRegistered = getListForPeriod(workingPeriod, account.getRegistered()); int accountRegisteredCount = accountRegistered.size(); boolean accountMeterIsNotExistsForService = true; for (AccountMeterEntity accountMeter : accountMeters) { MeterEntity meter = accountMeter.getMeter(); ServiceEntity service = meter.getService(); if (servicesWaterIds.contains(service.getId())) { accountMeterIsNotExistsForService = false; Double meterConsumption = 0D; Double normValue = getNormValueForPeriod(workingPeriod, service) * accountRegisteredCount; List<MeterValueEntity> meterValues = getMeterValuesForPeriod(meter, workingPeriod); for (MeterValueEntity meterValue : meterValues) { meterConsumption += meterValue.getConsumption(); } if (meterValues.isEmpty() || meterConsumption > normValue) { meterConsumption = normValue; } consumption += meterConsumption; } } if (accountMeterIsNotExistsForService) { for (ServiceEntity service : servicesWater) { consumption += getNormValueForPeriod(workingPeriod, service) * accountRegisteredCount; } } accountServiceCalculationDto.setConsumption(consumption); accountServiceCalculationDto.setSum(consumption * tariff); log.debug("calculateByMeterReadingWater() -> period: {}, service: {}, consumption: {}, tariff: {}", workingPeriod.getDateStart(), accountService.getService().getName(), consumption, tariffValue.getValue()); return accountServiceCalculationDto; } public Double getAccountTotalAreaForPeriod(AccountEntity account, WorkingPeriodEntity workingPeriod) { Double totalArea = account.getApartment().getTotalArea(); List<AccountParameterEntity> parameters = getListForPeriod(workingPeriod, account.getParameters()); for (AccountParameterEntity parameter : parameters) { if (parameter.getParameterType().getCode().equals(ParameterType.TOTAL_AREA.getCode())) { try { totalArea = Double.valueOf(parameter.getValue()); break; } catch (NumberFormatException e) { // do nothing } } } return totalArea; } public List<MeterValueEntity> getMeterValuesForPeriod(MeterEntity meter, WorkingPeriodEntity workingPeriod) { List<MeterValueEntity> list = new ArrayList<>(); List<MeterValueEntity> meterValues = meter.getValues(); for (MeterValueEntity meterValue : meterValues) { LocalDate dateValue = meterValue.getDateValue(); if (dateValue.compareTo(workingPeriod.getDateStart()) >= 0 && dateValue.compareTo(workingPeriod.getDateEnd()) <= 0) { list.add(meterValue); } } return list; } public List<ServiceEntity> getServicesWaterForPeriod(WorkingPeriodEntity workingPeriod, AccountEntity account, TariffValueEntity tariffValueWater) { List<ServiceEntity> list = new ArrayList<>(); List<AccountServiceEntity> accountServices = getListForPeriod(workingPeriod, account.getServices()); for (AccountServiceEntity accountService : accountServices) { TariffEntity tariff = accountService.getTariff(); List<TariffValueEntity> tariffValues = getListForPeriod(workingPeriod, tariff.getValues()); if (tariffValues.size() > 0) { TariffValueEntity serviceTariffValue = tariffValues.get(0); if (serviceTariffValue.getMeasurementUnit().getId().equals(tariffValueWater.getMeasurementUnit().getId())) { list.add(accountService.getService()); } } } return list; } private List<String> getServicesWaterIds(List<ServiceEntity> services) { List<String> list = new ArrayList<>(); for (ServiceEntity service : services) { list.add(service.getId()); } return list; } public Double getNormValueForPeriod(WorkingPeriodEntity workingPeriod, ServiceEntity service) { Double value = 0D; List<NormEntity> norms = normRepository.findByServiceId(service.getId()); for (NormEntity norm : norms) { List<NormValueEntity> normValues = getListForPeriod(workingPeriod, norm.getValues()); if (normValues.size() > 0) { NormValueEntity normValue = normValues.get(0); value = normValue.getValue(); break; } } return value; } public Double roundHalfUp(Double value) { BigDecimal bigDecimal = new BigDecimal(value); return bigDecimal.setScale(Constants.CALCULATION_ROUND_SCALE, BigDecimal.ROUND_HALF_UP).doubleValue(); } private void saveAccountCalculations(List<AccountServiceCalculationDto> accountCalculations, WorkingPeriodEntity currentWorkingPeriod, WorkingPeriodEntity forWorkingPeriod, RecalculationTypeEntity recalculationType, String bundleId, LocalDateTime date) { for (AccountServiceCalculationDto accountServiceCalculationDto : accountCalculations) { if (currentWorkingPeriod.getId().equals(forWorkingPeriod.getId())) { AccountAccrualEntity accountAccrual = new AccountAccrualEntity(); accountAccrual.setAccountService(accountServiceCalculationDto.getAccountService()); accountAccrual.setConsumption(roundHalfUp(accountServiceCalculationDto.getConsumption())); accountAccrual.setValue(roundHalfUp(accountServiceCalculationDto.getSum())); accountAccrual.setWorkingPeriod(currentWorkingPeriod); accountAccrual.setTariff(accountServiceCalculationDto.getTariff()); accountAccrual.setTariffCalculationType(accountServiceCalculationDto.getTariffCalculationType()); accountAccrual.setTariffMeasurementUnit(accountServiceCalculationDto.getTariffMeasurementUnit()); accountAccrual.setTariffValue(accountServiceCalculationDto.getTariffValue()); accountAccrual.setAccountServiceDaysActive(accountServiceCalculationDto.getAccountServiceDaysActive()); accountAccrualRepository.save(accountAccrual); } else { AccountRecalculationEntity accountRecalculation = new AccountRecalculationEntity(); accountRecalculation.setRecalculationType(recalculationType); accountRecalculation.setAccountService(accountServiceCalculationDto.getAccountService()); accountRecalculation.setConsumption(roundHalfUp(accountServiceCalculationDto.getConsumption())); accountRecalculation.setValue(roundHalfUp(accountServiceCalculationDto.getSum())); accountRecalculation.setNote("-"); accountRecalculation.setWorkingPeriod(currentWorkingPeriod); accountRecalculation.setForWorkingPeriod(forWorkingPeriod); accountRecalculation.setDate(date); accountRecalculation.setBundleId(bundleId); accountRecalculation.setTariff(accountServiceCalculationDto.getTariff()); accountRecalculation.setTariffCalculationType(accountServiceCalculationDto.getTariffCalculationType()); accountRecalculation.setTariffMeasurementUnit(accountServiceCalculationDto.getTariffMeasurementUnit()); accountRecalculation.setTariffValue(accountServiceCalculationDto.getTariffValue()); accountRecalculation.setAccountServiceDaysActive(accountServiceCalculationDto.getAccountServiceDaysActive()); accountRecalculationRepository.save(accountRecalculation); } } } public void calculateAccounts(String periodStartId, String periodEndId) { if (!systemPropertyService.getCalculationIsActive()) { List<String> accountsIds = accountRepository.getAccountsIds(); systemPropertyService.setCalculationActive(true); systemPropertyService.setCalculationAccountsCount(accountsIds.size()); systemPropertyService.setCalculationAccountsCalculated(0); ExecutorService executorService = Executors.newFixedThreadPool(appCalculationThreadsCount); List<Future<Integer>> futures = new ArrayList<>(); for (String accountId : accountsIds) { Callable<Integer> task = new CalculationThread(this, accountId, periodStartId, periodEndId); Future<Integer> future = executorService.submit(task); futures.add(future); } executorService.shutdown(); createCalculationWatcher(futures); log.info("calculateAccounts() -> periodStartId: {}, periodEndId: {}", periodStartId, periodEndId); } } public void closeWorkingPeriod() { if (!systemPropertyService.getCalculationIsActive()) { List<String> accountsIds = accountRepository.getAccountsIds(); systemPropertyService.setCalculationActive(true); systemPropertyService.setCalculationAccountsCount(accountsIds.size()); systemPropertyService.setCalculationAccountsCalculated(0); WorkingPeriodEntity currentWorkingPeriod = getCurrentWorkingPeriod(); WorkingPeriodEntity newWorkingPeriod = createNewWorkPeriod(currentWorkingPeriod); ExecutorService executorService = Executors.newFixedThreadPool(appCalculationThreadsCount); List<Future<Integer>> futures = new ArrayList<>(); for (String accountId : accountsIds) { Callable<Integer> task = new CalculationThread(this, accountId, currentWorkingPeriod, newWorkingPeriod); Future<Integer> future = executorService.submit(task); futures.add(future); } executorService.shutdown(); createCalculationWatcher(futures); log.info("closeWorkingPeriod() -> name: {}, dateStart: {}", currentWorkingPeriod.getName(), currentWorkingPeriod.getDateStart()); } } void calculateCloseWorkingPeriod(String accountId, WorkingPeriodEntity currentWorkingPeriod, WorkingPeriodEntity newWorkingPeriod) { AccountEntity account = accountRepository.findOne(accountId); LocalDate accountDateClose = account.getDateClose(); if (accountDateClose == null || accountDateClose.compareTo(newWorkingPeriod.getDateStart()) > 0) { List<AccountServiceEntity> accountServices = getListForPeriod(newWorkingPeriod, account.getServices()); for (AccountServiceEntity accountService : accountServices) { Double openingBalance = accountOpeningBalanceRepository.getSumByAccountServiceIdAndWorkingPeriodId(accountService.getId(), currentWorkingPeriod.getId()); Double accrual = accountAccrualRepository.getSumByAccountServiceIdAndWorkingPeriodId(accountService.getId(), currentWorkingPeriod.getId()); Double recalculation = accountRecalculationRepository.getSumByAccountServiceIdAndWorkingPeriodId(accountService.getId(), currentWorkingPeriod.getId()); Double payment = accountPaymentRepository.getSumByAccountServiceIdAndWorkingPeriodId(accountService.getId(), currentWorkingPeriod.getId()); if (openingBalance == null) openingBalance = 0D; if (accrual == null) accrual = 0D; if (recalculation == null) recalculation = 0D; if (payment == null) payment = 0D; Double closingBalance = roundHalfUp(openingBalance + accrual + recalculation - payment); if (closingBalance != 0) { AccountOpeningBalanceEntity accountOpeningBalance = new AccountOpeningBalanceEntity(); accountOpeningBalance.setWorkingPeriod(newWorkingPeriod); accountOpeningBalance.setAccountService(accountService); accountOpeningBalance.setValue(closingBalance); accountOpeningBalanceRepository.save(accountOpeningBalance); } } calculateAccount(accountId, newWorkingPeriod.getId(), newWorkingPeriod.getId()); } } private void createCalculationWatcher(List<Future<Integer>> futures) { ExecutorService executorServiceWatcher = Executors.newSingleThreadExecutor(); Callable<Integer> taskWatcher = () -> { try { int accountsCalculatedPrev = 0; while (true) { int accountsCalculated = 0; for (Future<Integer> future : futures) { if (future.isDone() || future.isCancelled()) { accountsCalculated++; } } if (accountsCalculated != accountsCalculatedPrev) { systemPropertyService.setCalculationAccountsCalculated(accountsCalculated); accountsCalculatedPrev = accountsCalculated; } if (accountsCalculated == futures.size()) { systemPropertyService.setCalculationActive(false); break; } } } catch (Exception e) { log.error(e.getMessage(), e); } return 0; }; executorServiceWatcher.submit(taskWatcher); executorServiceWatcher.shutdown(); } public void deleteCalculationsByAccountServiceId(String accountServiceId) { accountOpeningBalanceRepository.deleteByAccountServiceId(accountServiceId); accountAccrualRepository.deleteByAccountServiceId(accountServiceId); accountRecalculationRepository.deleteByAccountServiceId(accountServiceId); accountPaymentRepository.deleteByAccountServiceId(accountServiceId); } public void rollbackCurrentWorkingPeriod() { if (!systemPropertyService.getCalculationIsActive()) { if (workingPeriodRepository.count() > 1) { WorkingPeriodEntity currentWorkingPeriod = getCurrentWorkingPeriod(); accountOpeningBalanceRepository.deleteByWorkingPeriodId(currentWorkingPeriod.getId()); accountAccrualRepository.deleteByWorkingPeriodId(currentWorkingPeriod.getId()); accountRecalculationRepository.deleteByWorkingPeriodId(currentWorkingPeriod.getId()); accountPaymentRepository.deleteByWorkingPeriodId(currentWorkingPeriod.getId()); workingPeriodRepository.deleteById(currentWorkingPeriod.getId()); log.info("rollbackCurrentWorkingPeriod() -> name: {}, dateStart: {}", currentWorkingPeriod.getName(), currentWorkingPeriod.getDateStart()); } } } }
package kz.feekapo.model; public class User { private String id; private String firstname; private String lastname; private String uri; private String email; private int statusid; private String currenstatus; private String prevstatus; public User() {} public User(String id) { super(); this.id = id; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getFirstname() { return firstname; } public void setFirstname(String firstname) { this.firstname = firstname; } public String getLastname() { return lastname; } public void setLastname(String lastname) { this.lastname = lastname; } public String getUri() { return uri; } public void setUri(String uri) { this.uri = uri; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public int getStatusid() { return statusid; } public void setStatusid(int statusid) { this.statusid = statusid; } public String getCurrenstatus() { return currenstatus; } public void setCurrenstatus(String currenstatus) { this.currenstatus = currenstatus; } public String getPrevstatus() { return prevstatus; } public void setPrevstatus(String prevstatus) { this.prevstatus = prevstatus; } }
package com.example.root.curriculum.activity; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.TextInputLayout; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import com.example.root.curriculum.Constants; import com.example.root.curriculum.R; import com.example.root.curriculum.base.BaseActivity; import com.example.root.curriculum.base.IBasePresenter; import com.example.root.curriculum.bean.Users; import com.example.root.curriculum.util.IconFontTextView; import com.example.root.curriculum.util.ToastUtil; import butterknife.BindView; /** * 有关登陆界面的活动布局 */ public class LoginActivity extends BaseActivity<IBasePresenter> { @BindView(R.id.returnOne) IconFontTextView returnOne; @BindView(R.id.username) EditText et_userName; @BindView(R.id.password) EditText et_password; @BindView(R.id.confirm_password) EditText et_confirm; @BindView(R.id.login) Button btn_login; @BindView(R.id.register) TextView tv_register; @BindView(R.id.third) TextInputLayout layout; @BindView(R.id.login_register) Button btn_register; @BindView(R.id.title) TextView tv_title; private String userName; private String userPass; @Override protected int attachLayoutRes() { return R.layout.activity_login; } @Override protected void initViews() { clickThing(); } private void clickThing() { //注册的点击事件 tv_register.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //把几个状态值设置一下 layout.setVisibility(View.VISIBLE); btn_register.setVisibility(View.VISIBLE); btn_login.setVisibility(View.GONE); tv_register.setVisibility(View.GONE); et_confirm.setVisibility(View.VISIBLE); tv_title.setText("注册"); } }); returnOne.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //退出返回上一级 finish(); } }); btn_register.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // ToastUtil.showToast("注册部分"); userName = et_userName.getText().toString(); userPass = et_password.getText().toString(); String confirm = et_confirm.getText().toString(); if (TextUtils.isEmpty(userName) || TextUtils.isEmpty(userPass) || TextUtils.isEmpty(confirm)) { ToastUtil.showToast("输入不合法,请重新输入"); } else { if (userPass.length() < 6) { //长度不符合要求 et_password.setText(""); et_confirm.setText(""); ToastUtil.showToast("密码长度至少为6位"); } else if (userPass.equals(confirm)) { //说明密码相等 Intent intent = getIntent(); Bundle bun = new Bundle(); bun.putString("username", userName); bun.putString("password", userPass); intent.putExtras(bun); intent.putExtras(bun); ToastUtil.showToast("注册成功"); LoginActivity.this.setResult(3, intent); LoginActivity.this.finish(); } } } }); btn_login.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (TextUtils.isEmpty(userName) || TextUtils.isEmpty(userPass)) { //说明输入都不为空 userName = et_userName.getText().toString(); userPass = et_password.getText().toString(); Intent intent = getIntent(); Bundle bun = new Bundle(); bun.putString("username", userName); bun.putString("password", userPass); intent.putExtras(bun); LoginActivity.this.setResult(1, intent); LoginActivity.this.finish(); } else { //输入有为空的部分(不合法的输入) ToastUtil.showToast("用户名或密码不能为空"); } } }); } @Override protected void onRetry() { } }
import java.awt.*; import javax.swing.*; import javax.swing.border.*; class BorderDemo extends JFrame { JButton b1,b2,b3,b4,b5,b6,b7,b8; BorderDemo() { Container c=getContentPane(); c.setLayout(new FlowLayout()); b1=new JButton("Raised Bavel Border"); b2=new JButton("Lowered Bavel Border"); b3=new JButton("Raised Etched Border"); b4=new JButton("Lowered Etched Border"); b5=new JButton("Line Border"); b6=new JButton("Mette Border"); b7=new JButton("Compound Border"); b8=new JButton("Empty Border"); Border bd=BorderFactory.createBevelBorder(BevelBorder.RAISED,Color.red,Color.green); b1.setBorder(bd); bd=BorderFactory.createBevelBorder(BevelBorder.LOWERED); b2.setBorder(bd); bd=BorderFactory.createEtchedBorder(EtchedBorder.RAISED,Color.red,Color.green); b3.setBorder(bd); bd=BorderFactory.createEtchedBorder(EtchedBorder.LOWERED); b4.setBorder(bd); bd=BorderFactory.createLineBorder(Color.red,5); b5.setBorder(bd); bd=BorderFactory.createMatteBorder(5,10,15,20,Color.red); b6.setBorder(bd); bd=BorderFactory.createCompoundBorder(); b7.setBorder(bd); bd=BorderFactory.createEmptyBorder(); b8.setBorder(bd); c.add(b1); c.add(b2); c.add(b3); c.add(b4); c.add(b5); c.add(b6); c.add(b7); c.add(b8); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public static void main(String args[]) { BorderDemo obj=new BorderDemo(); obj.setTitle("Borders"); obj.setSize(500,400); obj.setVisible(true); } }
package de.jmda.core.mproc.task; import static java.lang.System.currentTimeMillis; import static java.lang.System.lineSeparator; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.annotation.processing.Processor; import javax.tools.JavaCompiler; import javax.tools.JavaFileObject; import org.apache.commons.collections.CollectionUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import de.jmda.core.MarkerAnnotationType; import de.jmda.core.util.JavaCompilerUtil; import de.jmda.core.util.TypeUtil; import de.jmda.core.util.ramcomp.JavaSourceCodeObject; /** * Provides {@link #run(AbstractTypeElementsTask...)} as utility method. * * @author ruu@jmda.de */ public abstract class TaskRunnerTypeElements { private final static Logger LOGGER = LogManager.getLogger(TaskRunnerTypeElements.class); public static String DYNA_CODE_PREFIX = "__DynaCode__"; /** * Each task in {@code tasks} defines a set of packages, a set of types a set of packageNames and a set of type names to * specify type elements that it wants to process in its {@link Task#execute()} method (see {@link AbstractTypeElementsTask}). * This method defines and runs processors so that the task's {@link Task#execute()} method will be called and the specified * type elements can be accessed via {@link AbstractTypeElementsTask#getTypeElements()}. * * @param tasks see above * @throws IOException */ public static void run(AbstractTypeElementsTask... tasks) throws IOException { run(null, tasks); } public static void run(Iterable<String> options, AbstractTypeElementsTask... tasks) throws IOException { if (options == null) options = new ArrayList<>(); if (tasks == null) return; if (tasks.length == 0) return; JavaCompiler compiler = JavaCompilerUtil.createJavaCompiler(); List<JavaFileObject> compilationUnits = new ArrayList<>(); for (AbstractTypeElementsTask task : tasks) { CollectionUtils.addAll ( compilationUnits, compiler .getStandardFileManager(null, null, null) .getJavaFileObjectsFromFiles(task.getCustomJavaSourceFileSetBuilder().build()) .iterator() ); } Iterator<? extends JavaFileObject> iterator = createSyntheticJavaFileObjectsFromTasks(compiler, tasks).iterator(); while (iterator.hasNext()) { compilationUnits.add(iterator.next()); } if (compilationUnits.isEmpty()) { LOGGER.warn("no compilation units - aborting compiler start"); return; } Iterable<? extends Processor> processors = createProcessors(tasks); JavaCompilerUtil.runProcessorsOnly(compiler, options, compilationUnits, processors); } private static Iterable<? extends Processor> createProcessors(AbstractTypeElementsTask... tasks) { List<Processor> result = new ArrayList<>(); for (AbstractTypeElementsTask task : tasks) { result.add(new TypeElementsTaskProcessor(task)); } return result; } /** * @param javaCompiler * @param tasks * @return <b>synthetic</b> java file objects as returned by {@link #createJavaFileObjects(AbstractTypeElementsTask)}, * accumulated for each element in <code>tasks</code> */ private static Iterable<? extends JavaFileObject> createSyntheticJavaFileObjectsFromTasks(JavaCompiler javaCompiler, AbstractTypeElementsTask... tasks) { List<JavaFileObject> result = new ArrayList<>(); for (AbstractTypeElementsTask task : tasks) { result.addAll(createSyntheticJavaFileObjectsFromTask(javaCompiler, task)); } return result; } /** * @param javaCompiler * @param task * @return List of <b>synthetic</b> java file objects. Each file object is annotated with {@link MarkerAnnotationType}. A file * object is created for * <ul> * <li>each {@code package} returned by {@link #getPackages(AbstractTypeElementsTask)} and</li> * <li>each {@code packageName} built by {@link #getPackageNames(AbstractTypeElementsTask)}.</li> * </ul> */ private static List<JavaFileObject> createSyntheticJavaFileObjectsFromTask(JavaCompiler javaCompiler, AbstractTypeElementsTask task) { List<JavaFileObject> result = new ArrayList<>(); long offset = currentTimeMillis(); long counter = 0; // create a synthetic java file object for each package returned by getPackages for (Package package_ : getPackages(task)) { String simpleName = DYNA_CODE_PREFIX + offset + counter; // TODO generation for package names looks better result.add ( new JavaSourceCodeObject ( package_.getName() + "." + simpleName, "package " + package_.getName() + ";" + lineSeparator() + "@" + MarkerAnnotationType.class.getName() + lineSeparator() + "class " + simpleName + " {}" ) ); counter++; } // create a synthetic java file object for each package returned by getPackageNames for (String packageName : getPackageNames(task)) { String simpleName = DYNA_CODE_PREFIX + offset + counter; String qualifiedName = packageName.isEmpty() ? simpleName : packageName + "." + simpleName; String packageStatement = packageName.isEmpty() ? "" : "package " + packageName + ";" + lineSeparator(); result.add ( new JavaSourceCodeObject ( qualifiedName, packageStatement + "@" + MarkerAnnotationType.class.getName() + lineSeparator() + "class " + simpleName + " {}" ) ); counter++; } // moved to run(...) method // CollectionUtils.addAll // ( // result, // javaCompiler // .getStandardFileManager(null, null, null) // .getJavaFileObjectsFromFiles(task.getCustomJavaSourceFileSetBuilder().build()) // .iterator() // ); if (result.isEmpty()) LOGGER.warn("no synthetic files were created"); return result; } /** * @param task * @return list of packages containing * <ul> * <li>all the packages from task ({@link AbstractTypeElementsTask#getPackagesCriterion()}) plus</li> * <li>all the packages of the types from task ({@link AbstractTypeElementsTask#getTypesCriterion()})</li> * </ul> */ private static List<Package> getPackages(AbstractTypeElementsTask task) { List<Package> result = new ArrayList<>(task.getPackagesCriterion()); for (Class<?> type : task.getTypesCriterion()) { result.add(type.getPackage()); } return result; } /** * @param task * @return list of package names containing * <ul> * <li>all the package names from task ({@link AbstractTypeElementsTask#getPackageNamesCriterion()}) plus</li> * <li>all the package names of the types from task ({@link AbstractTypeElementsTask#getTypeNamesCriterion()})</li> * </ul> */ private static List<String> getPackageNames(AbstractTypeElementsTask task) { List<String> result = new ArrayList<>(task.getPackageNamesCriterion()); for (String typeName : task.getTypeNamesCriterion()) { result.add(TypeUtil.getPackageNameFromQualifiedTypeName(typeName)); } return result; } }
package com.mayabot.nlp.segment.plugins.personname; import com.mayabot.nlp.segment.pipeline.PipelineLexerBuilder; import com.mayabot.nlp.segment.pipeline.PipelineLexerPlugin; /** * @author jimichan */ public class PersonNamePlugin implements PipelineLexerPlugin { @Override public void install(PipelineLexerBuilder builder) { builder.addWordSplitAlgorithm(PersonNameAlgorithm.class); } }
/* * 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 test; import uniud.trecevaloo.control.Minute; import uniud.trecevaloo.control.Time; import uniud.trecevaloo.control.TimeUnit; /** * Test for the Time+TimeUnit classes * @author Elia */ public class TimeTest { public static void main(String args[]) { Time t1s = new Time(1); System.out.println("One second is..."); Time t = t1s.convertTo(TimeUnit.MILLISEC); System.out.println("\t... "+t.toString()); t = t1s.convertTo(TimeUnit.MICROSEC); System.out.println("\t... "+t.toString()); t = t1s.convertTo(TimeUnit.NANOSEC); System.out.println("\t... "+t.toString()); t = t1s.convertTo(Minute.getInstance()); System.out.println("\t... "+t.toString()); Time t7mu = new Time(7, TimeUnit.MICROSEC); System.out.println(t7mu.toString()+" are..."); t = t7mu.convertTo(TimeUnit.SEC); System.out.println("\t... "+t.toString()); t = t7mu.convertTo(TimeUnit.MILLISEC); System.out.println("\t... "+t.toString()); t = t7mu.convertTo(TimeUnit.NANOSEC); System.out.println("\t... "+t.toString()); t = t7mu.convertTo(Minute.getInstance()); System.out.println("\t... "+t.toString()); } }
package model; import org.junit.jupiter.api.Test; import java.util.ArrayList; import static org.junit.jupiter.api.Assertions.assertEquals; public class AddToDataTest { @Test public void addToDataTest() { DataChoices dataChoices = new DataChoices("", "", "", ""); ArrayList<DataChoices> list = new ArrayList<>(); AddToData atd = new AddToData(list); DataChoices temp = (DataChoices) list.get(0); assertEquals("esports", temp.getInterests()); assertEquals("psychology", temp.getMajor()); assertEquals("canada", temp.getLocation()); assertEquals("University of British Columbia https://www.ubc.ca/" + "\n" + "Location: Vancouver, Canada" + "\n" + "World Ranking: 45 (2021)", temp.getUniversity()); } }
package basic; public class Exercise02 { public int calSumDigitsOfANumber(int number) { String num = "" + number; int sum = 0; for (int index = 0; index < num.length(); index++ ) { sum += (num.charAt(index) - '0'); } return sum; } }
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public boolean isPalindrome(ListNode head) { ListNode temp = head; int length=0; String x=""; ListNode reverseHead=null; ListNode slowPtr=null,fastPtr =null; if(temp==null || temp.next==null) return true; if(temp.next!=null){ slowPtr= temp.next; fastPtr=temp.next.next; } while( fastPtr!=null && fastPtr.next!=null){ slowPtr = slowPtr.next; fastPtr=fastPtr.next.next; } if(fastPtr == null){ reverseHead = reverseList(slowPtr); } else if(fastPtr.next==null){ reverseHead = reverseList(slowPtr.next); } while(reverseHead!=null&&temp!=null){ if(temp.val!=reverseHead.val) return false; reverseHead = reverseHead.next; temp=temp.next; } return true; } ListNode reverseList(ListNode head){ if(head.next == null || head==null) return head; ListNode t1=null; ListNode t2=head; while(t2!=null){ ListNode temp = t2.next; t2.next = t1; t1=t2; t2=temp; } return t1; } }
package jbyco.optimization.common; /** * An interface for optimization action loader. */ public interface ActionLoader<T extends Action> { /** * Loads inner classes that implement actions of type T. * @param libraries classes that contain actions */ void loadActions(Class<?> ...libraries); /** * Loads actions. * @param actions actions */ void loadActions(T ...actions); /** * Loads an action. * @param action action */ void loadAction(T action); }
/** * */ package com.cnk.travelogix.supplier.mappings.services; import com.cnk.travelogix.supplier.mappings.exception.SupplierMappingException; // TODO: Auto-generated Javadoc /** * The Interface SupplierMappingService. * * @author admin * @param <SUPPLIER_MAPPING_MODEL> * the generic type */ public interface SupplierMappingService<SUPPLIER_MAPPING_MODEL> { /** * Generate unique id. * * @param model * the model * @throws SupplierMappingException * the supplier mapping exception */ void generateAndAssignUniqueId(SUPPLIER_MAPPING_MODEL model) throws SupplierMappingException; /** * Checks if is exists. * * @param model * the model * @return true, if is exists */ public boolean isExists(final SUPPLIER_MAPPING_MODEL model); /** * Gets the model. * * @param model * the model * @return the model * @throws SupplierMappingException * the supplier mapping exception */ public SUPPLIER_MAPPING_MODEL getModel(final SUPPLIER_MAPPING_MODEL model) throws SupplierMappingException; }
import java.util.Random; import javax.microedition.lcdui.Graphics; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author exstac */ public class UFOEntity extends Entity { public static final double SMALL = 1, BIG = 1.5; private int moveTimer; private double size; private int shotTimer; private Random rand = null; private UFOShotEntity shot = null; private ShipEntity ship = null; public UFOEntity(int width, int height, double grid, Random rand, ShipEntity ship) { this.width = width; this.height = height; this.grid = grid; this.rand = rand; this.ship = ship; shotTimer = 1000; shot = new UFOShotEntity(width, height, grid); active = false; } public double getSize() { return size; } public void reset(double size) { this.size = size; bounds = new Entity.BoundingShape(BoundingShape.CIRCLE, 2 * size * grid); dx = (2 * rand.nextInt(2) - 1) * (width / grid) / 2500.0; dy = dx; x = (dx > 0) ? -3 * size * grid : 3 * size * grid + width; y = rand.nextInt(height); moveTimer = rand.nextInt(500) + 250; active = true; } public void shoot() { if (size == UFOEntity.BIG && !shot.isActive()) { shot.reset(x, y, rand.nextDouble() * 2 * Math.PI); } else if (size == UFOEntity.SMALL && !shot.isActive()) { double offset = Math.toRadians(30 * rand.nextDouble() - 15); shot.reset(x, y, mMath.atan2(ship.y - y, ship.x - x) + Math.PI / 2 + offset); } } public boolean shotCollision(Entity e) { return shot.collides(e); } public UFOShotEntity getShot() { return shot; } public void update(Graphics g, long deltaTime) { if (!isActive()) { return; } x += dx * deltaTime; y += dy * deltaTime; if ((shotTimer -= deltaTime) > 0) { shoot(); shotTimer = 1000; } if ((moveTimer -= deltaTime) < 0) { dy = -dy; moveTimer = rand.nextInt(2000) + 500; } if ((dx > 0 && x - 3 * size * grid > width) || (dx < 0 && x + 3 * size * grid < 0)) { if (rand.nextDouble() > 0.5) { reset(size); } else { setInactive(); } } if (y - 3 * size * grid > height) { y = -size * grid; } else if (y + 2 * size * grid < 0) { y = 2 * size * grid + height; } g.setColor(0xFFFFFF); g.drawLine((int) (x - 2 * size * grid), (int) y, (int) (x + 2 * size * grid), (int) y); g.drawLine((int) (x - 2 * size * grid), (int) y, (int) (x - size * grid), (int) (y + size * grid)); g.drawLine((int) (x - 2 * size * grid), (int) y, (int) (x - size * grid), (int) (y - size * grid)); g.drawLine((int) (x + 2 * size * grid), (int) y, (int) (x + size * grid), (int) (y - size * grid)); g.drawLine((int) (x + 2 * size * grid), (int) y, (int) (x + size * grid), (int) (y + size * grid)); g.drawLine((int) (x + size * grid), (int) (y + size * grid), (int) (x - size * grid), (int) (y + size * grid)); g.drawLine((int) (x + size * grid), (int) (y - size * grid), (int) (x - size * grid), (int) (y - size * grid)); g.drawArc((int) (x - size * grid), (int) (y - 2 * size * grid), (int) (2 * size * grid), (int) (2 * size * grid), 0, 180); shot.update(g, deltaTime); } }
package edu.floridapoly.polycamsportal.schedule; import java.util.List; import java.util.Objects; public class Course { private String title; private String department; // This is a String because some courses numbers have X and C in them private String number; private String type; private int credits; private List<CourseSection> sections; @SuppressWarnings("unused") public Course() { this("", "", "", "", 0, null); } public Course(String title, String department, String number, String type, int credits, List<CourseSection> sections) { this.title = title; this.department = department; this.number = number; this.type = type; this.credits = credits; this.setSections(sections); } public String getTitle() { return title; } public String getDepartment() { return department; } public String getNumber() { return number; } public String getType() { return type; } public int getCredits() { return credits; } public List<CourseSection> getSections() { return sections; } /** * Sets the list of sections for this course. * <p> * Each section is given a reference to this course so that it can access * its metadata. Because of this, the list of sections must not be * "owned" by another Course object, as an exception will be thrown * otherwise. * <p> * Note: This is private, but is called by Jackson upon deserialization. * * @param sections List of sections to set. */ @SuppressWarnings("unused") private void setSections(List<CourseSection> sections) { if (sections != null) { for (CourseSection section : sections) { section.setCourse(this); } } this.sections = sections; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Course course = (Course) o; return credits == course.credits && Objects.equals(title, course.title) && Objects.equals(department, course.department) && Objects.equals(number, course.number) && Objects.equals(type, course.type) && Objects.equals(sections, course.sections); } @Override public int hashCode() { return Objects.hash(title, department, number, type, credits, sections); } @Override public String toString() { return "Course{" + "title='" + title + '\'' + ", department='" + department + '\'' + ", number='" + number + '\'' + ", type='" + type + '\'' + ", credits=" + credits + ", sections=" + sections + '}'; } }
public class TestOpe04 { public static void main(String[] args) { int a = 5; a++;//相当于 a=a+1; System.out.println(a); a = 5; ++a; System.out.println(a); //++单独使用的时候,无论放在前还是后,都是加一操作 //将++参与到运算中: a = 5; int m = a++ + 7; System.out.println(m); System.out.println(a); a = 5; int n = ++a +7; System.out.println(n); System.out.println(a); } }
package com.algaworks.ecommerce.model; import lombok.Data; import lombok.EqualsAndHashCode; import javax.persistence.*; import java.util.Date; @Data @EqualsAndHashCode(onlyExplicitlyIncluded = true) @Entity @Table(name = "nota_fiscal") public class NotaFiscal { @EqualsAndHashCode.Include @Id @Column(name = "pedido_id") private Integer id; @MapsId @OneToOne(optional = false) @JoinColumn(name = "pedido_id", nullable = false, foreignKey = @ForeignKey(name = "fk_nota_fiscal_pedido")) private Pedido pedido; @Lob @Column(nullable = false) private byte[] xml; @Temporal(TemporalType.TIMESTAMP) @Column(name = "data_emissao", nullable = false) private Date dataEmissao; }
public class IteratorTest { public static void main(String[] args){ PersonRepository p = new PersonRepository(); for(Iterator i = p.getIterator(); i.hasNext();){ String name = (String)i.next(); System.out.println(name); } } }
package com.rc.portal.webapp.action; import java.io.PrintWriter; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.UUID; import java.util.regex.Pattern; import com.rc.app.framework.webapp.action.BaseAction; import com.rc.commons.mail.Mail; import com.rc.dst.client.util.ClientSubmit; import com.rc.portal.memcache.MemCached; import com.rc.portal.service.OpenSqlManage; import com.rc.portal.service.TMemberManager; import com.rc.portal.service.TSysParameterManager; import com.rc.portal.util.CodeUtil; import com.rc.portal.util.CustomDigestUtils; import com.rc.portal.util.NetworkUtil; import com.rc.portal.vo.TMember; import com.rc.portal.vo.TMemberExample; import com.rc.portal.webapp.util.MD5; public class FindPasswordAction extends BaseAction { private static final long serialVersionUID = 1654656456546L; private TMemberManager tmembermanager; private TMember tmember; private OpenSqlManage opensqlmanage; private TSysParameterManager tsysparametermanager; private Mail mailSender; public Mail getMailSender() { return mailSender; } public void setMailSender(Mail mailSender) { this.mailSender = mailSender; } public TSysParameterManager getTsysparametermanager() { return tsysparametermanager; } public void setTsysparametermanager(TSysParameterManager tsysparametermanager) { this.tsysparametermanager = tsysparametermanager; } public OpenSqlManage getOpensqlmanage() { return opensqlmanage; } public void setOpensqlmanage(OpenSqlManage opensqlmanage) { this.opensqlmanage = opensqlmanage; } public TMemberManager getTmembermanager() { return tmembermanager; } public void setTmembermanager(TMemberManager tmembermanager) { this.tmembermanager = tmembermanager; } public TMember getTmember() { return tmember; } public void setTmember(TMember tmember) { this.tmember = tmember; } /* * 发送验证码 */ public void validateMobileCode() throws Exception { Map<String, Object> map = new HashMap<String, Object>(); Map<String, Object> mobileMap = new HashMap<String, Object>(); String captcha = CodeUtil.getVcode(4); String username = this.getRequest().getParameter("username"); String rand = (String) this.getSession().getAttribute("rand"); String inputCode = this.getRequest().getParameter("inputCode"); MemCached.getmcc().set("pc_"+username,captcha,new Date(1000*300)); map.put("user_name", username); mobileMap.put("mobile", username); //this.getSession().setAttribute(username, captcha); Pattern pattern = Pattern.compile("^[1][3,4,7,5,8][0-9]{9}$"); // 验证手机号 int flag = -1; PrintWriter out = this.getResponse().getWriter(); //TMember member = (TMember) opensqlmanage.selectObjectByObject(map,"t_member.ibatorgenerated_selectByUserName"); TMember mobileMember = (TMember) this.opensqlmanage.selectObjectByObject(mobileMap, "t_member.ibatorgenerated_selectMemberByMobile"); // if (member != null) { // if (!inputCode.equalsIgnoreCase(rand)) { // flag = 1;// 输入的验证码不正确 // } else if (member.getIsMobileCheck() != 1) { // flag = 2;// 该用户未绑定手机号 // } else if (!pattern.matcher(member.getMobile()).matches()) { // flag = 3;// 手机格式不正确 // }else{ // Map<String, String> smsMap = new HashMap<String, String>(); // smsMap.put("mobiles", member.getMobile()); // smsMap.put("smsContent", "您的手机验证码是:"+captcha+"。要健康 要美丽 要时尚@111医药馆!"); // String YAO_GATEWAY_URL = tsysparametermanager.getKeys("sms"); // String buildRequestBySMS = ClientSubmit.buildRequestBySMS(smsMap,YAO_GATEWAY_URL); // System.out.println(buildRequestBySMS); // this.getSession().setAttribute("smsSuccess", "smsSuccess"); // flag=0; // } // }else if(username != null && pattern.matcher(username).matches() && mobileMember!=null && mobileMember.getStatus() == 0){ if (!inputCode.equalsIgnoreCase(rand)) { flag = 1;// 输入的验证码不正确 } else if (mobileMember.getIsMobileCheck() != 1) { flag = 2;// 该用户未绑定手机号 } else if (!pattern.matcher(mobileMember.getMobile()).matches()) { flag = 3;// 手机格式不正确 }else{ Map<String, String> smsMap = new HashMap<String, String>(); smsMap.put("mobiles", mobileMember.getMobile()); smsMap.put("smsContent", "您的手机验证码是:"+captcha+"。要健康 要美丽 要时尚@111医药馆!"); String YAO_GATEWAY_URL = tsysparametermanager.getKeys("sms"); String buildRequestBySMS = ClientSubmit.buildRequestBySMS(smsMap,YAO_GATEWAY_URL); System.out.println(buildRequestBySMS); this.getSession().setAttribute("smsSuccess", "smsSuccess"); flag=0; } } else { flag = 4; } out.print(flag); out.close(); } /* * 跳转到输入短信验证码页面 */ public String nextStep() { String username = this.getRequest().getParameter("username"); Map<String, Object> map = new HashMap<String, Object>(); Map<String, Object> mobileMap = new HashMap<String, Object>(); mobileMap.put("mobile", username); map.put("user_name", username); //TMember member = (TMember) opensqlmanage.selectObjectByObject(map,"t_member.ibatorgenerated_selectByUserName"); TMember mobileMember = (TMember) this.opensqlmanage.selectObjectByObject(mobileMap, "t_member.ibatorgenerated_selectMemberByMobile"); try { if(mobileMember!=null){ tmember = mobileMember; } // else{ // tmember = mobileMember; // } } catch (Exception e) { e.printStackTrace(); } return "nextstep2"; } /* * 校验验证码 */ public void getCode() throws Exception { int flag = -1; PrintWriter out = this.getResponse().getWriter(); String inputCode = this.getRequest().getParameter("inputCode"); String username = this.getRequest().getParameter("username"); String phoneCode =(String) MemCached.getmcc().get("pc_"+username); if (!inputCode.equalsIgnoreCase(phoneCode)) {//phoneCode flag = 1;// 短信验证码不对 } out.print(flag); out.close(); } /* * 重置密码 */ public void resetPassword() throws Exception { int flag = -1; PrintWriter out = this.getResponse().getWriter(); String password = this.getRequest().getParameter("password"); String username = this.getRequest().getParameter("username"); Map<String, Object> map = new HashMap<String, Object>(); Map<String, Object> mobileMap = new HashMap<String, Object>(); map.put("user_name", username); mobileMap.put("mobile", username); //TMember member = (TMember) opensqlmanage.selectObjectByObject(map,"t_member.ibatorgenerated_selectByUserName"); TMember mobileMember = (TMember) this.opensqlmanage.selectObjectByObject(mobileMap, "t_member.ibatorgenerated_selectMemberByMobile"); try { // if(member!=null){ // tmember = member; // tmember.setPassword(CustomDigestUtils.md5Hex(password, tmember)); // tmember.setLastDate(new Date()); // tmember.setLastIp(NetworkUtil.getIpAddress(this.getRequest())); // tmembermanager.updateByPrimaryKeySelective(tmember); // flag = 0; // }else{ tmember = mobileMember; tmember.setPassword(CustomDigestUtils.md5Hex(password, tmember)); tmember.setLastDate(new Date()); tmember.setLastIp(NetworkUtil.getIpAddress(this.getRequest())); tmembermanager.updateByPrimaryKeySelective(tmember); flag = 0; // } } catch (Exception e) { e.printStackTrace(); } out.print(flag); out.close(); } /* * 跳转到成功页 */ public String success() { return "success"; } /* * 跳转到重置密码页 */ public String nextStep2() { String username = this.getRequest().getParameter("username"); Map<String, Object> mobileMap = new HashMap<String, Object>(); Map<String, Object> map = new HashMap<String, Object>(); map.put("user_name", username); mobileMap.put("mobile", username); //TMember member = (TMember) opensqlmanage.selectObjectByObject(map,"t_member.ibatorgenerated_selectByUserName"); TMember mobileMember = (TMember) this.opensqlmanage.selectObjectByObject(mobileMap, "t_member.ibatorgenerated_selectMemberByMobile"); try { // if(member!=null){ // tmember = member; // }else{ tmember = mobileMember; // } } catch (Exception e) { e.printStackTrace(); } return "nextstep3"; } /* * 重新获取验证码 */ public void againGetMobileCode() throws Exception { Map<String, Object> map = new HashMap<String, Object>(); Map<String, Object> mobileMap = new HashMap<String, Object>(); String captcha = CodeUtil.getVcode(4); String username = this.getRequest().getParameter("username"); MemCached.getmcc().set("pc_"+username,captcha,new Date(1000*300)); map.put("user_name", username); mobileMap.put("mobile", username); Pattern pattern = Pattern.compile("^[1][3,4,7,5,8][0-9]{9}$"); // 验证手机号 int flag = -1; PrintWriter out = this.getResponse().getWriter(); // TMember member = (TMember) opensqlmanage.selectObjectByObject(map, // "t_member.ibatorgenerated_selectByUserName"); TMember mobileMember = (TMember) this.opensqlmanage.selectObjectByObject(mobileMap, "t_member.ibatorgenerated_selectMemberByMobile"); // if (member != null) { // if (member.getIsMobileCheck() != 1) { // flag = 2;// 该用户未绑定手机号 // } else if (!pattern.matcher(member.getMobile()).matches()) { // flag = 3;// 手机格式不正确 // }else{ // Map<String, String> smsMap = new HashMap<String, String>(); // smsMap.put("mobiles", member.getMobile()); // smsMap.put("smsContent", "您的手机验证码是:"+captcha+"。要健康 要美丽 要时尚@111医药馆!"); // //String YAO_GATEWAY_URL = tsysparametermanager.getKeys("sms"); // //String buildRequestBySMS = ClientSubmit.buildRequestBySMS(smsMap,YAO_GATEWAY_URL); // //System.out.println(buildRequestBySMS); // flag=0; // } // }else if(username != null && pattern.matcher(username).matches() && mobileMember!=null && mobileMember.getStatus() == 0){ if (mobileMember.getIsMobileCheck() != 1) { flag = 2;// 该用户未绑定手机号 } else if (!pattern.matcher(mobileMember.getMobile()).matches()) { flag = 3;// 手机格式不正确 }else{ Map<String, String> smsMap = new HashMap<String, String>(); smsMap.put("mobiles", mobileMember.getMobile()); smsMap.put("smsContent", "您的手机验证码是:"+captcha+"。要健康 要美丽 要时尚@111医药馆!"); String YAO_GATEWAY_URL = tsysparametermanager.getKeys("sms"); String buildRequestBySMS = ClientSubmit.buildRequestBySMS(smsMap,YAO_GATEWAY_URL); System.out.println(buildRequestBySMS); flag=0; } } else { flag = 4; } out.print(flag); out.close(); } /*-----------------密码找回新规则------------------*/ /* * 邮件点击返回到密码重置页 */ public String setEamilPassword() throws Exception{ String username = this.getRequest().getParameter("username"); Map<String, Object> usermap = new HashMap<String, Object>(); usermap.put("user_name", username); String key = this.getRequest().getParameter("key"); tmember = (TMember) opensqlmanage.selectObjectByObject(usermap,"t_member.ibatorgenerated_selectByUserName"); String safekey = (String) MemCached.getmcc().get(tmember.getEmail()); if(key==null || "".equals(key) || !key.equals(safekey)){ return "errorPage"; }else{ return "nextstep3"; } } /* * 发送邮件 */ public void sendEmail() throws Exception{ String email = this.getRequest().getParameter("email"); String randomUUID = UUID.randomUUID().toString(); int flag=-1; PrintWriter out = this.getResponse().getWriter(); MemCached.getmcc().set(email, randomUUID, new Date(2*60*60*1000)); Map<String, Object> emailMap = new HashMap<String, Object>(); emailMap.put("email", email); tmember = (TMember) this.opensqlmanage.selectObjectByObject(emailMap, "t_member.ibatorgenerated_selectMemberByEmail"); if(tmember!=null){ Map<Object,Object> contentMap = new HashMap<Object,Object>(); contentMap.put("username", tmember.getUserName()); contentMap.put("randomUUID", randomUUID); contentMap.put("currentDate", new Date()); if(mailSender.send(email, "111医药馆-验证邮箱", contentMap, "findpasswordmail.ftl")){ flag=0; }else{ flag=1; } } out.print(flag); out.close(); } /* * 重置密码 */ public void reSetPassword() throws Exception{ String mobile = (String) this.getRequest().getParameter("mobile"); String email = (String) this.getRequest().getParameter("email"); String password = this.getRequest().getParameter("password"); int flag=-1; PrintWriter out = this.getResponse().getWriter(); Map<String, Object> emailMap = new HashMap<String, Object>(); emailMap.put("email", email); if(!"".equals(mobile)&&mobile!=null){ Map<String, Object> mobileMap = new HashMap<String, Object>(); mobileMap.put("mobile", mobile); tmember = (TMember) this.opensqlmanage.selectObjectByObject(mobileMap, "t_member.ibatorgenerated_selectMemberByMobile"); } if(tmember!=null){ tmember.setPassword(MD5.MD5("111"+password+"yao")); tmember.setLastDate(new Date()); tmember.setLastIp(NetworkUtil.getIpAddress(this.getRequest())); tmembermanager.updateByPrimaryKeySelective(tmember); flag=0; }else{ tmember = (TMember) this.opensqlmanage.selectObjectByObject(emailMap, "t_member.ibatorgenerated_selectMemberByEmail"); tmember.setPassword(MD5.MD5("111"+password+"yao")); tmember.setLastDate(new Date()); tmember.setLastIp(NetworkUtil.getIpAddress(this.getRequest())); tmembermanager.updateByPrimaryKeySelective(tmember); flag=0; } out.print(flag); out.close(); } /* * 转到设置密码页 */ public String setPassword() throws Exception{ String mobile = this.getRequest().getParameter("mobile"); Map<String, Object> mobileMap = new HashMap<String, Object>(); mobileMap.put("mobile", mobile); tmember = (TMember) this.opensqlmanage.selectObjectByObject(mobileMap, "t_member.ibatorgenerated_selectMemberByMobile"); return "nextstep3"; } /* * 检查手机验证码是否正确 */ public void checkMobileCode() throws Exception{ String mobile = (String) this.getRequest().getParameter("mobile"); String mobilecode = (String) this.getRequest().getParameter("mobilecode"); String amoblieCode = (String) MemCached.getmcc().get(mobile); int flag=-1; PrintWriter out = this.getResponse().getWriter(); if(mobilecode !=null && amoblieCode !=null && mobilecode.equals(amoblieCode)){ flag=0; } out.print(flag); out.close(); } /* * 发送验证码 */ public void getMobileCode() throws Exception{ String captcha = CodeUtil .getVcode(4); String mobile = this.getRequest().getParameter("mobile"); MemCached.getmcc().set(mobile,captcha,new Date(1000*300)); Pattern pattern = Pattern.compile("^[1][3,4,7,5,8][0-9]{9}$"); // 验证手机号 int flag=-1; PrintWriter out = this.getResponse().getWriter(); if(mobile!=null && pattern.matcher(mobile).matches()){ Map<String, String> map = new HashMap<String, String>(); map.put("mobiles", mobile); map.put("smsContent", "您的111医药馆验证码:"+captcha+"。影视明星何政军先生推荐的中国好药房@111医药馆!"); String YAO_GATEWAY_URL =tsysparametermanager.getKeys("sms"); String buildRequestBySMS = ClientSubmit.buildRequestBySMS(map,YAO_GATEWAY_URL); System.out.println(buildRequestBySMS); flag=0; } out.print(flag); out.close(); } /* * 手机验证身份页面 */ public String mobileValidate() throws Exception{ String mobile = this.getRequest().getParameter("mobile"); if(mobile!=null && !"".equals(mobile)){ this.getRequest().setAttribute("mobile",mobile); } return "nextstep2"; } /* * 选择找回方式 */ public String chooseFindMethod() throws Exception{ Map<String, Object> usermap = new HashMap<String, Object>(); Map<String, Object> mobileMap = new HashMap<String, Object>(); Map<String, Object> emailMap = new HashMap<String, Object>(); String username = this.getRequest().getParameter("username"); usermap.put("user_name", username); mobileMap.put("mobile", username); emailMap.put("email", username); TMember usermember = (TMember) opensqlmanage.selectObjectByObject(usermap,"t_member.ibatorgenerated_selectByUserName"); TMember mobileMember = (TMember) this.opensqlmanage.selectObjectByObject(mobileMap, "t_member.ibatorgenerated_selectMemberByMobile"); TMember emailMember = (TMember) this.opensqlmanage.selectObjectByObject(emailMap, "t_member.ibatorgenerated_selectMemberByEmail"); if(usermember==null && mobileMember!=null){ tmember=mobileMember; }else if(mobileMember==null && emailMember!=null){ tmember=emailMember; }else{ tmember=usermember; } return "nextstep1"; } /* * 检查用户是否存在 */ public void checkUserIsExist() throws Exception{ int flag=1; PrintWriter out = this.getResponse().getWriter(); String username = this.getRequest().getParameter("username"); TMemberExample e1 = new TMemberExample(); e1.createCriteria().andUserNameEqualTo(username); TMemberExample e2 = new TMemberExample(); e2.createCriteria().andMobileEqualTo(username); TMemberExample e3 = new TMemberExample(); e3.createCriteria().andEmailEqualTo(username); int uname = this.tmembermanager.countByExample(e1); int mobile = this.tmembermanager.countByExample(e2); int email = this.tmembermanager.countByExample(e3); if(uname > 0 || mobile > 0 || email > 0){ flag=0;//说明用户存在 } out.print(flag); out.close(); } /* * 检查验证码是否正确 */ public void checkCodeIsExist() throws Exception{ int flag=-1; String code = this.getRequest().getParameter("code"); PrintWriter out = this.getResponse().getWriter(); String rand = (String) this.getSession().getAttribute("rand"); if(!code.equals(rand)){ flag=0;//验证码不正确 } out.print(flag); out.close(); } /* * 转到找回密码页面 */ public String index() { return "findpassword"; } @Override public Object getModel() { // TODO Auto-generated method stub return null; } @Override public void setModel(Object o) { // TODO Auto-generated method stub } }
package com.yixin.dsc.v1.service.capital.icbc; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.google.common.collect.Maps; import com.yixin.dsc.common.exception.BzException; import com.yixin.dsc.dto.DscCapitalDto; import com.yixin.dsc.entity.order.DscSalesApplyFinancing; import com.yixin.dsc.enumpackage.BankCostRateEnum; import com.yixin.dsc.util.PropertiesManager; import com.yixin.dsc.v1.service.capital.AfterShuntDeal; import com.yixin.kepler.common.RestTemplateUtil; import com.yixin.kepler.common.UrlConstant; import com.yixin.kepler.core.constant.CommonConstant; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import javax.annotation.Resource; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.HashMap; import java.util.Map; /** * 工行预审处理实现类 * @author YixinCapital -- xjt * 2018年9月28日 下午2:53:40 */ @Component("iCBCAfterShuntDeal") public class ICBCAfterShuntDeal extends AfterShuntDeal { private static final Logger LOGGER = LoggerFactory.getLogger(ICBCAfterShuntDeal.class); @Resource private PropertiesManager propertiesManager; @Override public DscCapitalDto deal(DscCapitalDto dscCapitalDto) { LOGGER.info("ICBC准入后处理开始:{}-{}", threadLocalApplyMain.get().getApplyNo(), dscCapitalDto.getCapitalCode()); try{ // 判断是否贴息,如果不贴息,则不校验贴息规则,预审通过 if (!StringUtils.hasText(threadLocalApplyCost.get().getAtxfs())){ return convertResult(dscCapitalDto, false, "缺失必须字段:贴息标识"); } else { if (threadLocalApplyCost.get().getAtxfs().equals(CommonConstant.DiscountType.DISCOUNT_NO)){ return convertResult(dscCapitalDto, true, "预审通过"); } } // 校验计算银行贴息所需属性是否齐全(期数、客户融资金额、担保费率、是否有担保费、结算利率) if (!StringUtils.hasText(threadLocalApplyMain.get().getArzqx())) { return convertResult(dscCapitalDto, false, "缺失必须字段:期数"); } if (null == threadLocalApplyCost.get().getFrze() || BigDecimal.ZERO.equals(threadLocalApplyCost.get().getFrze())) { return convertResult(dscCapitalDto, false, "缺失必须字段:客户融资额"); } if (null == threadLocalApplyCost.get().getFjsll() || BigDecimal.ZERO.equals(threadLocalApplyCost.get().getFjsll())) { return convertResult(dscCapitalDto, false, "缺失必须字段:结算利率"); } if (null == threadLocalApplyCost.get().getFcstxze() || BigDecimal.ZERO.equals(threadLocalApplyCost.get().getFcstxze())) { return convertResult(dscCapitalDto, false, "缺失必须字段:厂家贴息金额"); } if (null == threadLocalApplyCost.get().getFdlstxze() || BigDecimal.ZERO.equals(threadLocalApplyCost.get().getFdlstxze())) { return convertResult(dscCapitalDto, false, "缺失必须字段:经销商贴息金额"); } // 获取配置的银行成本费率 BankCostRateEnum bankCostRateEnum = BankCostRateEnum.getByParams(CommonConstant.BankName.ICBC_BANK, threadLocalApplyCar.get().getAcllx(), threadLocalApplyMain.get().getArzqx()); LOGGER.info("获取到银行成本费率:{}", bankCostRateEnum); if (null == bankCostRateEnum || !StringUtils.hasText(bankCostRateEnum.getBankCostRate())) { return convertResult(dscCapitalDto, false, "无法获取银行成本费率"); } // 校验是否存在费率 if ((null != threadLocalApplyCost.get().getFkhfl() && threadLocalApplyCost.get().getFkhfl().compareTo(BigDecimal.ZERO)>0) && (null != threadLocalApplyCost.get().getFjsfl() && threadLocalApplyCost.get().getFjsfl().compareTo(BigDecimal.ZERO)>0)) { LOGGER.info("存在费率字段,内部计算贴息"); // 计算补息金额:贴息金额、客户费率、银行资金成本费率、客户融资额 calculateInterestRate(threadLocalApplyCost.get().getFcstxze().add(threadLocalApplyCost.get().getFdlstxze()), threadLocalApplyCost.get().getFkhfl(), new BigDecimal(bankCostRateEnum.getBankCostRate()), threadLocalApplyCost.get().getFrze()); // 1. 帖0息,可准入。(贴息金额 = 银行成本费+易鑫服务费) // 2. 没有帖到银行的成本费,可准入。 (贴息金额<=易鑫服务费) // 计算返回不抛异常即为可以准入 return convertResult(dscCapitalDto, true, "预审通过"); } else { if (BigDecimal.ZERO.compareTo(threadLocalApplyCost.get().getFkhll()) == 0){ LOGGER.info("客户利率为0,贴0息准入"); return convertResult(dscCapitalDto, true, "预审通过"); } // 调用结算接口进行费用计算 String url = propertiesManager.getSettleWebEnvironment() + UrlConstant.SettleSystemUrl.calculationICBCInterestAmt; Map<String, Object> params = Maps.newHashMap(); // 期数 params.put("totalPeriod", threadLocalApplyMain.get().getArzqx()); // 客户融资额 params.put("custFinaceAmount", threadLocalApplyCost.get().getFrze()); // 银行成本费率 params.put("bankCostRate", new BigDecimal(bankCostRateEnum.getBankCostRate()).divide(new BigDecimal(100), 4, BigDecimal.ROUND_HALF_UP)); // 结算利率 params.put("settleInterestRate", threadLocalApplyCost.get().getFjsll().divide(new BigDecimal(100), 4, BigDecimal.ROUND_HALF_UP)); // 易鑫担保费(此处从融资项中获取) Map<String, Object> financingParams = new HashMap<>(); financingParams.put("mainId", threadLocalApplyMain.get().getId()); financingParams.put("arzxmid", CommonConstant.FinanceType.F117); DscSalesApplyFinancing financing = DscSalesApplyFinancing.findFirstByProperties(DscSalesApplyFinancing.class, financingParams); if (null != financing && financing.getFkhrzje().compareTo(BigDecimal.ZERO) > 0){ // if (null != threadLocalApplyCost.get().getFyxdbf() && threadLocalApplyCost.get().getFyxdbf().compareTo(BigDecimal.ZERO) > 0){ LOGGER.info("存在担保费,送入担保费率[{}]", threadLocalApplyCost.get().getFyxdbfl()); // 是否有担保费 params.put("isHavingGuarantee", "1"); // 此处需要的是费率,从cost表获取 params.put("guaranteeRate", threadLocalApplyCost.get().getFyxdbfl()); } String respData = ""; try { LOGGER.info("请求结算系统ICBC利转费计算贴息金额接口,url={},params={}", url, JSON.toJSONString(params)); respData = RestTemplateUtil.sendRequest(url, params, null); LOGGER.info("请求结算系统ICBC利转费计算贴息金额接口,url={},params={},返回报文:{}", url, JSON.toJSONString(params), respData); } catch (Exception e) { LOGGER.error("请求结算系统ICBC利转费计算贴息金额接口异常,订单编号:{}", threadLocalApplyMain.get().getApplyNo(), e); return convertResult(dscCapitalDto, false, "试算贴息失败!"); } if (org.apache.commons.lang3.StringUtils.isBlank(respData)) { LOGGER.error("请求结算系统ICBC利转费计算贴息金额接口,订单编号:{},获返回值为空", threadLocalApplyMain.get().getApplyNo()); return convertResult(dscCapitalDto, false, "试算贴息失败!"); } JSONObject synJson = JSONObject.parseObject(respData); if (!"true".equals(synJson.getString("success"))) { LOGGER.error("请求结算系统ICBC利转费计算贴息金额接口,申请编号:{},synJson.optString('success')为false", threadLocalApplyMain.get().getApplyNo()); return convertResult(dscCapitalDto, false, "试算贴息失败!"); } if (org.apache.commons.lang3.StringUtils.isBlank(synJson.getString("data")) || synJson.getJSONObject("data").isEmpty()) { LOGGER.error("请求结算系统ICBC利转费计算贴息金额接口,申请编号:{},返回值synJson.optString('data')为null或者为空", threadLocalApplyMain.get().getApplyNo()); return convertResult(dscCapitalDto, false, "试算贴息失败!"); } JSONObject data = synJson.getJSONObject("data"); // 易鑫服务费 BigDecimal yxServiceAmt = new BigDecimal(data.getString("yxServiceAmount")); // 银行手续费 BigDecimal bankServiceAmt = new BigDecimal(data.getString("bankServiceAmount")); // 1. 帖0息,可准入。(贴息金额 = 银行成本费+易鑫服务费) if (threadLocalApplyCost.get().getFcstxze().add(threadLocalApplyCost.get().getFdlstxze()).compareTo(yxServiceAmt.add(bankServiceAmt).setScale(2, RoundingMode.HALF_UP)) == 0) { return convertResult(dscCapitalDto, true, "预审通过"); } // 2. 没有帖到银行的成本费,可准入。 (贴息金额<=易鑫服务费) if (threadLocalApplyCost.get().getFcstxze().add(threadLocalApplyCost.get().getFdlstxze()).compareTo(yxServiceAmt.setScale(2, RoundingMode.HALF_UP)) <= 0) { return convertResult(dscCapitalDto, true, "预审通过"); } LOGGER.info("贴息金额超过易鑫服务费,贴息规则不满足,不允许准入"); return convertResult(dscCapitalDto, false, "预审失败!"); } } catch (BzException e) { LOGGER.error("资方预审异常,{},{}", threadLocalApplyMain.get().getApplyNo(), e.getMessage()); dscCapitalDto.setPretrialResult(false); //发起预审失败 dscCapitalDto.setPretrialMsg("资方预审异常"); return dscCapitalDto; } catch (Exception e) { LOGGER.error("资方预审异常,{}", threadLocalApplyMain.get().getApplyNo(), e); dscCapitalDto.setPretrialResult(false); //发起预审失败 dscCapitalDto.setPretrialMsg("资方预审异常"); return dscCapitalDto; } } private DscCapitalDto convertResult(DscCapitalDto dscCapitalDto, boolean result, String msg){ dscCapitalDto.setPretrialResult(result); //发起预审失败 dscCapitalDto.setPretrialMsg(msg); return dscCapitalDto; } /** * 1、如贴息后客户费率(结算费率-厂商和经销商贴息费率)高于银行资金成本费率,则对银行不属于补息产品,返回。(适应准入2) * 2、如贴息后客户费率(结算费率-厂商和经销商贴息费率)低于银行资金成本费率,且客户利率不为0(为0可能为贴0息产品,放在第三条校验),不允许准入,抛异常 * 3、贴息金额>0,同时客户费率=0准入,银行补息金额为:客户融资额X银行成本费率。(贴0息) * * @param interestAmt 贴息金额 * @param customerFeeRate 客户费率 * @param bankCostRate 银行资金成本费率 * @param customerFinancingAmt 客户融资额 * @throws BzException 如果不允许准入工行的资产,则抛出异常 */ public static BigDecimal calculateInterestRate(BigDecimal interestAmt, BigDecimal customerFeeRate, BigDecimal bankCostRate, BigDecimal customerFinancingAmt) throws BzException{ if (customerFeeRate.compareTo(bankCostRate) >= 0){ LOGGER.info("非补息"); return BigDecimal.ZERO; } if (customerFeeRate.compareTo(BigDecimal.ZERO) > 0 && customerFeeRate.compareTo(bankCostRate) < 0){ throw new BzException("客户费率不为0且低于银行资金成本费率,不允许准入"); } if (BigDecimal.ZERO.compareTo(interestAmt) < 0 && BigDecimal.ZERO.compareTo(customerFeeRate) == 0) { return customerFinancingAmt.multiply(bankCostRate); } throw new BzException("异常情况,不允许准入"); } }
package lib.tales.lemon.file; public class LmIndex { public int iPos; public int iSize; public int iEtc; public int iEx1; public int iEx2; public int iEx3; public int iEx4; public int iEx5; public byte strName[]; }
package com.tencent.mm.plugin.address.model; import com.tencent.mm.a.o; import com.tencent.mm.ab.b; import com.tencent.mm.ab.b.a; import com.tencent.mm.ab.e; import com.tencent.mm.ab.l; import com.tencent.mm.network.k; import com.tencent.mm.network.q; import com.tencent.mm.protocal.c.bew; import com.tencent.mm.protocal.c.bex; import com.tencent.mm.protocal.c.bhy; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; public final class d extends l implements k { private b diG; private e diJ; public int status; public d(String str, String str2, o oVar) { boolean z = true; a aVar = new a(); aVar.dIG = new bew(); aVar.dIH = new bex(); aVar.uri = "/cgi-bin/micromsg-bin/rcptinfoimport"; aVar.dIF = 582; aVar.dII = 0; aVar.dIJ = 0; String str3 = "MicroMsg.NetSceneRcptInfoImportYiXun"; StringBuilder append = new StringBuilder("a2key is ").append(!bi.oW(str)).append(", newa2key is "); if (bi.oW(str2)) { z = false; } x.d(str3, append.append(z).toString()); this.diG = aVar.KT(); bew bew = (bew) this.diG.dID.dIL; bew.reB = new bhy().bq(bi.WP(str)); bew.sgu = new bhy().bq(bi.WP(str2)); bew.qq = oVar.intValue(); } public final void a(int i, int i2, int i3, String str, q qVar, byte[] bArr) { x.d("MicroMsg.NetSceneRcptInfoImportYiXun", "errType:" + i2 + ",errCode:" + i3 + ",errMsg" + str); if (i2 == 0 && i3 == 0) { bex bex = (bex) ((b) qVar).dIE.dIL; this.status = bex.sgv; x.d("MicroMsg.NetSceneRcptInfoImportYiXun", "status : " + this.status); if (bex.sgt.sgw != null && this.status == 0) { x.d("MicroMsg.NetSceneRcptInfoImportYiXun", "resp.rImpl.rcptinfolist.rcptinfolist " + bex.sgt.sgw.size()); com.tencent.mm.plugin.address.a.a.Zv(); com.tencent.mm.plugin.address.a.a.Zx().q(bex.sgt.sgw); com.tencent.mm.plugin.address.a.a.Zv(); com.tencent.mm.plugin.address.a.a.Zx().Zz(); } } this.diJ.a(i2, i3, str, this); } public final int getType() { return 582; } public final int a(com.tencent.mm.network.e eVar, e eVar2) { this.diJ = eVar2; return a(eVar, this.diG, this); } }
/* Copyright (c) 2001-2007, David A. Clunie DBA Pixelmed Publishing. All rights reserved. */ package edu.co.unal.bioing.jnukak3d.ImageUtil; //import java.io.BufferedInputStream; //import java.io.File; //import java.io.FileInputStream; //import java.io.IOException; import java.awt.GraphicsEnvironment; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.awt.image.ColorModel; import java.awt.Transparency; import java.awt.color.ColorSpace; import java.awt.image.ByteLookupTable; import java.awt.image.ComponentColorModel; import java.awt.image.DataBuffer; import java.awt.image.LookupOp; import java.awt.image.SampleModel; import java.awt.image.WritableRaster; import java.util.Date; //import javax.imageio.ImageIO; //import com.pixelmed.dicom.Attribute; //import com.pixelmed.dicom.AttributeList; //import com.pixelmed.dicom.DecimalStringAttribute; //import com.pixelmed.dicom.DicomException; //import com.pixelmed.dicom.DicomInputStream; //import com.pixelmed.dicom.ModalityTransform; //import com.pixelmed.dicom.SOPClass; //import com.pixelmed.dicom.TagFromName; //import com.pixelmed.dicom.VOITransform; /** * <p>A class of static methods to perform window operations on images.</p> * * @author dclunie */ public class WindowCenterAndWidth { private static boolean DEBUG=false; private static final int constYmin = 0; private static final int constYmax = 255; /** * @param lut * @param pad * @param padRangeLimit * @param mask */ protected static void applyPaddingValueRangeToLUT(byte[] lut,int pad,int padRangeLimit,int mask) { //lut[pad&mask]=(byte)0; int maskedPadStart = pad&mask; int maskedPadEnd = padRangeLimit&mask; int incr = maskedPadStart <= maskedPadEnd ? 1 : -1; for (int i=maskedPadStart; i != maskedPadEnd; i+=incr) { //System.err.println("WindowCenterAndWidth.applyPaddingValueRangeToLUT(): LUT index set to zero for pad in range "+i); lut[i]=(byte)0; } lut[maskedPadEnd]=(byte)0; // since not done in for loop due to bi-directional end condition //System.err.println("WindowCenterAndWidth.applyPaddingValueRangeToLUT(): LUT index set to zero for pad in range "+maskedPadEnd); } /** * @param src * @param center * @param width * @param signed * @param inverted * @param useSlope * @param useIntercept * @param usePad * @param pad */ public static final BufferedImage applyWindowCenterAndWidthLogistic(BufferedImage src,double center,double width, boolean signed,boolean inverted,double useSlope,double useIntercept,boolean usePad,int pad) { return applyWindowCenterAndWidthLogistic(src,center,width,signed,inverted,useSlope,useIntercept,usePad,pad,pad); } /** * @param src * @param center * @param width * @param signed * @param inverted * @param useSlope * @param useIntercept * @param usePad * @param pad * @param padRangeLimit */ public static final BufferedImage applyWindowCenterAndWidthLogistic(BufferedImage src,double center,double width, boolean signed,boolean inverted,double useSlope,double useIntercept,boolean usePad,int pad,int padRangeLimit) { //System.err.println("WindowCenterAndWidth.applyWindowCenterAndWidthLogistic(): center="+center+" width="+width); int ymin = 0; int ymax = 255; int startx; int endx; byte lut[] = null; int mask; //System.err.println("WindowCenterAndWidth.applyWindowCenterAndWidthLogistic(): bottom="+bottom+" top="+top); int dataType = src.getSampleModel().getDataType(); //System.err.println("WindowCenterAndWidth.applyWindowCenterAndWidthLogistic(): Data type "+dataType); if (dataType == DataBuffer.TYPE_SHORT || dataType == DataBuffer.TYPE_USHORT) { //System.err.println("WindowCenterAndWidth.applyWindowCenterAndWidthLogistic(): Data type is short or ushort and signed is "+signed); startx = signed ? -32768 : 0; endx = signed ? 32768 : 65536; lut=new byte[65536]; mask=0xffff; } else if (dataType == DataBuffer.TYPE_BYTE) { //System.err.println("WindowCenterAndWidth.applyWindowCenterAndWidthLogistic(): Data type is byte and signed is "+signed); startx = signed ? -128 : 0; endx = signed ? 128 : 256; lut=new byte[256]; mask=0xff; } else { throw new IllegalArgumentException(); } //double a = ymax; //double b = 1/width; //double c = center < 0 ? 0 : center; //for (int xi=startx; xi<endx; ++xi) { // double x = xi*useSlope+useIntercept; // double y = a / (1 + c * Math.exp(-b*x)) + 0.5; // if (y < ymin) y=ymin; // else if (y > ymax) y=ymax; // if (inverted) y=(byte)(ymax-y); // lut[xi&mask]=(byte)y; //} int yrange = ymax - ymin; for (int xi=startx; xi<endx; ++xi) { double x = xi*useSlope+useIntercept; double y = yrange / (1 + Math.exp(-4*(x - center)/width)) + ymin + 0.5; if (y < ymin) y=ymin; else if (y > ymax) y=ymax; if (inverted) y=(byte)(ymax-y); //if (xi%16 == 0) System.err.println(xi+"\t"+(((int)y)&0xff)); lut[xi&mask]=(byte)y; } if (usePad) { applyPaddingValueRangeToLUT(lut,pad,padRangeLimit,mask); } LookupOp lookup=new LookupOp(new ByteLookupTable(0,lut), null); ColorModel dstColorModel=new ComponentColorModel( ColorSpace.getInstance(ColorSpace.CS_GRAY), new int[] {8}, false, // has alpha false, // alpha premultipled Transparency.OPAQUE, DataBuffer.TYPE_BYTE ); BufferedImage dst = lookup.filter(src,lookup.createCompatibleDestImage(src,dstColorModel)); // Fails if src is DataBufferShort return dst; } /** * @param src * @param center * @param width * @param signed * @param inverted * @param useSlope * @param useIntercept * @param usePad * @param pad */ public static final BufferedImage applyWindowCenterAndWidthLinear(BufferedImage src,double center,double width, boolean signed,boolean inverted,double useSlope,double useIntercept,boolean usePad,int pad) { return applyWindowCenterAndWidthLinear(src,center,width,signed,inverted,useSlope,useIntercept,usePad,pad,pad); } /** * @param src * @param center * @param width * @param signed * @param inverted * @param useSlope * @param useIntercept * @param usePad * @param pad * @param padRangeLimit */ public static final BufferedImage applyWindowCenterAndWidthLinear(BufferedImage src,double center,double width, boolean signed,boolean inverted,double useSlope,double useIntercept,boolean usePad,int pad,int padRangeLimit) { //System.err.println("WindowCenterAndWidth.applyWindowCenterAndWidthLinear(): center="+center+" width="+width); // byte bymin = (byte)constYmin; byte bymax = (byte)constYmax; double yrange = constYmax - constYmin; double cmp5 = center - 0.5; double wm1 = width - 1.0; double halfwm1 = wm1/2.0; double bottom = cmp5 - halfwm1; double top = cmp5 + halfwm1; int startx; int endx; byte lut[] = null; int mask; //System.err.println("WindowCenterAndWidth.applyWindowCenterAndWidthLinear(): bottom="+bottom+" top="+top); int dataType = src.getSampleModel().getDataType(); //System.err.println("WindowCenterAndWidth.applyWindowCenterAndWidthLinear(): Data type "+dataType); if (dataType == DataBuffer.TYPE_SHORT || dataType == DataBuffer.TYPE_USHORT) { //System.err.println("WindowCenterAndWidth.applyWindowCenterAndWidthLinear(): Data type is short or ushort and signed is "+signed); /*if(DEBUG) System.out.println("Data type found to be Ushort");*/ startx = signed ? -32768 : 0; endx = signed ? 32768 : 65536; lut=new byte[65536]; mask=0xffff; } else if (dataType == DataBuffer.TYPE_BYTE) { //System.err.println("WindowCenterAndWidth.applyWindowCenterAndWidthLinear(): Data type is byte and signed is "+signed); /* if(DEBUG) System.out.println("Data type found to be Byte");*/ startx = signed ? -128 : 0; endx = signed ? 128 : 256; lut=new byte[256]; mask=0xff; } else { throw new IllegalArgumentException(); } for (int xi=startx; xi<endx; ++xi) { double x = xi*useSlope+useIntercept; byte y; if (x <= bottom) y=bymin; else if (x > top) y=bymax; else { y = (byte)(((x-cmp5)/wm1 + 0.5)*yrange+constYmin); //System.err.println("xi&0xffff="+(xi&0xffff)+" y="+((int)y&0xff)+" x="+x); } if (inverted) y=(byte)(constYmax-y); //if (xi%16 == 0) System.err.println(xi+"\t"+(((int)y)&0xff)); lut[xi&mask]=y; } if (usePad) { applyPaddingValueRangeToLUT(lut,pad,padRangeLimit,mask); } /*System.out.println("Lut size "+lut.length); for(int i=0;i<lut.length;i++){ System.out.println(i+"->"+lut[i]); }*/ /* RenderingHints hints = new RenderingHints(null); hints.put(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_DEFAULT);*/ LookupOp lookup=new LookupOp(new ByteLookupTable(0,lut), null); ColorModel dstColorModel=new ComponentColorModel( ColorSpace.getInstance(ColorSpace.CS_GRAY), new int[] {8}, false, // has alpha false, // alpha premultipled Transparency.OPAQUE, DataBuffer.TYPE_BYTE ); BufferedImage dst = lookup.filter(src,lookup.createCompatibleDestImage(src,dstColorModel)); // Fails if src is DataBufferShort /* */ //System.err.println("WindowCenterAndWidth.applyWindowCenterAndWidthLinear(): BufferedImage out of LookupOp"+dst); return dst; } /** * @param src * @param center * @param width * @param signed * @param inverted * @param useSlope * @param useIntercept * @param usePad * @param pad * @param largestGray * @param bitsPerEntry * @param numberOfEntries * @param redTable * @param greenTable * @param blueTable */ public static final BufferedImage applyWindowCenterAndWidthWithPaletteColor(BufferedImage src,double center,double width, boolean signed,boolean inverted,double useSlope,double useIntercept, boolean usePad,int pad, int largestGray,int bitsPerEntry,int numberOfEntries, short[] redTable,short[] greenTable,short[] blueTable) { return applyWindowCenterAndWidthWithPaletteColor(src,center,width,signed,inverted,useSlope,useIntercept,usePad,pad,pad, largestGray,bitsPerEntry,numberOfEntries,redTable,greenTable,blueTable); } /** * @param src * @param center * @param width * @param signed * @param inverted * @param useSlope * @param useIntercept * @param usePad * @param pad * @param padRangeLimit * @param largestGray * @param bitsPerEntry * @param numberOfEntries * @param redTable * @param greenTable * @param blueTable */ public static final BufferedImage applyWindowCenterAndWidthWithPaletteColor(BufferedImage src,double center,double width, boolean signed,boolean inverted,double useSlope,double useIntercept, boolean usePad,int pad,int padRangeLimit, int largestGray,int bitsPerEntry,int numberOfEntries, short[] redTable,short[] greenTable,short[] blueTable) { //System.err.println("WindowCenterAndWidth.applyWindowCenterAndWidthWithPaletteColor center="+center+" width="+width); int ymin = 0; int ymax = 255; byte bymin = (byte)ymin; byte bymax = (byte)ymax; double yrange = ymax - ymin; double cmp5 = center - 0.5; double wm1 = width - 1.0; double halfwm1 = wm1/2.0; double bottom = cmp5 - halfwm1; double top = cmp5 + halfwm1; //double gamma = 2.2; int startx = signed ? -32768 : 0; // hmmm .... int endx = signed ? 32768 : 65536; //int endx = largestGray; byte rlut[]=new byte[65536]; byte glut[]=new byte[65536]; byte blut[]=new byte[65536]; for (int xi=startx; xi<endx; ++xi) { double x = xi*useSlope+useIntercept; byte y; if (x <= bottom) y=bymin; else if (x > top) y=bymax; else { y = (byte)(((x-cmp5)/wm1 + 0.5)*yrange+ymin); //System.err.println("xi&0xffff="+(xi&0xffff)+" y="+((int)y&0xff)+" x="+x); } if (inverted) y=(byte)(ymax-y); rlut[xi&0xffff]=y; glut[xi&0xffff]=y; blut[xi&0xffff]=y; } //System.err.println("WindowCenterAndWidth.applyWindowCenterAndWidthWithPaletteColor(): numberOfEntries = "+numberOfEntries); //System.err.println("WindowCenterAndWidth.applyWindowCenterAndWidthWithPaletteColor(): redTable.length = "+redTable.length); //System.err.println("WindowCenterAndWidth.applyWindowCenterAndWidthWithPaletteColor(): greenTable.length = "+greenTable.length); //System.err.println("WindowCenterAndWidth.applyWindowCenterAndWidthWithPaletteColor(): blueTable.length = "+blueTable.length); //System.err.println("WindowCenterAndWidth.applyWindowCenterAndWidthWithPaletteColor(): largestGray="+largestGray); int shiftRight = bitsPerEntry-8; int i; int xi; for (xi=largestGray+1,i=0; i < numberOfEntries; ++xi,++i) { //System.err.println("WindowCenterAndWidth.applyWindowCenterAndWidthWithPaletteColor: xi="+xi+" i="+i); //System.err.println("WindowCenterAndWidth.applyWindowCenterAndWidthWithPaletteColor: redTable[i]="+redTable[i]); //System.err.println("WindowCenterAndWidth.applyWindowCenterAndWidthWithPaletteColor: redTable[i]>>shiftRight="+(redTable[i]>>shiftRight)); //System.err.println("WindowCenterAndWidth.applyWindowCenterAndWidthWithPaletteColor: redTable[i]>>shiftRight="+Integer.toHexString((redTable[i]>>shiftRight)&0xff)); rlut[xi&0xffff]=(byte)(redTable[i]>>shiftRight); glut[xi&0xffff]=(byte)(greenTable[i]>>shiftRight); blut[xi&0xffff]=(byte)(blueTable[i]>>shiftRight); } if (usePad) { applyPaddingValueRangeToLUT(rlut,pad,padRangeLimit,0xffff); applyPaddingValueRangeToLUT(glut,pad,padRangeLimit,0xffff); applyPaddingValueRangeToLUT(blut,pad,padRangeLimit,0xffff); } int columns = src.getWidth(); int rows = src.getHeight(); SampleModel srcSampleModel = src.getSampleModel(); WritableRaster srcRaster = src.getRaster(); DataBuffer srcDataBuffer = srcRaster.getDataBuffer(); int srcNumBands = srcRaster.getNumBands(); //ColorModel dstColorModel = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration().getColorModel(); ColorModel dstColorModel = BufferedImageUtilities.getMostFavorableColorModel(); if (dstColorModel == null) { // This color model is what we use in SourceImage when reading RGB images dstColorModel = new ComponentColorModel( ColorSpace.getInstance(ColorSpace.CS_sRGB), new int[] {8,8,8}, false, // has alpha false, // alpha premultipled Transparency.OPAQUE, DataBuffer.TYPE_BYTE ); } WritableRaster dstRaster = dstColorModel.createCompatibleWritableRaster(columns,rows); DataBuffer dstDataBuffer = dstRaster.getDataBuffer(); BufferedImage dst = new BufferedImage(dstColorModel, dstRaster, dstColorModel.isAlphaPremultiplied(), null); SampleModel dstSampleModel = dst.getSampleModel(); int dstNumBands = dstRaster.getNumBands(); int srcPixels[] = null; // to disambiguate SampleModel.getPixels() method signature srcPixels = srcSampleModel.getPixels(0,0,columns,rows,srcPixels,srcDataBuffer); int srcPixelsLength = srcPixels.length; int dstPixels[] = null; // to disambiguate SampleModel.getPixels() method signature dstPixels = dstSampleModel.getPixels(0,0,columns,rows,dstPixels,dstDataBuffer); int dstPixelsLength = dstPixels.length; //System.err.println("WindowCenterAndWidth.applyWindowCenterAndWidthWithPaletteColor: dstNumBands = "+dstNumBands); if (srcNumBands == 1 && dstNumBands == 4 && srcPixelsLength*4 == dstPixelsLength) { //System.err.println("WindowCenterAndWidth.applyWindowCenterAndWidthWithPaletteColor: converting gray to RGBA"); int dstIndex=0; for (int srcIndex=0; srcIndex<srcPixelsLength; ++srcIndex) { dstPixels[dstIndex++]=rlut[srcPixels[srcIndex]]; dstPixels[dstIndex++]=glut[srcPixels[srcIndex]]; dstPixels[dstIndex++]=blut[srcPixels[srcIndex]]; dstPixels[dstIndex++]=-1; } dstSampleModel.setPixels(0,0,columns,rows,dstPixels,dstDataBuffer); } else if (srcNumBands == 1 && dstNumBands == 3 && srcPixelsLength*3 == dstPixelsLength) { //System.err.println("WindowCenterAndWidth.applyWindowCenterAndWidthWithPaletteColor: converting gray to RGB"); int dstIndex=0; for (int srcIndex=0; srcIndex<srcPixelsLength; ++srcIndex) { dstPixels[dstIndex++]=rlut[srcPixels[srcIndex]]; dstPixels[dstIndex++]=glut[srcPixels[srcIndex]]; dstPixels[dstIndex++]=blut[srcPixels[srcIndex]]; } dstSampleModel.setPixels(0,0,columns,rows,dstPixels,dstDataBuffer); } return dst; } /** * @param src * @param center * @param width * @param identityCenter * @param identityWidth * @param signed * @param inverted * @param useSlope * @param useIntercept * @param usePad * @param pad * @param padRangeLimit * @param numberOfEntries * @param bitsPerEntry * @param grayTable * @param entryMin * @param entryMax * @param topOfEntryRange */ public static final BufferedImage applyVOILUT(BufferedImage src,double center,double width,double identityCenter,double identityWidth, boolean signed,boolean inverted,double useSlope,double useIntercept, boolean usePad,int pad,int padRangeLimit, int numberOfEntries,int firstValueMapped,int bitsPerEntry,short[] grayTable,int entryMin,int entryMax,int topOfEntryRange) { //System.err.println("WindowCenterAndWidth.applyVOILUT(): firstValueMapped="+firstValueMapped); //System.err.println("WindowCenterAndWidth.applyVOILUT center="+center+" width="+width); int ymin = 0; int ymax = 255; double yrange = ymax - ymin; int bottomOfEntryRange = 0; double entryRange = topOfEntryRange - bottomOfEntryRange; //System.err.println("WindowCenterAndWidth.applyVOILUT(): bottomOfEntryRange="+bottomOfEntryRange+" topOfEntryRange="+topOfEntryRange+" entryRange="+entryRange); int firstLUTValue = grayTable[0] & 0xffff; int lastLUTValue = grayTable[numberOfEntries-1] & 0xffff; //System.err.println("WindowCenterAndWidth.applyVOILUT(): firstLUTValue="+firstLUTValue+" lastLUTValue="+lastLUTValue); byte bymin = (byte)(((firstLUTValue-bottomOfEntryRange)/entryRange)*yrange+ymin); byte bymax = (byte)(((lastLUTValue -bottomOfEntryRange)/entryRange)*yrange+ymin); //System.err.println("WindowCenterAndWidth.applyVOILUT(): bymin="+(bymin&0xff)+" bymax="+(bymax&0xff)); int startx; int endx; byte lut[] = null; int mask; int dataType = src.getSampleModel().getDataType(); //System.err.println("WindowCenterAndWidth.applyVOILUT(): Data type "+dataType); if (dataType == DataBuffer.TYPE_SHORT || dataType == DataBuffer.TYPE_USHORT) { //System.err.println("WindowCenterAndWidth.applyVOILUT(): Data type is short or ushort and signed is "+signed); startx = signed ? -32768 : 0; endx = signed ? 32768 : 65536; lut=new byte[65536]; mask=0xffff; } else if (dataType == DataBuffer.TYPE_BYTE) { //System.err.println("WindowCenterAndWidth.applyVOILUT(): Data type is byte and signed is "+signed); startx = signed ? -128 : 0; endx = signed ? 128 : 256; lut=new byte[256]; mask=0xff; } else { throw new IllegalArgumentException(); } for (int xi=startx; xi<endx; ++xi) { double x = xi*useSlope+useIntercept; byte y; //int lutIndex = (int)(x-firstValueMapped); // warning: there could be sign issues here related to the nominal "VR" of the second LUT Descriptor entry - see PS 3.3 C.11.2.1.1 :( //int lutIndex = (int)(((x-center)/width) * numberOfEntries + numberOfEntries/2); int lutIndex = (int)(((x-center)/width) * identityWidth + identityCenter - firstValueMapped); //System.err.println("xi&0xffff="+(xi&0xffff)+" x="+x+" lutIndex="+lutIndex); if (lutIndex < 0) { y=bymin; } else if (lutIndex > (numberOfEntries-1)) { y=bymax; } else { y = (byte)(((grayTable[lutIndex] & 0xffff)/entryRange)*yrange+ymin); //System.err.println("xi&0xffff="+(xi&0xffff)+" y="+((int)y&0xff)+" x="+x+" lutIndex="+lutIndex); } if (inverted) y=(byte)(ymax-y); //if (xi%16 == 0) System.err.println(xi+"\t"+(((int)y)&0xff)); lut[xi&mask]=y; } if (usePad) { applyPaddingValueRangeToLUT(lut,pad,padRangeLimit,mask); } LookupOp lookup=new LookupOp(new ByteLookupTable(0,lut), null); ColorModel dstColorModel=new ComponentColorModel( ColorSpace.getInstance(ColorSpace.CS_GRAY), new int[] {8}, false, // has alpha false, // alpha premultipled Transparency.OPAQUE, DataBuffer.TYPE_BYTE ); BufferedImage dst = lookup.filter(src,lookup.createCompatibleDestImage(src,dstColorModel)); // Fails if src is DataBufferShort //System.err.println("WindowCenterAndWidth.applyVOILUT(): BufferedImage out of LookupOp"+dst); return dst; } }
package test; import static org.junit.Assert.*; import junit.framework.Assert; import model.ChemicalElement; import model.Classification; import model.SpectralLines; import org.junit.Before; import org.junit.Test; public class SpectralLinesTest { ChemicalElement hydrogen; SpectralLines elementLines; @Before public void setUp() throws Exception { hydrogen = new ChemicalElement("Hidrogênio", "H", 1, 1, 1, Classification.NAO_METAIS); elementLines = new SpectralLines(hydrogen); } @Test public void testConstructorLinhasEspectrais() { try { new SpectralLines(null); Assert.fail("Esperava excessão."); } catch (Exception e) { assertEquals("Elemento nao pode ser nulo!", e.getMessage()); } } @Test public void testParamGets() { try { elementLines.getEnergy(0); Assert.fail("Esperava excessão."); } catch (Exception e) { assertEquals("Comprimento de onda invalido!", e.getMessage()); } try { elementLines.getEnergy(-1000); Assert.fail("Esperava excessão."); } catch (Exception e) { assertEquals("Comprimento de onda invalido!", e.getMessage()); } try { elementLines.getPosition(0, 40); Assert.fail("Esperava excessão."); } catch (Exception e) { assertEquals("Parametro(s) invalido(s)!", e.getMessage()); } try { elementLines.getPosition(-1000, 40); Assert.fail("Esperava excessão."); } catch (Exception e) { assertEquals("Parametro(s) invalido(s)!", e.getMessage()); } try { elementLines.getPosition(40, 0); Assert.fail("Esperava excessão."); } catch (Exception e) { assertEquals("Parametro(s) invalido(s)!", e.getMessage()); } try { elementLines.getPosition(40, -1000); Assert.fail("Esperava excessão."); } catch (Exception e) { assertEquals("Parametro(s) invalido(s)!", e.getMessage()); } } @Test public void testGetsAndSets() throws Exception { try { elementLines.getEnergy(-100); Assert.fail("Esperava excessão."); } catch(Exception e) { assertEquals("Comprimento de onda invalido!", e.getMessage()); } try { elementLines.getEnergy(0); Assert.fail("Esperava excessão."); } catch(Exception e) { assertEquals("Comprimento de onda invalido!", e.getMessage()); } try { elementLines.getPosition(-200, -500); Assert.fail("Esperava excessão."); } catch(Exception e) { assertEquals("Parametro(s) invalido(s)!", e.getMessage()); } try { elementLines.getPosition(-200, 500); Assert.fail("Esperava excessão."); } catch(Exception e) { assertEquals("Parametro(s) invalido(s)!", e.getMessage()); } try { elementLines.getPosition(0, -500); Assert.fail("Esperava excessão."); } catch(Exception e) { assertEquals("Parametro(s) invalido(s)!", e.getMessage()); } try { elementLines.getPosition(1, -500); Assert.fail("Esperava excessão."); } catch(Exception e) { assertEquals("Parametro(s) invalido(s)!", e.getMessage()); } try { elementLines.getPosition(0, 0); Assert.fail("Esperava excessão."); } catch(Exception e) { assertEquals("Parametro(s) invalido(s)!", e.getMessage()); } elementLines.setChemicalElement(new ChemicalElement("Hidrogênio", "H", 1, 1, 1, Classification.NAO_METAIS)); assertEquals(new ChemicalElement("Hidrogênio", "H", 1, 1, 1, Classification.NAO_METAIS), elementLines.getElement()); elementLines.setChemicalElement(new ChemicalElement("Ferro", "Fe", 4, 8, 26, Classification.METAIS_DE_TRANSICAO)); assertEquals(new ChemicalElement("Ferro", "Fe", 4, 8, 26, Classification.METAIS_DE_TRANSICAO), elementLines.getElement()); elementLines.setChemicalElement(new ChemicalElement("Bromo", "Br", 4, 17, 35, Classification.HALOGENIOS)); assertEquals(new ChemicalElement("Bromo", "Br", 4, 17, 35, Classification.HALOGENIOS), elementLines.getElement()); elementLines.setChemicalElement(new ChemicalElement("Elemento", "E", 1, 1, 21, Classification.LIQUIDO)); assertEquals(new ChemicalElement("Elemento", "E", 1, 1, 21, Classification.LIQUIDO), elementLines.getElement()); } @Test public void testFunctions() throws Exception { assertEquals(3.712982585550099E-19, elementLines.getEnergy(535E-9), 0); assertEquals(5.255147310236251E-19, elementLines.getEnergy(378E-9), 0); assertEquals(6.921413530555061E-19, elementLines.getEnergy(287E-9), 0); assertEquals(4.966114208173257E-19, elementLines.getEnergy(400E-9), 0); assertEquals(2.8377795475275755E-19, elementLines.getEnergy(700E-9), 0); assertEquals(1.2150227305844928E-7, elementLines.getPosition(1, 2), 0); assertEquals(1.0251754289306658E-7, elementLines.getPosition(1, 3), 0); assertEquals(6.56112274515626E-7,elementLines.getPosition(2, 3), 0); assertEquals(1.8746064986160745E-6, elementLines.getPosition(3, 4), 0); assertEquals(4.651258890518761E-6, elementLines.getPosition(5, 7), 0); } }
package net.sssanma.mc.data.user.itembox; import net.sssanma.mc.data.user.User; import net.sssanma.mc.data.user.UserLoadException; import net.sssanma.mc.data.user.rank.UserFunctionLimitedException; import java.io.File; import java.io.FileFilter; import java.io.FileNotFoundException; import java.util.HashMap; import java.util.Map; public final class UserManagerItemBox { final File itemboxFolder; private User user; private Map<String, ItemBox> itemboxes = new HashMap<>(); public UserManagerItemBox(User user) { this.user = user; this.itemboxFolder = new File(user.userFolder, "itembox"); } public User getUser() { return user; } public ItemBox getItemBox(String name) { return itemboxes.get(name); } public ItemBox[] getItemBoxes() { return itemboxes.values().toArray(new ItemBox[itemboxes.size()]); } synchronized void removeItemBoxFromList(ItemBox itemBox) { itemboxes.remove(itemBox.getName()); } public ItemBox createNewItemBox(String name) throws ItemBoxException, UserFunctionLimitedException { user.managerRank.getRankType().userRank.checkCanCreateMoreItemBox(this); if (!itemboxes.containsKey(name)) { ItemBox itembox = new ItemBox(this); itembox.createNew(name); itemboxes.put(name, itembox); return itembox; } else throw new ItemBoxException(name + "はすでに存在します。別の名前にしてください!"); } void requestSaveAllItemBoxes() { for (ItemBox itemBox : itemboxes.values()) itemBox.requestSave(); } public void loadItemBoxes() throws UserLoadException, FileNotFoundException { this.itemboxFolder.mkdirs(); File[] files = itemboxFolder.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { return pathname.isDirectory(); } }); // int loadSucceed = 0; for (File file : files) { ItemBox itemBox = new ItemBox(this); itemBox.load(file.getName()); ItemBox dup = itemboxes.put(itemBox.getName(), itemBox); // if (dup == null) // loadSucceed++; // else if (dup != null) throw new UserLoadException("itembox重複 : " + dup.getName()); } } public int getNOItemBox() { return itemboxes.size(); } }
package com.benz.event.receiver.util; import java.util.HashMap; import java.util.Map; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; /** * The Class EventReceiverUtil. */ @Component @EnableScheduling public class EventReceiverUtil { public static final Map<String, Float> inMemoryCache = new HashMap<>(); //Runs every 12 clock and update the inmemory cache @Scheduled(cron = "0 0 0 * * *") public void updateCache() { inMemoryCache.put("Bangalore", 82.75f); inMemoryCache.put("Hyderabad", 78.45f); inMemoryCache.put("Delhi", 85.25f); inMemoryCache.put("Mumbai", 81.65f); inMemoryCache.put("Punjab", 84.75f); } public float getPrice(String city) { return inMemoryCache.get(city); } }
package com.tencent.mm.plugin.appbrand.jsapi; import com.tencent.mm.plugin.appbrand.config.a$e; import com.tencent.mm.plugin.appbrand.l; import com.tencent.mm.plugin.appbrand.page.e; import org.json.JSONObject; public final class bm extends a { public static final int CTRL_INDEX = -2; public static final String NAME = "setTabBarStyle"; public final void a(l lVar, JSONObject jSONObject, int i) { a$e a_e = lVar.fdO.fcv.foP; String optString = jSONObject.optString("color", a_e.dxh); String optString2 = jSONObject.optString("selectedColor", a_e.fpb); String optString3 = jSONObject.optString("backgroundColor", a_e.fpc); String optString4 = jSONObject.optString("borderStyle", a_e.fpd); com.tencent.mm.plugin.appbrand.page.l currentPage = lVar.fdO.fcz.getCurrentPage(); if (currentPage instanceof e) { ((e) currentPage).getTabBar().h(optString, optString2, optString3, optString4); lVar.E(i, f("ok", null)); return; } lVar.E(i, f("fail:not TabBar page", null)); } }
package com.qswy.app.utils; import android.content.Context; import android.widget.Toast; /** * Created by ryl on 2016/10/31. */ public class ToastUtils { private static Toast toast; public static void show(Context context,String content){ if (toast==null){ toast = Toast.makeText(context,content,Toast.LENGTH_SHORT); }else{ toast.setText(content); } toast.show(); } }
package com.newsblur.activity; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import com.newsblur.R; import com.newsblur.domain.SocialFeed; import com.newsblur.util.UIUtils; public class SocialFeedItemsList extends ItemsList { public static final String EXTRA_SOCIAL_FEED = "social_feed"; private SocialFeed socialFeed; @Override protected void onCreate(Bundle bundle) { socialFeed = (SocialFeed) getIntent().getSerializableExtra(EXTRA_SOCIAL_FEED); super.onCreate(bundle); UIUtils.setCustomActionBar(this, socialFeed.photoUrl, socialFeed.feedTitle); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.itemslist, menu); return true; } }
package com.dragon.design.pattern.visitor; import java.util.Collection; public interface Visitor { public void visitString(StringElement stringE); public void visitFloat(FloatElement floatE); public void visitCollection(Collection<Visitable> collection); }
package DomFaryna.FiveGuysOneRobot.Controls; import com.pi4j.io.gpio.*; import com.pi4j.io.gpio.event.GpioPinListenerDigital; // Button is used to wait until a button pressed before going on public class StartButton { private final Pin dPin = RaspiBcmPin.GPIO_19; //private final Pin dPin = RaspiPin.GPIO_24; private final GpioPinDigitalInput button; public StartButton() { GpioController gpio = GpioFactory.getInstance(); button = gpio.provisionDigitalInputPin(dPin, PinPullResistance.PULL_DOWN); button.setDebounce(100); } // waits for the pin to be pressed public void waitForPress() { // Add a listener to start the program iff the button has ben pressed once and only once synchronized (button){ button.addListener((GpioPinListenerDigital) event -> { synchronized (button) { System.out.println(String.format("Got event %s", event.getEdge().getName())); if (event.getEdge() != PinEdge.RISING) { return; } button.removeAllListeners(); button.notify(); } }); try { button.wait(); // Safety sleep so that the robot doesn't just YEEEEEEET when its time to go Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } // tests for a wait and the prints public void waitForPressAndPrint() { System.out.println("Gonna wait for a press"); waitForPress(); System.out.println("Got a press. No longer waiting!!!"); } public boolean getON() { return button.isHigh(); } }
package com.weijuju.iag.wxoauth.util;/** * Created by zhangyin on 2017/1/5. */ import org.apache.http.conn.ssl.TrustStrategy; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; /** * @author zhangyin * @create 2017-01-05 */ public class AnyTrustStrategy implements TrustStrategy { @Override public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }
package com.tencent.mm.plugin.wallet.balance.ui; import android.content.Intent; import android.view.MenuItem; import android.view.MenuItem.OnMenuItemClickListener; import com.tencent.mm.bg.d; import com.tencent.mm.model.q; import com.tencent.mm.wallet_core.ui.e; class WalletBalanceManagerUI$4 implements OnMenuItemClickListener { final /* synthetic */ WalletBalanceManagerUI pax; WalletBalanceManagerUI$4(WalletBalanceManagerUI walletBalanceManagerUI) { this.pax = walletBalanceManagerUI; } public final boolean onMenuItemClick(MenuItem menuItem) { Intent intent = new Intent(); intent.putExtra("rawUrl", this.pax.paw.plY); intent.putExtra("showShare", false); intent.putExtra("geta8key_username", q.GF()); intent.putExtra("KPublisherId", "pay_blance_list"); intent.putExtra("geta8key_scene", 33); d.b(this.pax, "webview", ".ui.tools.WebViewUI", intent); e.He(16); return true; } }
package assignment.easyaccount.activity; import android.app.AlertDialog; import android.app.TabActivity; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.TabHost; import android.widget.TabHost.OnTabChangeListener; import assignment.easyaccount.R; import assignment.easyaccount.dialog.DateSelectorDialog; public class QueryAccount extends TabActivity implements OnTabChangeListener { private TabHost tabHost; private static final int MENU_DELETE = 1001; private static final int REQUEST_QUERYDATE = 2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); tabHost = getTabHost(); tabHost.addTab(tabHost.newTabSpec("today").setIndicator("Bill Today",getResources().getDrawable(R.drawable.tab_today)) .setContent(new Intent(this,TodayAccount.class) .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))); tabHost.addTab(tabHost.newTabSpec("history").setIndicator("Bill History",getResources().getDrawable(R.drawable.tab_history)) .setContent(new Intent(this,HistoryAccount.class))); tabHost.setOnTabChangedListener(this); } @Override public boolean onCreateOptionsMenu(Menu menu) { menu.add(Menu.NONE,MENU_DELETE,0,"Delete selected item").setIcon(android.R.drawable.ic_menu_delete); return super.onCreateOptionsMenu(menu); } @Override public void onTabChanged(String tabId) { if(tabId.equals("history")) { Intent intent = new Intent(this,DateSelectorDialog.class); startActivityForResult(intent, REQUEST_QUERYDATE); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if(requestCode == REQUEST_QUERYDATE) { if(resultCode == RESULT_OK) { String startDate = data.getCharSequenceExtra("startDate").toString(); String endDate = data.getCharSequenceExtra("endDate").toString(); Intent queryIntent = new Intent(); queryIntent.setAction(HistoryAccount.QUERY_HISTORY_ACCOUNT); queryIntent.putExtra("startDate", startDate); queryIntent.putExtra("endDate", endDate); sendBroadcast(queryIntent); } } } }
package com.linkedbook.dto.comment; import lombok.Getter; import lombok.NoArgsConstructor; @NoArgsConstructor @Getter public class CommentInput { private String isbn; private double score; private String content; private int[] categories; }
package Stack; public class MTSTACK<X> implements ISTACK<X> { public MTSTACK() {}; public ISTACK<X> pop() throws Exception{ throw new Exception("Method pop applied to an empty stack");} public ISTACK<X> push (X v){return new NMTSTACK<X>(v, this);} public X top() throws Exception{ throw new Exception("Method first applied to an empty stack");} public boolean emptyStack() {return true;} public ISTACK<X> reverse() {return this;} public ISTACK<X> stackrest() throws Exception { throw new Exception("Method first applied to an empty stack"); } public String ToString() {return null;} }
package recycle_bin.camera2; import android.annotation.TargetApi; import android.hardware.camera2.CameraAccessException; import android.hardware.camera2.CameraCharacteristics; import android.hardware.camera2.CameraDevice; import android.hardware.camera2.CameraManager; import android.hardware.camera2.CaptureRequest; import android.os.Handler; import android.os.SystemClock; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Size; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.Locale; import java.util.TreeMap; import sci.crayfis.shramp.CaptureOverseer; import sci.crayfis.shramp.logging.ShrampLogger; /** * The ShrampCamManager class augments/wraps the Android CameraController. * Usage: * // from an Activity or Frangment "this" * ShrampCamManager myManager = ShrampCamManager.getInstance(this) * if (myManager.hasBackCamera()) { * myManager.openBackCamera(); * } */ @TargetApi(21) // Lollipop public final class ShrampCamManager { //////////////////////////////////////////////////////////////////////////////////////////////// // Nested Enum //////////////////////////////////////////////////////////////////////////////////////////////// // Enum for selecting Front, Back, or External cameras private enum mSelect { FRONT, BACK, EXTERNAL } //********************************************************************************************** // Class Variables //---------------- // There is only one ShrampCamManager instance in existence. // This is it's reference, access it with getInstance(Context) private static ShrampCamManager mInstance; // set in getInstance(Context) private static CameraManager mCameraManager; private static TreeMap<mSelect, String> mCameraIds; private static TreeMap<mSelect, CameraCharacteristics> mCameraCharacteristics; private static TreeMap<mSelect, ShrampCam> mShrampCameraDevices; private static ShrampCam mActiveCamera; // Lock to prevent multiple threads from opening a 2nd camera before closing the first private static final Object CAMERA_ACCESS_LOCK = new Object(); // logging private static final ShrampLogger mLogger = new ShrampLogger(ShrampLogger.DEFAULT_STREAM); private static final DecimalFormat mNanosFormatter = (DecimalFormat) NumberFormat.getInstance(Locale.US); //********************************************************************************************** // Class Methods //-------------- /** * Disable default constructor to limit access to getInstance(Context) */ private ShrampCamManager() { mCameraIds = new TreeMap<>(); mCameraCharacteristics = new TreeMap<>(); mShrampCameraDevices = new TreeMap<>(); } /** * Get access to single instance camera manager. * Manages all camera devices (front, back, or external) present. * @param cameraManager Context to provide CAMERA_SERVICE and access to a CameraController object. * @return The single instance of ShrampCamManager, or null if something doesn't exist. */ @Nullable public static synchronized ShrampCamManager getInstance(@NonNull CameraManager cameraManager) { if (mInstance != null) { return mInstance; } long startTime = SystemClock.elapsedRealtimeNanos(); mLogger.log("Creating CameraController"); mInstance = new ShrampCamManager(); mCameraManager = cameraManager; mLogger.log("Discovering cameras"); String[] cameraIds; try { cameraIds = ShrampCamManager.mCameraManager.getCameraIdList(); } catch (CameraAccessException e) { // TODO: ERROR mLogger.log("ERROR: Camera Access Exception; return null;"); return null; } for (String id : cameraIds) { CameraCharacteristics cameraCharacteristics; Integer lensFacing; try { cameraCharacteristics = mCameraManager.getCameraCharacteristics(id); lensFacing = cameraCharacteristics.get(CameraCharacteristics.LENS_FACING); if (lensFacing == null) { // TODO: report anomaly mLogger.log("ERROR: lensFacing == null; continue;"); continue; } mSelect cameraKey = null; switch (lensFacing) { case (CameraCharacteristics.LENS_FACING_FRONT) : { cameraKey = mSelect.FRONT; mLogger.log("Found front camera, ID: " + id); break; } case (CameraCharacteristics.LENS_FACING_BACK) : { cameraKey = mSelect.BACK; mLogger.log("Found back camera, ID: " + id); break; } case (CameraCharacteristics.LENS_FACING_EXTERNAL) : { cameraKey = mSelect.EXTERNAL; mLogger.log("Found external camera, ID: " + id); break; } } if (cameraKey == null) { // TODO: report anomally mLogger.log("ERROR: cameraKey == null; continue;"); continue; } mCameraIds.put(cameraKey, id); mCameraCharacteristics.put(cameraKey, cameraCharacteristics); } catch (CameraAccessException e) { // TODO ERROR mLogger.log("ERROR: Camera Access Exception; return null;"); return null; } } String elapsed = mNanosFormatter.format(SystemClock.elapsedRealtimeNanos() - startTime); mLogger.log("return ShrampCamManager; elapsed = " + elapsed + " [ns]"); return ShrampCamManager.mInstance; } //////////////////////////////////////////////////////////////////////////////////////////////// /** * Does this device have a front-facing camera (same side as the screen) * @return true if yes, false if no */ public boolean hasFrontCamera() { boolean hasCamera = mCameraCharacteristics.containsKey(mSelect.FRONT); mLogger.log("return: " + Boolean.toString(hasCamera)); return hasCamera; } /** * Does this device have a back-facing camera (opposite side as the screen) * @return true if yes, false if no */ public boolean hasBackCamera() { boolean hasCamera = mCameraCharacteristics.containsKey(mSelect.BACK); mLogger.log("return: " + Boolean.toString(hasCamera)); return hasCamera; } /** * Does this device have an external camera plugged in * @return true if yes, false if no */ public boolean hasExternalCamera() { boolean hasCamera = mCameraCharacteristics.containsKey(mSelect.EXTERNAL); mLogger.log("return: " + Boolean.toString(hasCamera)); return hasCamera; } //////////////////////////////////////////////////////////////////////////////////////////////// static void cameraReady(ShrampCam shrampCam) { // if multiple cameras, wait for all to check in and collect their builders // when ready, send it over to the master manager mLogger.log("All cameras reporting ready"); mActiveCamera = shrampCam; CameraDevice cameraDevice = shrampCam.getCameraDevice(); mLogger.log("return via CaptureOverseer.cameraReady();"); //CaptureOverseer.cameraReady(cameraDevice); } //////////////////////////////////////////////////////////////////////////////////////////////// /** * Open front camera device and configure it for capture */ public synchronized boolean openFrontCamera() { long startTime = SystemClock.elapsedRealtimeNanos(); if (!hasFrontCamera()) { // TODO no front camera mLogger.log("ERROR: No front camera; return false;"); return false; } CameraCharacteristics characteristics = mCameraCharacteristics.get(mSelect.FRONT); assert characteristics != null; if (mShrampCameraDevices.containsKey(mSelect.FRONT)) { // TODO: camera already open mLogger.log("Camera already open"); } else { mLogger.log("Creating CameraDevice"); mShrampCameraDevices.put(mSelect.FRONT, new ShrampCam(characteristics, "shramp_front_cam")); openCamera(mSelect.FRONT); } String elapsed = mNanosFormatter.format(SystemClock.elapsedRealtimeNanos() - startTime); mLogger.log("return true; elapsed = " + elapsed + " [ns]"); return true; } /** * Open back camera device and configure it for capture */ public synchronized boolean openBackCamera() { long startTime = SystemClock.elapsedRealtimeNanos(); if (!hasBackCamera()) { // TODO: no back camera mLogger.log("ERROR: No back camera; return false;"); return false; } CameraCharacteristics characteristics = mCameraCharacteristics.get(mSelect.BACK); assert characteristics != null; if (mShrampCameraDevices.containsKey(mSelect.BACK)) { // TODO: camera already open mLogger.log("Camera already open"); } else { mLogger.log("Creating CameraDevice"); mShrampCameraDevices.put(mSelect.BACK, new ShrampCam(characteristics, "shramp_back_cam")); openCamera(mSelect.BACK); } String elapsed = mNanosFormatter.format(SystemClock.elapsedRealtimeNanos() - startTime); mLogger.log("return true; elapsed = " + elapsed + " [ns]"); return true; } /** * Open external camera device and configure it for capture */ public synchronized boolean openExternalCamera() { long startTime = SystemClock.elapsedRealtimeNanos(); if (!hasExternalCamera()) { // TODO: no external camera mLogger.log("ERROR: No external camera; return false;"); return false; } CameraCharacteristics characteristics = mCameraCharacteristics.get(mSelect.EXTERNAL); assert characteristics != null; if (mShrampCameraDevices.containsKey(mSelect.EXTERNAL)) { // TODO: camera already open mLogger.log("Camera already open"); } else { mLogger.log("Creating CameraDevice"); mShrampCameraDevices.put(mSelect.EXTERNAL, new ShrampCam(characteristics, "shramp_external_cam")); openCamera(mSelect.EXTERNAL); } String elapsed = mNanosFormatter.format(SystemClock.elapsedRealtimeNanos() - startTime); mLogger.log("return true; elapsed = " + elapsed + " [ns]"); return true; } /** * Create ShrampCam, instantiate camera callbacks, and open the camera * @param cameraKey mSelect which camera to open */ private void openCamera(mSelect cameraKey) { long startTime = SystemClock.elapsedRealtimeNanos(); synchronized (CAMERA_ACCESS_LOCK) { mLogger.log("Opening camera now"); String cameraId = mCameraIds.get(cameraKey); assert cameraId != null; ShrampCam shrampCam = mShrampCameraDevices.get(cameraKey); assert shrampCam != null; try { mCameraManager.openCamera(cameraId, shrampCam, shrampCam.getHandler()); } catch (SecurityException e) { // TODO: user hasn't granted permissions mLogger.log("ERROR: Security Exception; return;"); return; } catch (CameraAccessException e) { // TODO: ERROR mLogger.log("ERROR: Camera Access Exception; return;"); return; } } String elapsed = mNanosFormatter.format(SystemClock.elapsedRealtimeNanos() - startTime); mLogger.log("return; elapsed = " + elapsed + " [ns]"); } //////////////////////////////////////////////////////////////////////////////////////////////// /** * Close front camera device and background threads */ public synchronized void closeFrontCamera() { mLogger.log("Close front camera"); closeCamera(mSelect.FRONT); } /** * Close back camera device and background threads */ public synchronized void closeBackCamera() { mLogger.log("Close back camera"); closeCamera(mSelect.BACK); } /** * Close back camera device and background threads */ public synchronized void closeExternalCamera() { mLogger.log("Close external camera"); closeCamera(mSelect.EXTERNAL); } /** * Close camera device and background threads * @param cameraKey mSelect which camera to close */ private void closeCamera(mSelect cameraKey) { long startTime = SystemClock.elapsedRealtimeNanos(); mActiveCamera = null; if (!mShrampCameraDevices.containsKey(cameraKey)) { mLogger.log("There was no camera to close; return;"); return; } synchronized (CAMERA_ACCESS_LOCK) { mLogger.log("Closing camera now"); try { mShrampCameraDevices.get(cameraKey).close(); } catch (NullPointerException e) { mLogger.log("ERROR: null pointer exception; return;"); return; } } String elapsed = mNanosFormatter.format(SystemClock.elapsedRealtimeNanos() - startTime); mLogger.log("return; elapsed = " + elapsed + " [ns]"); } ////////////////////////////////////////////////////////////////////////////////////////////////\ /** * @return ImageFormat constant int (either YUV_420_888 or RAW_SENSOR) */ public static int getImageFormat() { return mActiveCamera.getShrampCamSettings().getOutputFormat(); } public static int getImageBitsPerPixel() { return mActiveCamera.getShrampCamSettings().getBitsPerPixel(); } public static Size getImageSize() { return mActiveCamera.getShrampCamSettings().getOutputSize(); } public static Handler getCameraHandler() { return mActiveCamera.getHandler(); } public static CaptureRequest.Builder getCaptureRequestBuilder() { return mActiveCamera.getCaptureRequestBuilder(); } }
package it.polimi.ingsw.GC_21.VIEW; import java.util.Scanner; import it.polimi.ingsw.GC_21.CLIENT.ChooseActionMessage; import it.polimi.ingsw.GC_21.PLAYER.FamilyMemberColor; public class PlacementInput extends ActionInput{ protected ActionInput actionInput; protected FamilyMemberColor familyMemberColor; protected int servantsToConvert; protected boolean blackPlayer; public PlacementInput(ActionInput actionInput, StringBuffer input, boolean blackPlayer) { this.actionInput = actionInput; this.input = input; this.blackPlayer = blackPlayer; } public PlacementInput() { // TODO Auto-generated constructor stub } public void execute(RemoteView remoteView) { int playerServant = remoteView.getPlayer().getMyPersonalBoard().getMyPossession().getServants().getValue(); if (playerServant == 0){ ChooseActionMessage retryActionMessage = new ChooseActionMessage(false, "You don't have servant to convert!", remoteView.getPlayer()); adapterConnection.sendObject(retryActionMessage); remoteView.inputObject(); } if (servantsToConvert > playerServant){ ChooseActionMessage retryActionMessage = new ChooseActionMessage(false, "You don't have enough servant to convert, try again!", remoteView.getPlayer()); adapterConnection.sendObject(retryActionMessage); remoteView.inputObject(); } } @Override public void inputFromCli() throws InterruptedException { familyMemberColor = this.chooseFamilyMember(actionInput); if (!blackPlayer) { servantsToConvert = this.chooseHowManyServants(actionInput); } } public int chooseHowManyServants(InputForm craftInput) throws InterruptedException{ System.out.println("How many servants do you want to convert?:"); String servantString = takeInput(craftInput); int servantsToConvert = Integer.parseInt(servantString); return servantsToConvert; } public FamilyMemberColor chooseFamilyMember(InputForm setFamilyMemberInput) throws InterruptedException{ System.out.println("Select Family Member [ N - O - W - B ]:"); String choice = takeInput(setFamilyMemberInput); switch (choice) { case "N": return FamilyMemberColor.Neutral; case "O": return FamilyMemberColor.Orange; case "W": return FamilyMemberColor.White; case "B": return FamilyMemberColor.Black; default: System.out.println("Invalid Family Member choice, try again!"); return this.chooseFamilyMember(setFamilyMemberInput); } } public FamilyMemberColor getFamilyMemberColor() { return familyMemberColor; } public void setFamilyMemberColor(FamilyMemberColor familyMemberColor) { this.familyMemberColor = familyMemberColor; } public int getServantsToConvert() { return servantsToConvert; } public void setServantsToConvert(int servantsToConvert) { this.servantsToConvert = servantsToConvert; } }
package bnorm.virtual; import bnorm.utils.Trig; public class VectorWave extends Wave implements IVectorWave { private IVector vector; public VectorWave(double x, double y, double velocity, double heading, long time) { super(x, y, velocity, time); this.vector = new Vector(0, 0, heading, velocity); } public VectorWave(double x, double y, double velocity, IPoint target, long time) { this(x, y, velocity, Trig.angle(x - target.getX(), y - target.getY()), time); } @Override public double getDeltaX() { return vector.getDeltaX(); } @Override public double getDeltaY() { return vector.getDeltaY(); } @Override public double getHeading() { return vector.getHeading(); } }
package com.hangarww.vaccination; import com.fasterxml.jackson.databind.ObjectMapper; import com.hangarww.vaccination.model.AadharCard; import com.hangarww.vaccination.model.VaccinatedPerson; import com.hangarww.vaccination.model.VaccinationCentre; import com.hangarww.vaccination.model.Vaccine; import com.hangarww.vaccination.model.VaccineAvailability; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.data.mongodb.core.MongoTemplate; import java.io.InputStream; import java.util.Arrays; import java.util.List; import static com.hangarww.vaccination.utility.MongoUtils.loadResource; @SpringBootApplication public class VaccinationApplication implements CommandLineRunner { @Autowired private MongoTemplate mongoTemplate; private static final String AADHAR_CARDS = "AadharCards"; private static final String VACCCINATED_PEOPLE = "VaccinatedPeople"; private static final String VACCINATION_CENTRES = "VaccinationCentres"; private static final String VACCINES = "Vaccines"; private static final String VACCINE_AVAILABILITIES = "VaccineAvailabilities"; public static void main(String[] args) { SpringApplication.run(VaccinationApplication.class, args); } @Override public void run(String... args) throws Exception { ObjectMapper mapper = new ObjectMapper(); InputStream in = getClass().getClassLoader().getResourceAsStream("imports" + "/aadhar_card.json"); List<AadharCard> aadharCardList = Arrays.asList(mapper.readValue(in, AadharCard[].class)); mongoTemplate.dropCollection(AADHAR_CARDS); mongoTemplate.createCollection(AADHAR_CARDS); mongoTemplate.insertAll(aadharCardList); in = getClass().getClassLoader().getResourceAsStream("imports" + "/vaccinated_person.json"); List<VaccinatedPerson> vaccinatedPersonList = Arrays.asList(mapper.readValue(in, VaccinatedPerson[].class)); mongoTemplate.dropCollection(VACCCINATED_PEOPLE); mongoTemplate.createCollection(VACCCINATED_PEOPLE); mongoTemplate.insertAll(vaccinatedPersonList); in = getClass().getClassLoader().getResourceAsStream("imports" + "/vaccination_centre.json"); List<VaccinationCentre> vaccinationCentreList = Arrays.asList(mapper.readValue(in, VaccinationCentre[].class)); mongoTemplate.dropCollection(VACCINATION_CENTRES); mongoTemplate.createCollection(VACCINATION_CENTRES); mongoTemplate.insertAll(vaccinationCentreList); in = getClass().getClassLoader().getResourceAsStream("imports" + "/vaccine.json"); List<Vaccine> vaccineList = Arrays.asList(mapper.readValue(in, Vaccine[].class)); mongoTemplate.dropCollection(VACCINES); mongoTemplate.createCollection(VACCINES); mongoTemplate.insertAll(vaccineList); in = getClass().getClassLoader().getResourceAsStream("imports" + "/vaccine_availability.json"); List<VaccineAvailability> vaccineAvailabilityList = Arrays.asList(mapper.readValue(in, VaccineAvailability[].class)); mongoTemplate.dropCollection(VACCINE_AVAILABILITIES); mongoTemplate.createCollection(VACCINE_AVAILABILITIES); mongoTemplate.insertAll(vaccineAvailabilityList); } }
package com.tencent.mm.g.a; import com.tencent.mm.sdk.b.b; public final class nz extends b { public a bYU; public b bYV; public nz() { this((byte) 0); } private nz(byte b) { this.bYU = new a(); this.bYV = new b(); this.sFm = false; this.bJX = null; } }
package com.zhouyi.business.controller; import com.zhouyi.business.core.model.LedenCollectLooks; import com.zhouyi.business.core.model.Response; import com.zhouyi.business.core.service.BaseService; import com.zhouyi.business.core.vo.LedenCollectLooksVo; import io.swagger.annotations.Api; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping(value = "/api/looks") @Api(value = "人像接口",hidden = true) public class LedenCollectLooksController { @Autowired private BaseService<LedenCollectLooks, LedenCollectLooksVo> baseService; @RequestMapping(value = "/get/{id}") public Response getDataById(@PathVariable(value = "id") String id){ return baseService.findDataById(id); } @RequestMapping(value = "/getlist") public Response getList(@RequestBody LedenCollectLooksVo ledenCollectLooksVo){ LedenCollectLooksVo ledenCollectLooksVo1 = ledenCollectLooksVo; if (ledenCollectLooksVo == null){ ledenCollectLooksVo1 = new LedenCollectLooksVo(); } return baseService.findDataList(ledenCollectLooksVo1); } @RequestMapping(value = "/save") public Response saveData(@RequestBody LedenCollectLooks ledenCollectLooks){ return baseService.saveData(ledenCollectLooks); } @RequestMapping(value = "/update") public Response updateData(@RequestBody LedenCollectLooks ledenCollectLooks){ return baseService.updateData(ledenCollectLooks); } @RequestMapping("/delete/{id}") public Response deleteData(@PathVariable(value = "id")String id){ return baseService.deleteData(id); } }
package com.basis.cg.xtarefas.domain; import lombok.Getter; import lombok.Setter; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import java.io.Serializable; import java.time.LocalDate; @Entity @Table(name = "TB_RESPONSAVEL") @Getter @Setter public class Responsavel implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String nome; private String email; @Column(name = "data_nascimento") private LocalDate dataNascimento; }
package org.alienideology.jcord.util; import org.alienideology.jcord.JCord; import org.alienideology.jcord.util.log.LogLevel; import org.apache.commons.codec.binary.StringUtils; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.Base64; /** * DataUtils - Utilities for I/O and data. * * @author AlienIdeology */ public class DataUtils { public static byte[] getBytesFromImage(String fileFormat, BufferedImage image) throws IOException { ByteArrayOutputStream byteoutput = new ByteArrayOutputStream(); ImageIO.write(image, fileFormat, byteoutput); return byteoutput.toByteArray(); } public static String encodeIcon(String fileFormat, BufferedImage image) throws IOException { return "data:image/" + fileFormat + ";base64, " + byteToString(getBytesFromImage(fileFormat, image)); } public static String byteToString(byte[] bytes) { return StringUtils.newStringUtf8(Base64.getEncoder().encode(bytes)); } public static String encodeToUrl(String toEncode) { try { return URLEncoder.encode(toEncode, "UTF-8"); } catch (UnsupportedEncodingException e) { JCord.LOG.log(LogLevel.FETAL, e); return toEncode; } } }
package gbernat.flashlight; import android.app.Application; import android.content.Context; import android.hardware.Camera; public class Utils extends Application { private static Context context; public static Camera cam; public static boolean isRunning; public void onCreate(){ super.onCreate(); Utils.context = getApplicationContext(); } public static Context getAppContext() { return Utils.context; } }
package com.vilio.nlbs.dynamicdatasource.service.impl; import com.vilio.nlbs.dynamicdatasource.CustomerContextHolder; import com.vilio.nlbs.dynamicdatasource.dao.BPSTestDao; import com.vilio.nlbs.dynamicdatasource.pojo.TestCity; import com.vilio.nlbs.dynamicdatasource.service.TestService; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.List; import java.util.Map; /** * Created by dell on 2017/5/22/0022. */ @Service public class TestServiceImpl implements TestService { @Resource BPSTestDao bpsTestDao; public Map testService() { return null; } }
package br.ufjf.dcc171; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.swing.JFrame; public class Trabalho1Lab3 { public static void main(String[] args) { Janela j = new Janela(getSampleData()); j.setSize(800, 350); j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); j.setLocationRelativeTo(null); j.setVisible(true); } private static List<Mesa> getSampleData() { Mesa mesa1 = new Mesa(1, "Mesa 1"); Mesa mesa2 = new Mesa(2, "Mesa 2"); Mesa mesa3 = new Mesa(3, "Mesa 3"); Mesa mesa4 = new Mesa(4, "Mesa 4"); List<Mesa> mesas = new ArrayList<>(); mesas.add(mesa1); mesas.add(mesa2); mesas.add(mesa3); mesas.add(mesa4); return mesas; } }
/** * Created by Nicu Osan on 29.03.2017. */ public class Problema3 { /*3. Se citesc numere naturale pânã când se introduce numãrul 0. Afisati suma obtinutã prin adunarea doar a numerelor mai mari decat 4 si mai mici decat 11.*/ public static void main(String[] args) { int numere = 0; int sum = 0; do { numere = SkeletonJava.readIntConsole("Intriduceti numarul "); boolean cond = ((numere > 4) && numere < 11); if (cond) { sum = numere + sum; } } while (numere != 0); System.out.println(sum); } }
package com.tencent.mm.plugin.webview.ui.tools.widget.input; public interface WebViewInputFooter$b { void aSX(); void aSY(); }
package oops; public class ExParameterizedConstructor { int stuId; String stuName; char gender; String color; ExParameterizedConstructor(int stuId,String stuName,char gender,String color){ this.stuId = stuId; this.stuName = stuName; this.gender = gender; this.color = color; } public static void main(String args[]) { ExParameterizedConstructor venkatesh = new ExParameterizedConstructor(10,"Venkatesh K",'M',"White"); System.out.println("Student Id is:" + venkatesh.stuId); System.out.println("Student name is:" + venkatesh.stuName); System.out.println("Student gender is:" + venkatesh.gender); System.out.println("Student color is:" + venkatesh.color); ExParameterizedConstructor mounika= new ExParameterizedConstructor(20,"Mounika",'F',"Pink"); System.out.println("Student Id is:" + mounika.stuId); System.out.println("Student name is:" + mounika.stuName); System.out.println("Student gender is:" + mounika.gender); System.out.println("Student color is:" + mounika.color); } }
package org.browsexml.timesheetjob.model; import java.util.Date; public class CheckPayPeriodItem { private String lastName; private String firstName; private String peopleId; private Date punched; private Job job; public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getPeopleId() { return peopleId; } public void setPeopleId(String peopleId) { this.peopleId = peopleId; } public Date getPunched() { return punched; } public void setPunched(Date date) { this.punched = date; } public Job getJob() { return job; } public void setJob(Job job) { this.job = job; } }
package org.motechproject.server.omod.web.model; import org.apache.velocity.app.VelocityEngine; import org.motechproject.server.model.MailTemplate; import org.springframework.ui.velocity.VelocityEngineUtils; import java.util.Map; public class SupportCaseMailTemplate implements MailTemplate { private VelocityEngine velocityEngine; private String template; private Map data; private String subjectTemplate; private String textTemplate; private static final String SPACE = " "; public SupportCaseMailTemplate(String subjectTemplate, String textTemplate) { this.subjectTemplate = subjectTemplate; this.textTemplate = textTemplate; } public void setVelocityEngine(VelocityEngine velocityEngine) { this.velocityEngine = velocityEngine; } public String subject(Map data) { return renderWith(subjectTemplate,data); } public String text(Map data) { return renderWith(textTemplate,data); } private String renderWith(String template, Map data) { return VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, template, data).trim(); } }