text stringlengths 10 2.72M |
|---|
package tests.testsUnidad;
import static org.junit.Assert.*;
import org.junit.*;
import agenda.modelo.Campo;
import agenda.modelo.Contacto;
/**
*
* @author Francisco Jesús Dominguez Ruíz
* @author Edgar Pérez Ferrando
*/
public class ContactoTests {
Contacto c;
@Before
public void init(){
c = new Contacto();
c.setValor(Campo.NOMBRE, "Antonio");
c.setValor(Campo.APELLIDO, "Paredes");
c.setValor(Campo.EMAIL, "tonyparedes@gmail.com");
c.setValor(Campo.TELEFONO, "639344708");
}
@Test
public void test1() {
c.setValor(Campo.NOMBRE, "Pepe");
assertEquals(c.getValor(Campo.NOMBRE), "Pepe");
}
@Test
public void test2() {
c.setValor(Campo.APELLIDO, "Gomez");
assertEquals(c.getValor(Campo.APELLIDO), "Gomez");
}
@Test
public void test3() {
c.setValor(Campo.EMAIL, "chiki@gmail.com");
assertEquals(c.getValor(Campo.EMAIL), "chiki@gmail.com");
}
@Test
public void test4() {
c.setValor(Campo.TELEFONO, "111111111");
assertEquals(c.getValor(Campo.TELEFONO), "111111111");
}
@Test
public void test5() {
assertEquals(0,c.compareTo(c));
}
@Test
public void test6() {
Contacto c2 = new Contacto();
c2.setValor(Campo.NOMBRE, "Antonio");
c2.setValor(Campo.APELLIDO, "Paredes");
c2.setValor(Campo.EMAIL, "tonyparedes@gmail.com");
c2.setValor(Campo.TELEFONO, "639344708");
assertEquals(0,c.compareTo(c2));
}
@Test (expected = NullPointerException.class)
public void test7() {
Contacto c2 = new Contacto();
c2.setValor(Campo.NOMBRE, "Antonio");
c2.setValor(Campo.APELLIDO, "Paredes");
c2.setValor(Campo.EMAIL, "tonyparedes@gmail.com");
c.compareTo(c2);
}
@Test
public void test8(){
assertEquals(c.toString(),"contacto(Antonio, Paredes, tonyparedes@gmail.com, 639344708)");
}
@Test
public void test9(){
Contacto c2 = new Contacto();
c2.setValor(Campo.APELLIDO, "Paredes");
c2.setValor(Campo.TELEFONO, "639344708");
assertEquals(c2.toString(),"contacto(null, Paredes, null, 639344708)");
}
@Test
public void test10(){
Contacto c2 = new Contacto();
c2.setValor(Campo.NOMBRE, "Antonio1");
c2.setValor(Campo.APELLIDO, "Paredes");
c2.setValor(Campo.EMAIL, "tonyparedes@gmail.com");
c2.setValor(Campo.TELEFONO, "639344708");
assertNotEquals(0,c2.toString());
}
@Test
public void test11(){
Contacto c2 = new Contacto();
c2.setValor(Campo.NOMBRE, "Antonio");
c2.setValor(Campo.APELLIDO, "Paredes1");
c2.setValor(Campo.EMAIL, "tonyparedes@gmail.com");
c2.setValor(Campo.TELEFONO, "639344708");
assertNotEquals(0,c2.toString());
}
@Test
public void test12(){
Contacto c2 = new Contacto();
c2.setValor(Campo.NOMBRE, "Antonio");
c2.setValor(Campo.APELLIDO, "Paredes");
c2.setValor(Campo.EMAIL, "tonyparedes1@gmail.com");
c2.setValor(Campo.TELEFONO, "639344708");
assertNotEquals(0,c2.toString());
}
@Test
public void test13(){
Contacto c2 = new Contacto();
c2.setValor(Campo.NOMBRE, "Antonio");
c2.setValor(Campo.APELLIDO, "Paredes");
c2.setValor(Campo.EMAIL, "tonyparedes@gmail.com");
c2.setValor(Campo.TELEFONO, "639344707");
assertNotEquals(0,c2.toString());
}
@Test
public void test14(){
Contacto c1 = new Contacto();
c1.setValor(Campo.NOMBRE, "Antonio");
c1.setValor(Campo.APELLIDO, "Paredes");
c1.setValor(Campo.EMAIL, "tonyparedes@gmail.com");
c1.setValor(Campo.TELEFONO, "639344707");
Contacto c2 = new Contacto();
c2.setValor(Campo.NOMBRE, "Antonio");
c2.setValor(Campo.APELLIDO, "Paredes");
c2.setValor(Campo.EMAIL, "tonyparedes@gmail.com");
c2.setValor(Campo.TELEFONO, "639344707");
assertEquals(c1.hashCode(), c2.hashCode());
}
@Test
public void test15(){
Contacto c1 = new Contacto();
c1.setValor(Campo.NOMBRE, "Antonio");
c1.setValor(Campo.APELLIDO, "Paredes");
c1.setValor(Campo.EMAIL, "tonyparedes@gmail.com");
c1.setValor(Campo.TELEFONO, "639344707");
Contacto c2 = new Contacto();
c2.setValor(Campo.NOMBRE, "Antonio");
c2.setValor(Campo.APELLIDO, "Paredes");
c2.setValor(Campo.EMAIL, "tonyparedes@gmail.com");
c2.setValor(Campo.TELEFONO, "154785");
assertNotEquals(c1.hashCode(), c2.hashCode());
}
@Test
public void test16(){
Contacto c1 = new Contacto();
c1.setValor(Campo.NOMBRE, "Antonio");
c1.setValor(Campo.APELLIDO, "Paredes");
c1.setValor(Campo.EMAIL, "tonyparedes@gmail.com");
c1.setValor(Campo.TELEFONO, "639344707");
Contacto c2 = new Contacto();
c2.setValor(Campo.NOMBRE, "Antonio");
c2.setValor(Campo.APELLIDO, "Paredes");
c2.setValor(Campo.EMAIL, "tonyparedes@gmail.com");
c2.setValor(Campo.TELEFONO, "154785");
assertFalse(c1.equals(c2));
}
@Test
public void test17(){
Contacto c1 = new Contacto();
c1.setValor(Campo.NOMBRE, "Antonio");
c1.setValor(Campo.APELLIDO, "Paredes");
c1.setValor(Campo.EMAIL, "tonyparedes@gmail.com");
c1.setValor(Campo.TELEFONO, "639344707");
Contacto c2 = new Contacto();
c2.setValor(Campo.NOMBRE, "Antonio");
c2.setValor(Campo.APELLIDO, "Paredes");
c2.setValor(Campo.EMAIL, "tonyparedes@gmail.com");
c2.setValor(Campo.TELEFONO, "639344707");
assertTrue(c1.equals(c2));
}
@Test(expected = Exception.class)
public void test18(){
Contacto c1 = new Contacto();
c1.setValor(null, "Antonio");
c1.setValor(Campo.APELLIDO, "Paredes");
c1.setValor(Campo.EMAIL, "tonyparedes@gmail.com");
c1.setValor(Campo.TELEFONO, "639344707");
}
}
|
package View.Alimentazione;
import Object.Enum.StatusEnum;
import javax.swing.*;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.HashMap;
/**
* La classe GiornoAlimForm contiene attributi e metodi associati al file XML GiornoAlimForm.form
*/
public class GiornoAlimForm {
private JPanel mainPanel;
private JButton addSpuntino;
private JButton removeSpuntino;
private JTable spuntiniEffTable;
private JButton addColazione;
private JButton removeColazione;
private JTable colazioneEffTable;
private JButton addCena;
private JButton removeCena;
private JTable cenaEffTable;
private JButton addPranzo;
private JButton removePranzo;
private JTable pranzoEffTable;
private JLabel Titlelabel;
private JButton confermaColazione;
private JButton confermaPranzo;
private JButton confermaCena;
private JButton confermaSpuntino;
private HashMap<ListSelectionModel, JButton> tabelle;
private HashMap<String, JTable> bottoni;
public GiornoAlimForm(String Title) {
Titlelabel.setText(Title);
String[] columnnames = {"Portata", "Alimento", "Quantita"};
DefaultTableModel tablemodel = new DefaultTableModel(columnnames, 0) {
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
colazioneEffTable.setModel(new DefaultTableModel(columnnames, 0) {
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
});
pranzoEffTable.setModel( new DefaultTableModel(columnnames, 0) {
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
});
cenaEffTable.setModel( new DefaultTableModel(columnnames, 0) {
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
});
spuntiniEffTable.setModel( new DefaultTableModel(columnnames, 0) {
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
});
}
public JPanel getMainPanel() {
return mainPanel;
}
/**
* Metodo che setta la visibilità dei bottoni per aggiungere una nuova portata nei pasti effettivi
*/
public void setButtonsVisible () {
addColazione.setVisible(true);
removeColazione.setVisible(true);
addPranzo.setVisible(true);
removePranzo.setVisible(true);
addCena.setVisible(true);
removeCena.setVisible(true);
addSpuntino.setVisible(true);
removeSpuntino.setVisible(true);
}
/**
* Metodo che mostra la visibilità dei componenti dell'interfaccia grafice in base allo status
* @param status Valore enumerativo di status su cui basare la visibilità
*/
public void enableConfermaButton(StatusEnum status){
if(status.equals(StatusEnum.colazione)) {
confermaColazione.setEnabled(true);
addPranzo.setEnabled(false);
addCena.setEnabled(false);
addSpuntino.setEnabled(false);
} else if(status.equals(StatusEnum.pranzo)) {
confermaColazione.setEnabled(false);
confermaPranzo.setEnabled(true);
colazioneEffTable.setEnabled(false);
addColazione.setEnabled(false);
addPranzo.setEnabled(true);
addCena.setEnabled(false);
addSpuntino.setEnabled(false);
} else if(status.equals(StatusEnum.spuntino)) {
confermaPranzo.setEnabled(false);
confermaSpuntino.setEnabled(true);
colazioneEffTable.setEnabled(false);
pranzoEffTable.setEnabled(false);
addColazione.setEnabled(false);
addPranzo.setEnabled(false);
addSpuntino.setEnabled(true);
addCena.setEnabled(false);
} else if(status.equals(StatusEnum.cena)) {
confermaSpuntino.setEnabled(false);
confermaCena.setEnabled(true);
colazioneEffTable.setEnabled(false);
pranzoEffTable.setEnabled(false);
spuntiniEffTable.setEnabled(false);
addColazione.setEnabled(false);
addPranzo.setEnabled(false);
addSpuntino.setEnabled(false);
addCena.setEnabled(true);
} else {
confermaCena.setEnabled(false);
colazioneEffTable.setEnabled(false);
pranzoEffTable.setEnabled(false);
spuntiniEffTable.setEnabled(false);
cenaEffTable.setEnabled(false);
addColazione.setEnabled(false);
addPranzo.setEnabled(false);
addSpuntino.setEnabled(false);
addCena.setEnabled(false);
}
}
/**
* Metodo che setta la visibilità del bottone conferma e i bottoni di aggiunta di una portata
* @param comb Variabile booleana che indica se il programma alimentare è combinato
* @param status Valore enumerativo di status su cui basare la visibilità
*/
public void visibilityConfermaAndAddButtons(boolean comb, StatusEnum status){
confermaColazione.setVisible(comb);
confermaPranzo.setVisible(comb);
confermaSpuntino.setVisible(comb);
confermaCena.setVisible(comb);
if(comb) {
enableConfermaButton(status);
}
else{
addColazione.setEnabled(true);
addPranzo.setEnabled(true);
addSpuntino.setEnabled(true);
addCena.setEnabled(true);
}
}
/**
* Metodo che aggiunge le tabelle dei pasti effettivi ad un arrylist di JTable
* @return Un ArrayList di Jtable
*/
public ArrayList<JTable> getEffTables () {
ArrayList<JTable> listatabelle = new ArrayList<JTable>(4);
listatabelle.add(0, colazioneEffTable);
listatabelle.add(1, pranzoEffTable);
listatabelle.add(2, spuntiniEffTable);
listatabelle.add(3, cenaEffTable);
return listatabelle;
}
/**
* Metodo che riepie un HashMap con dei componenti la cui la chiave è il model della tabella ed il valore è il bottone di di rimuovi
*/
public void setButtonFromTable(){
this.tabelle = new HashMap<ListSelectionModel, JButton>();
tabelle.put(colazioneEffTable.getSelectionModel(), removeColazione);
tabelle.put(pranzoEffTable.getSelectionModel(), removePranzo);
tabelle.put(cenaEffTable.getSelectionModel(), removeCena);
tabelle.put(spuntiniEffTable.getSelectionModel(), removeSpuntino);
}
/**
* Ottiene il valore di un componente dell'HasHMap in base alla chiave
* @param tablemodel Variabile di tipo ListSelectionModel
* @return Il bottone rimuovi della tabella ottenuta
*/
public JButton getButtonFromTable(ListSelectionModel tablemodel){
return tabelle.get(tablemodel);
}
/**
* Metodo che riepie un HashMap con dei componenti la cui la chiave è l'action command del bottone ed il valore è una tabella
*/
public void setTableFromButton(){
this.bottoni = new HashMap<String, JTable>();
bottoni.put(removeColazione.getActionCommand(), colazioneEffTable);
bottoni.put(removePranzo.getActionCommand(), pranzoEffTable);
bottoni.put(removeCena.getActionCommand(), cenaEffTable);
bottoni.put(removeSpuntino.getActionCommand(), spuntiniEffTable);
}
/**
* Ottiene il valore di un componente dell'HasHMap in base alla chiave
* @param nomebottone Stringa del bottone
* @return Tabella selezionata
*/
public JTable getTableFromButton(String nomebottone){
return bottoni.get(nomebottone);
}
/** Listener associati ad elementi di cui è composto il file XML GiornoAlimForm.form */
public void addListenersAndShowButtons(ActionListener listener) {
addColazione.addActionListener(listener);
addPranzo.addActionListener(listener);
addCena.addActionListener(listener);
addSpuntino.addActionListener(listener);
setButtonsVisible();
}
public void addListenersForRemoveButtons(ActionListener listener){
removeColazione.addActionListener(listener);
removePranzo.addActionListener(listener);
removeCena.addActionListener(listener);
removeSpuntino.addActionListener(listener);
}
public void addListenersConfermaButton(ActionListener listener){ // Funzione che aggiunge i listener ai bottini di Conferma e li rende visibili
confermaColazione.addActionListener(listener);
confermaPranzo.addActionListener(listener);
confermaCena.addActionListener(listener);
confermaSpuntino.addActionListener(listener);
}
public void addTableSelectionListener(ListSelectionListener listener) {
colazioneEffTable.getSelectionModel().addListSelectionListener(listener);
pranzoEffTable.getSelectionModel().addListSelectionListener(listener);
cenaEffTable.getSelectionModel().addListSelectionListener(listener);
spuntiniEffTable.getSelectionModel().addListSelectionListener(listener);
}
}
|
package com.edu.realestate.services;
import java.util.List;
import java.util.Map;
import com.edu.realestate.exceptions.RealEstateException;
import com.edu.realestate.model.AdStatus;
import com.edu.realestate.model.Advertisement;
import com.edu.realestate.model.AdvertisementModel;
import com.edu.realestate.model.City;
import com.edu.realestate.model.Picture;
import com.edu.realestate.yelp.YelpResult;
public interface AdvertisementService {
Advertisement findAdvertisementById(int id) throws RealEstateException;
Advertisement findAdvertisementByNumber(String adNumber) throws RealEstateException;
List<Advertisement> findAdvertisementByCity(int cityId) throws RealEstateException;
Advertisement createAdFromModel(AdvertisementModel am) throws RealEstateException;
void placeAdvertisement(Advertisement ad) throws RealEstateException;
Picture findPictureById(int id) throws RealEstateException;
List<Picture> findPicturesByAdId(int aid) throws RealEstateException;
List<Advertisement> findLatestAds(int number) throws RealEstateException;
void validateAdvertisement(int adId) throws RealEstateException;
void refuseAdvertisement(int adId, String refusedComment) throws RealEstateException;
List<Advertisement> findAdvertisementsByStatus(AdStatus status) throws RealEstateException;
YelpResult findYelpData(City city) throws Exception;
Map<String, Long> getAdvertisementsData() throws RealEstateException;
public List<String> findAdNumbers(String input, boolean exact) throws RealEstateException;
}
|
package test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
public class DeleteTest {
public static void main(String[] args) {
String classname="com.mysql.jdbc.Driver";
Connection conn=null;
String url="jdbc:mysql://localhost:3306/t1";
String user="hong";
String password="123";
Statement stmt=null;
PreparedStatement pstmt=null;
try {
Class.forName(classname);
conn=DriverManager.getConnection(url, user, password);
conn.setAutoCommit(false);
StringBuilder sql=new StringBuilder();
sql.append("delete ");
sql.append("from member ");
sql.append("where mid=? ");
pstmt=conn.prepareStatement(sql.toString());
pstmt.setString(1, "a1");
int r=pstmt.executeUpdate();
System.out.println(r+" »èÁ¦ ¿Ï·á");
conn.commit();
} catch (ClassNotFoundException e) {
System.out.println(e);
}catch(SQLException e){
System.out.println(e);
}finally{
if(pstmt!=null)try{pstmt.close();}catch(SQLException e){System.out.println(e);
if(conn!=null)try{conn.close();}catch(SQLException e1){System.out.println(e1);};
}
}
}
}
|
/*
* 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 Controller;
import Controller.HibernateUtil;
import Model.MediaLog;
import Model.Medium;
import java.math.BigDecimal;
import Controller.JSONclass;
import Model.User;
import java.io.IOException;
import java.util.List;
import java.util.Date;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class MediaLog_controller {
private static SessionFactory factory;
private static JSONclass json = new JSONclass();
public Boolean addLog(User user, Medium medium, String item, Double rating, Double timeSpent, Date dateFinished){
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction tx = null;
Integer logID = null;
try{
// tx = session.beginTransaction();
// MediaLog mediaLog = new MediaLog(user, medium, item, rating, timeSpent, dateFinished);
// logID = (Integer) session.save(mediaLog);
// tx.commit();
// try {
// json.AddItemJSON();
// } catch (IOException ex) {
// Logger.getLogger(Item_controller.class.getName()).log(Level.SEVERE, null, ex);
// }
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
return true;
}
public void listLog( ){
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
List logs = session.createQuery("FROM MediaLog").list();
for (Iterator iterator =
logs.iterator(); iterator.hasNext();){
MediaLog mediaLog = (MediaLog) iterator.next();
// System.out.println("Medium: " + mediaLog.getMedium().getTypeMedium());
// System.out.println("Title: " + mediaLog.getItem());
System.out.println("Rating: " + mediaLog.getRating());
System.out.println("Time: " + mediaLog.getTimeSpent());
System.out.println("Date Finished: " + mediaLog.getDateFinished());
}
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}
// public List<Item> getItems()
// {
// Item item = new Item();
// List<Item> list = item.items();
// return list;
// }
public Boolean updateLog(int logId, User user, Medium medium, String item, Double rating, Double timeSpent, Date dateFinished){
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
MediaLog mediaLog =
(MediaLog)session.get(MediaLog.class, logId);
// mediaLog.setUser(user);
// mediaLog.setMedium(medium);
// mediaLog.setItem(item);
// mediaLog.setRating(rating);
// mediaLog.setTimeSpent(timeSpent);
mediaLog.setDateFinished(dateFinished);
session.update(mediaLog);
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
return true;
}
public Boolean deleteLog(Integer logId){
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
MediaLog mediaLog =
(MediaLog)session.get(MediaLog.class, logId);
session.delete(mediaLog);
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
return true;
}
}
|
package com.dbTest;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DbConnection {
public static void main(String[] args) throws SQLException {
String url = "jdbc:mysql://localhost/testdb";
Connection connection = DriverManager.getConnection(url,"root","root");
Statement statement = connection.createStatement();
System.out.println("Successfully connected to the database: "+statement);
ResultSet resultSet = statement.executeQuery("Select * from student");
while(resultSet.next()) {
System.out.println(resultSet.getString("name")+ " " + resultSet.getInt("marks"));
}
}
}
|
package com.swjt.xingzishop.Sercurity;
import org.springframework.security.authentication.AuthenticationDetailsSource;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
/**
* branches
* 自定义
*
* @author : wpf
* @date : 2020-10-29 20:58
**/
@Component
public class MyWebAuthenticationDetailsSource implements AuthenticationDetailsSource<HttpServletRequest, WebAuthenticationDetails> {
@Override
public WebAuthenticationDetails buildDetails(HttpServletRequest context) {
return new MyWebAuthenticationDetails(context);
}
}
|
package cn.tedu.reivew;
//面向对象综合测试
public class TestOOP {
public static void main(String[] args) {
Pigeon p=new Pigeon();
p.fly();
p.eggnumber=6;
p.layEggs();
Swallow s=new Swallow();
s.fly();
s.eggnumber=8;
s.layEggs();
s.makehome();
Ant a=new Ant();
a.fly();
a.eggnumber=300;
a.spawn();
Bee b=new Bee();
b.fly();
b.eggnumber=200;
b.spawn();
b.honey();
}
}
interface FlyAnimal{
void fly();
}
abstract class Bird{
int legnumber=2;
int eggnumber;
public abstract void layEggs();
}
abstract class Insect{
int legnumber=6;
int eggnumber;
public abstract void spawn();
}
class Pigeon extends Bird implements FlyAnimal{
@Override
public void fly() {
System.out.println("鸽子飞走了");
}
@Override
public void layEggs() {
System.out.println("鸽子下蛋的数量:"+eggnumber);
}
}
class Swallow extends Bird implements FlyAnimal{
@Override
public void fly() {
System.out.println("小燕子飞走了");
}
@Override
public void layEggs() {
System.out.println("小燕子下蛋数量:"+eggnumber);
}
public void makehome(){
System.out.println("小燕子会用口水搭窝");
}
}
class Ant extends Insect implements FlyAnimal{
@Override
public void fly() {
System.out.println("蚂蚁会飞你相信吗?");
}
@Override
public void spawn() {
System.out.println("蚂蚁产卵数:"+eggnumber);
}
}
class Bee extends Insect implements FlyAnimal{
@Override
public void fly() {
System.out.println("蜜蜂到处飞去 采蜜");
}
@Override
public void spawn() {
System.out.println("蜜蜂产卵数:"+eggnumber);
}
public void honey(){
System.out.println("一只成年蜜蜂一年可以产蜜100吨");
}
} |
package Usermenu;
import Admin.*;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;
public class BookCheckout extends javax.swing.JFrame {
Connection con; Statement s;
String id=User.userID;
String bid;
private javax.swing.JComboBox branchcom;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JLabel jLabel1;
private javax.swing.JList jList1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JSeparator jSeparator1;
public BookCheckout() {
init();
connectsql();
}
private void connectsql() {
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/libdb", "root","Albert1792");
s = con.createStatement();
System.out.println("Connected to db");
}catch(Exception e){
System.err.println("ERROR: "+e);
}
}
private void init() {
jLabel1 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
branchcom = new javax.swing.JComboBox();
jSeparator1 = new javax.swing.JSeparator();
jScrollPane1 = new javax.swing.JScrollPane();
jList1 = new javax.swing.JList();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("BOOK");
jButton1.setText("SEARCH");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
branchcom.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Miller, Downtown", "Domino, Mid West", "Grease, Upper East", "Helmet, Upper West", "Circle, Midtown", "Ted's, Gramercy", "Kramer, Kips Bay", "Joyce, Murray Hill", "Gyoza, Chinatown", "Kimchi, KTown", "Wall, Financial District", "Battery, Battery Park", "Shake, Harlem", "Eataly, East Willage", "Lobster Tail, Chelsea", "Dumbo, Brooklyn", "Park Slope, Brooklyn", "Sunny, Queens", "Wood, Queens", "Island, Roosevelt", "Brooklyn College, Brooklyn" }));
jScrollPane1.setViewportView(jList1);
jButton2.setText("CHECKOUT");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jButton3.setText("<< BACK");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane1)
.addComponent(jSeparator1)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 183, Short.MAX_VALUE)
.addComponent(branchcom, javax.swing.GroupLayout.PREFERRED_SIZE, 172, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(23, 23, 23))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(21, 21, 21)
.addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(23, 23, 23)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGap(6, 6, 6)
.addComponent(branchcom, javax.swing.GroupLayout.DEFAULT_SIZE, 33, Short.MAX_VALUE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 11, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 343, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 17, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton2)
.addComponent(jButton3))
.addContainerGap())
);
pack();
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
try {
List<String> books = new ArrayList();
DefaultListModel dl = new DefaultListModel();
jList1.setModel(dl);
String s = branchcom.getSelectedItem().toString();
s = s.substring(0,s.indexOf(","));
String query = "Select * from branch where name ='"+s+"'";
ResultSet res = this.con.createStatement().executeQuery(query);
while(res.next()){
this.bid = res.getString("branchid");
String q1 = "Select * from location where branchid = '"+this.bid+"'";
ResultSet r1 = this.con.createStatement().executeQuery(q1);
while(r1.next()){
System.out.println(r1.getString("bookid"));
books.add(r1.getString("bookid"));
}r1.close();
}res.close();
List<String> books2 = new ArrayList();
for(String bo:books){
String q2 = "Select * from borrow where bookid = '"+bo+"'";
ResultSet r3 = this.con.createStatement().executeQuery(q2);
while(r3.next()){
if(r3.getString("rdate") == null){
books2.add(bo);
}
}
}
for(String bo:books){
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
java.util.Date date = new java.util.Date();
String da = dateFormat.format(date);
String q2 = "Select * from reserve where bookid = '"+bo+"'";
ResultSet r3 = this.con.createStatement().executeQuery(q2);
while(r3.next()){
if( !r3.getString("date").equals(da) ){
books2.add(bo);
}
}
}
books.removeAll(books2);
for(String bf : books){
System.out.println(books);
}
if(books.size() == 0){
dispose();
JOptionPane op = new JOptionPane();
op.setMessage("There are no available books at this time in that branch");
op.setMessageType(0);
JDialog dia = op.createDialog(null,"Error");
dia.setTitle("OOPS");
dia.setVisible(true);
}else{
List<String> names = new ArrayList();
for(String b: books){
String q5 = "Select * from book where bookid='"+b+"'";
ResultSet r5 = this.con.createStatement().executeQuery(q5);
while(r5.next()){
String q6 = "Select * from bookinfo where isbn='"+r5.getString("isbn")+"'";
ResultSet r6 = this.con.createStatement().executeQuery(q6);
while (r6.next()){
names.add(r6.getString("title"));
}r6.close();
}r5.close();
}
for(int i = 0 ; i<names.size() ; i++){
dl.addElement("ID: "+books.get(i)+" TITLE: "+names.get(i));
}
}
} catch (SQLException ex) {
Logger.getLogger(BookReserve.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
try {
System.out.println(id);
String book = jList1.getSelectedValue().toString();
book = book.substring(book.indexOf(':')+2,book.indexOf('T')-1);
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
java.util.Date date = new java.util.Date();
String da = dateFormat.format(date);
String query = " insert into borrow (bookid, readerid, branchid, bdate)"
+ " values (?, ?, ?, ? )";
PreparedStatement preparedStatement = this.con.prepareStatement(query);
preparedStatement.setString(1, book);
preparedStatement.setString(2, User.userID);
preparedStatement.setString(3, bid);
preparedStatement.setString(4, da);
preparedStatement.execute();
JOptionPane op = new JOptionPane();
op.setMessage("Thank you for borrowing a book ");
op.setMessageType(1);
JDialog dia = op.createDialog(null,"Info");
dia.setTitle("INFO");
dia.setVisible(true);
dispose();
} catch (SQLException ex) {
Logger.getLogger(BookCheckout.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
dispose();
UserMenu uMenu = new UserMenu();
uMenu.setVisible(true);
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new BookCheckout().setVisible(true);
}
});
}
} |
package org.valar.project.contactsApplication.dao;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcDaoSupport;
// This will not work independently so don't put inside IOC container using
// @Repository @Service @Component
abstract public class BaseDAO extends NamedParameterJdbcDaoSupport {
@Autowired
public void setDataSourceObj(DataSource ds) {
super.setDataSource(ds);
}
}
|
package com.synchrony.album.controller;
import javax.websocket.server.PathParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.synchrony.album.model.User;
import com.synchrony.album.service.UserService;
import com.synchrony.album.vo.AlbumResponse;
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@PostMapping("/register")
public ResponseEntity<?> register(@RequestBody User user) {
userService.saveUser(user);
return ResponseEntity.status(HttpStatus.CREATED).body(new AlbumResponse("MSG001","Successfully register the user"));
}
@GetMapping("{userId}")
public ResponseEntity<?> getUser(@PathParam("userId") Long userId) {
User user = userService.getUser(userId);
if(user == null) {
return ResponseEntity.ok(new AlbumResponse("MSG002","User does not exist"));
}
return ResponseEntity.ok(userService.getUser(userId));
}
}
|
package com.rednovo.ace.widget.live;
import android.app.Activity;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.facebook.drawee.generic.GenericDraweeHierarchy;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.request.ImageRequest;
import com.rednovo.ace.R;
import com.rednovo.ace.core.session.SessionEngine;
import com.rednovo.ace.data.UserInfoUtils;
import com.rednovo.ace.data.events.LiveEndEvent;
import com.rednovo.ace.net.parser.UserInfoResult;
import com.rednovo.libs.BaseApplication;
import com.rednovo.libs.common.DateUtils;
import com.rednovo.libs.net.fresco.FrescoEngine;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;
/**
* Created by lizhen on 16/3/15.
*/
public class CloseLiveView extends RelativeLayout implements View.OnClickListener {
private TextView tvNickName;
private TextView tvMoney;
private TextView tvFans;
private TextView tvAudience;
private TextView tvLiveTime;
private TextView tvPraise;
private SimpleDraweeView simpleDraweeView;
private int drawable;
public CloseLiveView(Context context) {
super(context);
initView(context);
}
public CloseLiveView(Context context, AttributeSet attrs) {
super(context, attrs);
initView(context);
}
public CloseLiveView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initView(context);
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
UserInfoResult.UserEntity user = UserInfoUtils.getUserInfo();
drawable = R.drawable.head_offline;
Context cxt = BaseApplication.getApplication().getApplicationContext();
((GenericDraweeHierarchy) simpleDraweeView.getHierarchy()).setFailureImage(cxt.getResources().getDrawable(drawable));
FrescoEngine.setSimpleDraweeView(simpleDraweeView, user.getProfile(), ImageRequest.ImageType.SMALL);
}
@Subscribe(threadMode = ThreadMode.MainThread)
public void onRecvLiveEndEvent(LiveEndEvent liveEndEvent) {
if(UserInfoUtils.isAlreadyLogin()){
//接到账号封停后,用户已经被退出登录
String nickName = UserInfoUtils.getUserInfo().getNickName();
tvNickName.setText(nickName);
int coinsLenght = liveEndEvent.conins.length();
if (coinsLenght > 5) {
tvMoney.setTextSize(28);
} else if (coinsLenght > 8) {
tvMoney.setTextSize(24);
} else {
tvMoney.setTextSize(36);
}
tvMoney.setText(liveEndEvent.conins);
tvFans.setText(liveEndEvent.fans);
String coverTime = null;
try {
coverTime = DateUtils.converTime(Integer.parseInt(liveEndEvent.length));
} catch (NumberFormatException e) {
e.printStackTrace();
}
tvLiveTime.setText(coverTime);
tvAudience.setText(liveEndEvent.memberCnt);
tvPraise.setText(liveEndEvent.support);
}
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
EventBus.getDefault().register(this);
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
EventBus.getDefault().unregister(this);
drawable = 0;
}
protected void initView(Context mContext) {
inflate(mContext, R.layout.activity_live_close, this);
tvNickName = (TextView) findViewById(R.id.tv_nickName);
tvMoney = (TextView) findViewById(R.id.tv_money);
tvFans = (TextView) findViewById(R.id.tv_fans);
tvAudience = (TextView) findViewById(R.id.tv_audience);
tvLiveTime = (TextView) findViewById(R.id.tv_live_time);
tvPraise = (TextView) findViewById(R.id.tv_praise);
simpleDraweeView = (SimpleDraweeView) findViewById(R.id.iv_anchor);
findViewById(R.id.tv_sure).setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.tv_sure:
new Thread(new Runnable() {
@Override
public void run() {
SessionEngine.getSessionEngine().close();
}
}).start();
((Activity) getContext()).finish();
break;
default:
break;
}
}
public boolean isVisible() {
if (getVisibility() == View.VISIBLE)
return true;
else
return false;
}
public void setVisible(boolean isEndView) {
if (isEndView) {
this.setVisibility(View.VISIBLE);
}else{
this.setVisibility(View.GONE);
}
}
}
|
/**
* Sencha GXT 3.0.1 - Sencha for GWT
* Copyright(c) 2007-2012, Sencha, Inc.
* licensing@sencha.com
*
* http://www.sencha.com/products/gxt/license/
*/
package com.sencha.gxt.examples.resources.client;
import com.google.gwt.i18n.client.NumberFormat;
import com.sencha.gxt.core.client.ValueProvider;
import com.sencha.gxt.examples.resources.client.model.Data;
import com.sencha.gxt.widget.core.client.form.NumberPropertyEditor;
import com.sencha.gxt.widget.core.client.grid.filters.NumericFilter;
public class FormattedNumericFilter extends NumericFilter<Data, Double> {
NumberFormat formatter;
public FormattedNumericFilter(ValueProvider<? super Data, Double> valueProvider,
NumberPropertyEditor<Double> propertyEditor, String format) {
super(valueProvider, propertyEditor);
formatter = NumberFormat.getFormat(format);
}
protected boolean equals(Double a, Double b) {
return formatter.format(a).equals(formatter.format(b));
}
}
|
package cc.aies.web.service;
import cc.aies.web.beans.Dictionary;
import cc.aies.web.beans.DictionaryExample;
import cc.aies.web.dao.DictionaryMapper;
import cc.aies.web.utils.CommonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by Intellij IDEA.
*
* @author: 霍运浩
* @date: 2018-09-23
* @time: 23:13
*/
@Service
public class DictionaryService {
@Autowired
DictionaryMapper dictionaryMapper;
public void addDic(Dictionary dictionary) {
dictionary.setDictionaryId(CommonUtils.getUUID());
dictionaryMapper.insertSelective(dictionary);
}
public void updateDic(Dictionary dictionary) {
dictionaryMapper.updateByPrimaryKeySelective(dictionary);
}
public Dictionary getDic(String id) {
return dictionaryMapper.selectByPrimaryKey(id);
}
//查询所有父类的dic
public List<Dictionary> getDicPa() {
DictionaryExample dictionaryExample=new DictionaryExample();
DictionaryExample.Criteria criteria=dictionaryExample.createCriteria();
criteria.andParentIdEqualTo("");
return dictionaryMapper.selectByExample(dictionaryExample);
}
public List<Dictionary> getSonPa(String id) {
DictionaryExample dictionaryExample=new DictionaryExample();
DictionaryExample.Criteria criteria=dictionaryExample.createCriteria();
criteria.andParentIdEqualTo(id);
return dictionaryMapper.selectByExample(dictionaryExample);
}
/**
* 获取所有字典
* @return
*/
public List<Dictionary> getAllDic(){
return dictionaryMapper.selectByExample(null);
}
public List<Dictionary> getTreeDic() {
List<Dictionary> dictionaryList=this.getAllDic();
return this.makeTreeDic(dictionaryList);
//获取所有字典
//
}
public List<Dictionary> makeTreeDic(List<Dictionary> dictionaryList){
Map<String,Dictionary> stringDictionaryMap=new HashMap<>(dictionaryList.size());
// //获取父字典
List<Dictionary> dictionaryParentList=new ArrayList<>();
for(Dictionary dictionary:dictionaryList){
stringDictionaryMap.put(dictionary.getDictionaryId(),dictionary);
if(dictionary.getParentId()==null || dictionary.getParentId().trim().isEmpty())
{
dictionaryParentList.add(dictionary);
}
}
for(Dictionary dictionary:dictionaryList){
if(dictionary.getParentId()!="" || !dictionary.getParentId().trim().isEmpty()){
Dictionary parent=stringDictionaryMap.get(dictionary.getParentId());
if(parent!=null)
{
parent.getChildrenList().add(dictionary);
}
}
}
return dictionaryParentList;
}
/**
* 查询出改字典所有的子字典
*/
List<Dictionary> dictionaryDeList=new ArrayList<>();
private void selectAllSonPa(String id){
Dictionary dictionary=dictionaryMapper.selectByPrimaryKey(id);
dictionaryDeList.add(dictionary);
//查询这个字典的子字典
DictionaryExample example=new DictionaryExample();
DictionaryExample.Criteria criteria=example.createCriteria();
criteria.andParentIdEqualTo(dictionary.getDictionaryId());
List<Dictionary> dictionaryList=dictionaryMapper.selectByExample(example);
for(Dictionary dictionary1:dictionaryList){
selectAllSonPa(dictionary1.getDictionaryId());
}
}
//删除字典
public void deleteDic(String id) {
selectAllSonPa(id);
for(Dictionary dictionary:dictionaryDeList){
dictionaryMapper.deleteByPrimaryKey(dictionary.getDictionaryId());
}
System.out.println(dictionaryDeList);
}
//通过字典的Code 获取字典名字
public String getDicNameByCode(String code){
DictionaryExample dictionaryExample=new DictionaryExample();
DictionaryExample.Criteria criteria=dictionaryExample.createCriteria();
criteria.andDicValueEqualTo(code);
List<Dictionary> dicList=dictionaryMapper.selectByExample(dictionaryExample);
String Name=null;
for(Dictionary dictionary:dicList){
Name=dictionary.getDicValue();
break;
}
return Name;
}
}
|
/*
* GuestBookDaoImplJDBC.java
*
* Created on 2007Äê1ÔÂ19ÈÕ, ÏÂÎç10:51
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package tot.dao.jdbc;
import tot.dao.AbstractDao;
import tot.db.DBUtils;
import tot.bean.*;
import tot.exception.ObjectNotFoundException;
import tot.exception.DatabaseException;
import java.sql.*;
import java.util.*;
import java.io.StringReader;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
*
* @author totcms
*/
public class GuestbookDaoImplJDBC extends AbstractDao{
private static Log log = LogFactory.getLog(GuestbookDaoImplJDBC.class);
/** Creates a new instance of GuestBookDaoImplJDBC */
public GuestbookDaoImplJDBC() {
}
/** add GuestBook */
public boolean addGuestBook(int objid,int typeid,String author,String content,String ip,Timestamp moditime){
Connection conn = null;
PreparedStatement ps = null;
boolean returnValue=true;
String sql="insert into t_gbook(ObjId,TypeId,Author,Content,Ip,ModiTime) values(?,?,?,?,?,?)";
try{
conn = DBUtils.getConnection();
ps=conn.prepareStatement(sql);
ps.setInt(1,objid);
ps.setInt(2,typeid);
ps.setString(3,author);
if(DBUtils.getDatabaseType()==DBUtils.DATABASE_ORACLE){
ps.setCharacterStream(4, new StringReader(content), content.length());
}else{
ps.setString(4,content);
}
ps.setString(5,ip);
ps.setTimestamp(6,moditime);
if(ps.executeUpdate()!=1) returnValue=false;
} catch(SQLException e){
log.error("add GuestBook error",e);
} finally{
DBUtils.closePrepareStatement(ps);
DBUtils.closeConnection(conn);
}
return returnValue;
}
/*
* mod GuestBook
*/
public boolean modGuestBook(int id,String author,String content){
Connection conn = null;
PreparedStatement ps = null;
boolean returnValue=true;
String sql="update t_gbook set author=?,Content=? where id=?";
try{
conn = DBUtils.getConnection();
ps=conn.prepareStatement(sql);
ps.setString(1,author);
if(DBUtils.getDatabaseType()==DBUtils.DATABASE_ORACLE){
ps.setCharacterStream(2, new StringReader(content), content.length());
}else{
ps.setString(2,content);
}
ps.setInt(3,id);
if(ps.executeUpdate()!=1) returnValue=false;
} catch(SQLException e){
log.error("mod GuestBook error",e);
} finally{
DBUtils.closePrepareStatement(ps);
DBUtils.closeConnection(conn);
}
return returnValue;
}
public DataField getGuestBook(int id){
return getFirstData("select id,ObjId,TypeId,Author,Content,Ip,ModiTime from t_gbook where id="+id,"id,ObjId,TypeId,Author,Content,Ip,ModiTime");
}
public boolean delGuestBook(int id) throws ObjectNotFoundException,DatabaseException{
return exe("delete from t_gbook where id="+id);
}
public void batDel(String[] s){
this.bat("delete from t_gbook where id=?",s);
}
public Collection getGuestBookListByObj_Limit(int objid,int typeid,int currentpage,int pagesize){
if(DBUtils.getDatabaseType() == DBUtils.DATABASE_MYSQL){
StringBuffer sql=new StringBuffer(512);
sql.append("select id,Author,Content,Ip,ModiTime from t_gbook where 1=1");
if(objid>0) sql.append(" and ObjId="+objid);
if(typeid>0) sql.append(" and TypeId="+typeid);
return getDataList_mysqlLimit(sql.toString(),"id,Author,Content,Ip,ModiTime",pagesize,(currentpage-1)*pagesize);
} else if (DBUtils.getDatabaseType() == DBUtils.DATABASE_SQLSERVER) {
StringBuffer sql=new StringBuffer(512);
sql.append("SELECT TOP ");
sql.append(pagesize);
sql.append(" id,Author,Content,Ip,ModiTime FROM t_gbook WHERE (id <=(SELECT MIN(id) FROM (SELECT TOP ");
sql.append((currentpage-1)*pagesize+1);
sql.append(" id FROM t_gbook where 1=1");
if(objid>0) sql.append(" and ObjId="+objid);
if(typeid>0) sql.append(" and TypeId="+typeid);
sql.append(" ORDER BY id DESC) AS t))");
if(objid>0) sql.append(" and ObjId="+objid);
if(typeid>0) sql.append(" and TypeId="+typeid);
sql.append(" ORDER BY id DESC");
return getData(sql.toString(),"id,Author,Content,Ip,ModiTime");
} else{
StringBuffer sql=new StringBuffer(512);
sql.append("select id,Author,Content,Ip,ModiTime from t_gbook where 1=1");
if(objid>0) sql.append(" and ObjId="+objid);
if(typeid>0) sql.append(" and TypeId="+typeid);
return getDataList_Limit_Normal(sql.toString(),"id,Author,Content,Ip,ModiTime",pagesize,(currentpage-1)*pagesize);
}
}
public int getTotalCount(int objid,int typeid){
StringBuffer sql=new StringBuffer(512);
sql.append("select count(*) from t_gbook where 1=1");
if(objid>0){
sql.append(" and ObjId=");
sql.append(objid);
}
if(typeid>0){
sql.append(" and TypeId=");
sql.append(typeid);
}
return(this.getDataCount(sql.toString()));
}
}
|
package xdroid.core;
/**
* Alternative to {@link Runnable}.
*
* @author Oleksii Kropachov (o.kropachov@shamanland.com)
*/
public interface Invokable {
Object invoke(Object... args);
}
|
package io.ceph.rgw.client.config;
import io.ceph.rgw.client.exception.RGWException;
import io.ceph.rgw.client.util.AddressUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.*;
import java.util.stream.Collectors;
/**
* Properties for {@link io.ceph.rgw.client.Clients}.
*
* @author zhuangshuo
* Created by zhuangshuo on 2020/2/27.
*/
public class RGWClientProperties {
private static final Logger LOGGER = LoggerFactory.getLogger(RGWClientProperties.class);
private static final String PREFIX = "rgwclient.";
private static final String APPLICATION_NAME = PREFIX + "application.name";
private static final String ENABLE_ADMIN = PREFIX + "enableAdmin";
private static final String ENABLE_BUCKET = PREFIX + "enableBucket";
private static final String ENABLE_OBJECT = PREFIX + "enableObject";
private static final String CONNECTOR_PREFIX = PREFIX + "connector";
private static final String THREAD_POOLS_PREFIX = PREFIX + "threadPools";
private static final String ENABLE_HYSTRIX = PREFIX + "enableHystrix";
private static final String HYSTRIX_PREFIX = PREFIX + "hystrix";
public static final Boolean DEFAULT_ENABLE_ADMIN = false;
public static final Boolean DEFAULT_ENABLE_BUCKET = true;
public static final Boolean DEFAULT_ENABLE_OBJECT = true;
public static final Boolean DEFAULT_ENABLE_HYSTRIX = false;
protected String applicationName;
protected Boolean enableAdmin;
protected Boolean enableBucket;
protected Boolean enableObject;
protected Boolean enableHystrix;
protected ConnectorProperties connector;
protected Map<String, ThreadPoolProperties> threadPools;
protected Configuration hystrixConfig;
protected RGWClientProperties() {
}
private RGWClientProperties(Builder builder) {
this.applicationName = builder.applicationName;
this.enableAdmin = builder.enableAdmin;
this.enableBucket = builder.enableBucket;
this.enableObject = builder.enableObject;
this.enableHystrix = builder.enableHystrix;
this.connector = builder.connector;
this.threadPools = builder.threadPools;
this.hystrixConfig = new Configuration(builder.hystrix);
this.validate();
}
private RGWClientProperties(Configuration config) {
this.applicationName = config.getString(APPLICATION_NAME);
this.enableAdmin = config.getBoolean(ENABLE_ADMIN, DEFAULT_ENABLE_ADMIN);
this.enableBucket = config.getBoolean(ENABLE_BUCKET, DEFAULT_ENABLE_BUCKET);
this.enableObject = config.getBoolean(ENABLE_OBJECT, DEFAULT_ENABLE_OBJECT);
this.connector = new ConnectorProperties(config.getSubConfig(CONNECTOR_PREFIX));
Map<String, Configuration> threadPoolConfigs = config.getSubConfigMap(THREAD_POOLS_PREFIX);
if (threadPoolConfigs != null && threadPoolConfigs.size() > 0) {
this.threadPools = threadPoolConfigs.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ThreadPoolProperties(e.getValue())));
} else {
this.threadPools = Collections.emptyMap();
}
this.enableHystrix = config.getBoolean(ENABLE_HYSTRIX, DEFAULT_ENABLE_HYSTRIX);
this.hystrixConfig = config.getSubConfig(HYSTRIX_PREFIX);
this.validate();
}
public String getApplicationName() {
return applicationName;
}
public Boolean isEnableAdmin() {
return enableAdmin;
}
public Boolean isEnableBucket() {
return enableBucket;
}
public Boolean isEnableObject() {
return enableObject;
}
public Boolean isEnableHystrix() {
return enableHystrix;
}
public ConnectorProperties getConnector() {
return connector;
}
public Map<String, ThreadPoolProperties> getThreadPools() {
return threadPools;
}
public Configuration getHystrixConfig() {
return hystrixConfig;
}
public void setEnableAdmin(Boolean enableAdmin) {
this.enableAdmin = enableAdmin;
}
public void setEnableBucket(Boolean enableBucket) {
this.enableBucket = enableBucket;
}
public void setEnableObject(Boolean enableObject) {
this.enableObject = enableObject;
}
public void setEnableHystrix(Boolean enableHystrix) {
this.enableHystrix = enableHystrix;
}
public void setConnector(ConnectorProperties connector) {
this.connector = connector;
}
public void setThreadPools(Map<String, ThreadPoolProperties> threadPools) {
this.threadPools = threadPools;
}
public void setHystrixConfig(Configuration hystrixConfig) {
this.hystrixConfig = hystrixConfig;
}
protected final void validate() {
Validate.notBlank(getApplicationName(), "application.name cannot be empty string");
if (enableAdmin == null) {
enableAdmin = DEFAULT_ENABLE_ADMIN;
}
if (enableBucket == null) {
enableBucket = DEFAULT_ENABLE_BUCKET;
}
if (enableObject == null) {
enableObject = DEFAULT_ENABLE_OBJECT;
}
if (enableHystrix == null) {
enableHystrix = DEFAULT_ENABLE_HYSTRIX;
}
connector.validate();
if (threadPools == null || threadPools.isEmpty()) {
LOGGER.info("ThreadPools is not set.");
threadPools = new HashMap<>(2);
}
threadPools.computeIfAbsent("action", k -> new ThreadPoolPropertiesBuilder()
.withCoreSize(ThreadPoolProperties.DEFAULT_ACTION_CORE_SIZE)
.withMaxSize(ThreadPoolProperties.DEFAULT_ACTION_MAX_SIZE)
.withKeepAlive(ThreadPoolProperties.DEFAULT_ACTION_KEEP_ALIVE)
.withQueueSize(ThreadPoolProperties.DEFAULT_ACTION_QUEUE_SIZE)
.build());
threadPools.computeIfAbsent("listener", k -> new ThreadPoolPropertiesBuilder()
.withCoreSize(ThreadPoolProperties.DEFAULT_LISTENER_CORE_SIZE)
.withMaxSize(ThreadPoolProperties.DEFAULT_LISTENER_MAX_SIZE)
.withKeepAlive(ThreadPoolProperties.DEFAULT_LISTENER_KEEP_ALIVE)
.withQueueSize(ThreadPoolProperties.DEFAULT_LISTENER_QUEUE_SIZE)
.build());
Validate.isTrue(threadPools.size() == 2, "threadPools can only set action and listener");
ThreadPoolProperties action = threadPools.get("action");
if (action.coreSize == null || action.coreSize <= 0) {
action.coreSize = ThreadPoolProperties.DEFAULT_ACTION_CORE_SIZE;
} else if (action.coreSize < 1) {
action.coreSize = 1;
} else if (action.coreSize > 64) {
action.coreSize = 64;
}
if (action.maxSize == null || action.maxSize <= 0) {
action.maxSize = ThreadPoolProperties.DEFAULT_ACTION_MAX_SIZE;
} else if (action.maxSize < action.coreSize) {
action.maxSize = action.coreSize;
} else if (action.maxSize > 128) {
action.maxSize = 128;
}
if (action.keepAlive == null || action.keepAlive <= 0) {
action.keepAlive = ThreadPoolProperties.DEFAULT_ACTION_KEEP_ALIVE;
} else if (action.keepAlive < 10_000) {
action.keepAlive = 10_000;
} else if (action.keepAlive > 600_000) {
action.keepAlive = 600_000;
}
if (action.queueSize == null || action.queueSize < 0) {
action.queueSize = ThreadPoolProperties.DEFAULT_ACTION_QUEUE_SIZE;
}
ThreadPoolProperties listener = threadPools.get("listener");
if (listener.coreSize == null || listener.coreSize <= 0) {
listener.coreSize = ThreadPoolProperties.DEFAULT_LISTENER_CORE_SIZE;
} else if (listener.coreSize < 1) {
listener.coreSize = 1;
} else if (listener.coreSize > 64) {
listener.coreSize = 64;
}
if (listener.maxSize == null || listener.maxSize <= 0) {
listener.maxSize = ThreadPoolProperties.DEFAULT_LISTENER_MAX_SIZE;
} else if (listener.maxSize < listener.coreSize) {
listener.maxSize = listener.coreSize;
} else if (listener.maxSize < 128) {
listener.maxSize = 128;
}
if (listener.keepAlive == null || listener.keepAlive <= 0) {
listener.keepAlive = ThreadPoolProperties.DEFAULT_LISTENER_KEEP_ALIVE;
} else if (listener.keepAlive < 10_000) {
listener.keepAlive = 10_000;
} else if (listener.keepAlive > 600_000) {
listener.keepAlive = 600_000;
}
if (listener.queueSize == null || listener.queueSize <= 0) {
listener.queueSize = ThreadPoolProperties.DEFAULT_LISTENER_QUEUE_SIZE;
} else if (listener.queueSize < 10) {
listener.queueSize = 10;
} else if (listener.queueSize > 128) {
listener.queueSize = 128;
}
}
@Override
public String toString() {
return "RGWClientProperties{" +
"applicationName='" + applicationName + '\'' +
", enableAdmin=" + enableAdmin +
", enableBucket=" + enableBucket +
", enableObject=" + enableObject +
", enableHystrix=" + enableHystrix +
", connector=" + connector +
", threadPools=" + threadPools +
", hystrixConfig=" + hystrixConfig +
'}';
}
public static class ConnectorProperties {
private static final String STORAGES_PREFIX = "storages";
private static final String SUBSCRIBES_PREFIX = "subscribes";
private static final String MAX_CONNECTIONS = "maxConnections";
private static final String CONNECTION_TIMEOUT = "connectionTimeout";
private static final String SOCKET_TIMEOUT = "socketTimeout";
private static final String CONNECTION_MAX_IDLE = "connectionMaxIdle";
private static final String ENABLE_GZIP = "enableGzip";
private static final String ENABLE_KEEP_ALIVE = "enableKeepAlive";
private static final String ENABLE_RETRY = "enableRetry";
private static final String MAX_RETRIES = "maxRetries";
private static final String BASE_DELAY_TIME = "baseDelayTime";
private static final String MAX_BACKOFF_TIME = "maxBackoffTime";
public static final Integer DEFAULT_MAX_CONNECTIONS = 30;
public static final Integer DEFAULT_CONNECTION_TIMEOUT = 5_000;
public static final Integer DEFAULT_SOCKET_TIMEOUT = 10_000;
public static final Long DEFAULT_CONNECTION_MAX_IDLE = 60_000L;
public static final Boolean DEFAULT_ENABLE_GZIP = true;
public static final Boolean DEFAULT_ENABLE_KEEP_ALIVE = true;
public static final Boolean DEFAULT_ENABLE_RETRY = false;
public static final Integer DEFAULT_MAX_RETRIES = 3;
public static final Integer DEFAULT_BASE_DELAY_TIME = 1500;
public static final Integer DEFAULT_MAX_BACKOFF_TIME = 20_000;
protected List<EndpointProperties> storages;
protected List<EndpointProperties> subscribes;
protected Integer maxConnections;
protected Integer connectionTimeout;
protected Integer socketTimeout;
protected Long connectionMaxIdle;
protected Boolean enableGzip;
protected Boolean enableKeepAlive;
protected Boolean enableRetry;
protected Integer maxRetries;
protected Integer baseDelayTime;
protected Integer maxBackoffTime;
public ConnectorProperties() {
}
private ConnectorProperties(ConnectorPropertiesBuilder builder) {
this.storages = builder.storages;
this.subscribes = builder.subscribes;
this.maxConnections = builder.maxConnections;
this.connectionTimeout = builder.connectionTimeout;
this.socketTimeout = builder.socketTimeout;
this.connectionMaxIdle = builder.connectionMaxIdle;
this.enableGzip = builder.enableGzip;
this.enableKeepAlive = builder.enableKeepAlive;
this.enableRetry = builder.enableRetry;
this.maxRetries = builder.maxRetries;
this.baseDelayTime = builder.baseDelayTime;
this.maxBackoffTime = builder.maxBackoffTime;
}
private ConnectorProperties(Configuration config) {
List<Configuration> endpointConfigs = config.getSubConfigList(STORAGES_PREFIX);
if (endpointConfigs != null && endpointConfigs.size() > 0) {
this.storages = endpointConfigs.stream().map(EndpointProperties::new).collect(Collectors.toList());
} else {
this.storages = Collections.emptyList();
}
endpointConfigs = config.getSubConfigList(SUBSCRIBES_PREFIX);
if (endpointConfigs != null && endpointConfigs.size() > 0) {
this.subscribes = endpointConfigs.stream().map(EndpointProperties::new).collect(Collectors.toList());
} else {
this.subscribes = Collections.emptyList();
}
this.maxConnections = config.getInteger(MAX_CONNECTIONS, DEFAULT_MAX_CONNECTIONS);
this.connectionTimeout = config.getInteger(CONNECTION_TIMEOUT, DEFAULT_CONNECTION_TIMEOUT);
this.socketTimeout = config.getInteger(SOCKET_TIMEOUT, DEFAULT_SOCKET_TIMEOUT);
this.connectionMaxIdle = config.getLong(CONNECTION_MAX_IDLE, DEFAULT_CONNECTION_MAX_IDLE);
this.enableGzip = config.getBoolean(ENABLE_GZIP, DEFAULT_ENABLE_GZIP);
this.enableKeepAlive = config.getBoolean(ENABLE_KEEP_ALIVE, DEFAULT_ENABLE_KEEP_ALIVE);
this.enableRetry = config.getBoolean(ENABLE_RETRY, DEFAULT_ENABLE_RETRY);
this.maxRetries = config.getInteger(MAX_RETRIES, DEFAULT_MAX_RETRIES);
this.baseDelayTime = config.getInteger(BASE_DELAY_TIME, DEFAULT_BASE_DELAY_TIME);
this.maxBackoffTime = config.getInteger(MAX_BACKOFF_TIME, DEFAULT_MAX_BACKOFF_TIME);
}
public List<EndpointProperties> getStorages() {
return storages;
}
public List<EndpointProperties> getSubscribes() {
return subscribes;
}
public Integer getMaxConnections() {
return maxConnections;
}
public Integer getConnectionTimeout() {
return connectionTimeout;
}
public Integer getSocketTimeout() {
return socketTimeout;
}
public Long getConnectionMaxIdle() {
return connectionMaxIdle;
}
public Boolean isEnableGzip() {
return enableGzip;
}
public Boolean isEnableKeepAlive() {
return enableKeepAlive;
}
public Boolean isEnableRetry() {
return enableRetry;
}
public Integer getMaxRetries() {
return maxRetries;
}
public Integer getBaseDelayTime() {
return baseDelayTime;
}
public Integer getMaxBackoffTime() {
return maxBackoffTime;
}
public void setStorages(List<EndpointProperties> storages) {
this.storages = storages;
}
public void setSubscribes(List<EndpointProperties> subscribes) {
this.subscribes = subscribes;
}
public void setMaxConnections(Integer maxConnections) {
this.maxConnections = maxConnections;
}
public void setConnectionTimeout(Integer connectionTimeout) {
this.connectionTimeout = connectionTimeout;
}
public void setSocketTimeout(Integer socketTimeout) {
this.socketTimeout = socketTimeout;
}
public void setConnectionMaxIdle(Long connectionMaxIdle) {
this.connectionMaxIdle = connectionMaxIdle;
}
public void setEnableGzip(Boolean enableGzip) {
this.enableGzip = enableGzip;
}
public void setEnableKeepAlive(Boolean enableKeepAlive) {
this.enableKeepAlive = enableKeepAlive;
}
public void setEnableRetry(Boolean enableRetry) {
this.enableRetry = enableRetry;
}
public void setMaxRetries(Integer maxRetries) {
this.maxRetries = maxRetries;
}
public void setBaseDelayTime(Integer baseDelayTime) {
this.baseDelayTime = baseDelayTime;
}
public void setMaxBackoffTime(Integer maxBackoffTime) {
this.maxBackoffTime = maxBackoffTime;
}
private void validate() {
if ((storages == null || storages.size() == 0) && (subscribes == null || subscribes.size() == 0)) {
throw new IllegalArgumentException("none of storages and subscribes is set");
}
if (storages != null && storages.size() > 0) {
if (storages.stream().map(EndpointProperties::getEndpoint).distinct().count() != storages.size()) {
throw new IllegalArgumentException("cannot specify same endpoint");
}
for (EndpointProperties properties : storages) {
Validate.notBlank(properties.getAccessKey(), "accessKey cannot be empty string");
Validate.notBlank(properties.getSecretKey(), "secretKey cannot be empty string");
properties.validate();
}
}
if (subscribes != null && subscribes.size() > 0) {
if (subscribes.stream().map(EndpointProperties::getEndpoint).distinct().count() != subscribes.size()) {
throw new IllegalArgumentException("cannot specify same endpoint");
}
subscribes.forEach(EndpointProperties::validate);
}
if (maxConnections == null || maxConnections <= 0) {
LOGGER.warn("Invalid maxConnections value [{}], set to 30.", maxConnections);
maxConnections = DEFAULT_MAX_CONNECTIONS;
} else if (maxConnections > 100) {
LOGGER.warn("maxConnections value [{}] too large, set to 100.", maxConnections);
maxConnections = 100;
}
if (connectionTimeout == null || connectionTimeout < 0) {
LOGGER.warn("Invalid connectionTimeout value [{}], set to 10000.", connectionTimeout);
connectionTimeout = DEFAULT_CONNECTION_TIMEOUT;
} else if (connectionTimeout < 1000) {
LOGGER.warn("Value connectionTimeout [{}] too short, set to 1000.", connectionTimeout);
connectionTimeout = 1000;
} else if (connectionTimeout > 6_000) {
LOGGER.warn("Value connectionTimeout [{}] too long, set to 6000.", connectionTimeout);
connectionTimeout = 6_000;
}
if (socketTimeout == null || socketTimeout < 0) {
LOGGER.warn("Invalid socketTimeout value [{}], set to 50000.", socketTimeout);
socketTimeout = DEFAULT_SOCKET_TIMEOUT;
} else if (socketTimeout < 5000) {
LOGGER.warn("Value socketTimeout [{}] too short, set to 5000.", socketTimeout);
socketTimeout = 5000;
} else if (socketTimeout > 20_000) {
LOGGER.warn("Value socketTimeout [{}] too long, set to 20000.", socketTimeout);
socketTimeout = 20_000;
}
if (connectionMaxIdle == null || connectionMaxIdle < 0) {
LOGGER.warn("Invalid connectionMaxIdle value [{}], set to 60000.", connectionMaxIdle);
connectionMaxIdle = DEFAULT_CONNECTION_MAX_IDLE;
} else if (connectionMaxIdle < 10_000L) {
LOGGER.warn("Value connectionMaxIdle [{}] too short, set to 10000.", connectionMaxIdle);
connectionMaxIdle = 10_000L;
} else if (connectionMaxIdle > 600_000) {
LOGGER.warn("Value connectionMaxIdle [{}] too long, set to 600000.", connectionMaxIdle);
connectionMaxIdle = 600_000L;
}
if (enableGzip == null) {
enableGzip = DEFAULT_ENABLE_GZIP;
}
if (enableKeepAlive == null) {
enableKeepAlive = DEFAULT_ENABLE_KEEP_ALIVE;
}
if (enableRetry == null) {
enableRetry = DEFAULT_ENABLE_RETRY;
}
if (enableRetry) {
if (maxRetries == null || maxRetries < 0) {
maxRetries = DEFAULT_MAX_RETRIES;
} else if (maxRetries > 3) {
maxRetries = 3;
}
if (baseDelayTime == null || baseDelayTime < 0) {
baseDelayTime = DEFAULT_BASE_DELAY_TIME;
} else if (baseDelayTime < 1000) {
baseDelayTime = 1000;
} else if (baseDelayTime > 5_000) {
baseDelayTime = 5_000;
}
if (maxBackoffTime == null || maxBackoffTime < 0) {
maxBackoffTime = DEFAULT_MAX_BACKOFF_TIME;
} else if (maxBackoffTime < baseDelayTime) {
maxBackoffTime = baseDelayTime;
} else if (maxBackoffTime > 30_000) {
maxBackoffTime = 30_000;
}
}
}
@Override
public String toString() {
return "ConnectorProperties{" +
"storages=" + storages +
", subscribes='" + subscribes + '\'' +
", maxConnections=" + maxConnections +
", connectionTimeout=" + connectionTimeout +
", socketTimeout=" + socketTimeout +
", connectionMaxIdle=" + connectionMaxIdle +
", enableGzip=" + enableGzip +
", enableKeepAlive=" + enableKeepAlive +
", enableRetry=" + enableRetry +
", maxRetries=" + maxRetries +
", baseDelayTime=" + baseDelayTime +
", maxBackoffTime=" + maxBackoffTime +
'}';
}
}
public static class EndpointProperties {
private static final String ENDPOINT = "endpoint";
private static final String REGION = "region";
private static final String PROTOCOL = "protocol";
private static final String ACCESS_KEY = "accessKey";
private static final String SECRET_KEY = "secretKey";
public static final String DEFAULT_PROTOCOL = "http";
protected String endpoint;
protected String region;
protected String protocol;
protected String accessKey;
protected String secretKey;
public EndpointProperties() {
}
private EndpointProperties(EndpointPropertiesBuilder builder) {
this.endpoint = builder.endpoint;
this.region = builder.region;
this.protocol = builder.protocol;
this.accessKey = builder.accessKey;
this.secretKey = builder.secretKey;
}
private EndpointProperties(Configuration config) {
this.endpoint = config.getString(ENDPOINT);
this.region = config.getString(REGION, "").trim();
this.protocol = config.getString(PROTOCOL, DEFAULT_PROTOCOL);
this.accessKey = config.getString(ACCESS_KEY, "").trim();
this.secretKey = config.getString(SECRET_KEY, "").trim();
}
public String getEndpoint() {
return endpoint;
}
public String getRegion() {
return region;
}
public String getProtocol() {
return protocol;
}
public String getAccessKey() {
return accessKey;
}
public String getSecretKey() {
return secretKey;
}
public void setEndpoint(String endpoint) {
this.endpoint = endpoint;
}
public void setRegion(String region) {
this.region = region;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
public void setAccessKey(String accessKey) {
this.accessKey = accessKey;
}
public void setSecretKey(String secretKey) {
this.secretKey = secretKey;
}
private void validate() {
Validate.notBlank(endpoint, "endpoint cannot be empty string");
try {
URI uri = new URI(protocol + "://" + endpoint);
if (StringUtils.isBlank(uri.getHost()) || AddressUtil.getPort(uri) < 0) {
throw new IllegalArgumentException("invalid endpoint: " + endpoint);
}
} catch (URISyntaxException e) {
throw new IllegalArgumentException("invalid endpoint: " + endpoint, e);
}
if (StringUtils.isBlank(protocol)) {
LOGGER.info("Protocol is empty, set to http.");
protocol = DEFAULT_PROTOCOL;
} else {
protocol = protocol.toLowerCase();
if (!"http".equals(protocol) && !"https".equals(protocol)) {
LOGGER.warn("Invalid protocol value [{}], set to http", protocol);
protocol = DEFAULT_PROTOCOL;
}
}
}
@Override
public String toString() {
return "EndpointProperties{" +
"endpoint='" + endpoint + '\'' +
", region='" + region + '\'' +
", protocol='" + protocol + '\'' +
", hash(accessKey)='" + (accessKey == null ? null : accessKey.hashCode()) + '\'' +
", hash(secretKey)='" + (secretKey == null ? null : secretKey.hashCode()) + '\'' +
'}';
}
}
public static class ThreadPoolProperties {
private static final String CORE_SIZE = "coreSize";
private static final String MAX_SIZE = "maxSize";
private static final String KEEP_ALIVE = "keepAlive";
private static final String QUEUE_SIZE = "queueSize";
public static final Integer DEFAULT_ACTION_CORE_SIZE = Runtime.getRuntime().availableProcessors();
public static final Integer DEFAULT_ACTION_MAX_SIZE = DEFAULT_ACTION_CORE_SIZE * 4;
public static final Integer DEFAULT_ACTION_KEEP_ALIVE = 60_000;
public static final Integer DEFAULT_ACTION_QUEUE_SIZE = 0;
public static final Integer DEFAULT_LISTENER_CORE_SIZE = Runtime.getRuntime().availableProcessors();
public static final Integer DEFAULT_LISTENER_MAX_SIZE = DEFAULT_LISTENER_CORE_SIZE;
public static final Integer DEFAULT_LISTENER_KEEP_ALIVE = 0;
public static final Integer DEFAULT_LISTENER_QUEUE_SIZE = 20;
protected Integer coreSize;
protected Integer maxSize;
protected Integer keepAlive;
protected Integer queueSize;
public ThreadPoolProperties() {
}
private ThreadPoolProperties(ThreadPoolPropertiesBuilder builder) {
this.coreSize = builder.coreSize;
this.maxSize = builder.maxSize;
this.keepAlive = builder.keepAlive;
this.queueSize = builder.queueSize;
}
private ThreadPoolProperties(Configuration config) {
this.coreSize = config.getInteger(CORE_SIZE);
this.maxSize = config.getInteger(MAX_SIZE);
this.keepAlive = config.getInteger(KEEP_ALIVE);
this.queueSize = config.getInteger(QUEUE_SIZE);
}
public Integer getCoreSize() {
return coreSize;
}
public Integer getMaxSize() {
return maxSize;
}
public Integer getKeepAlive() {
return keepAlive;
}
public Integer getQueueSize() {
return queueSize;
}
public void setCoreSize(Integer coreSize) {
this.coreSize = coreSize;
}
public void setMaxSize(Integer maxSize) {
this.maxSize = maxSize;
}
public void setKeepAlive(Integer keepAlive) {
this.keepAlive = keepAlive;
}
public void setQueueSize(Integer queueSize) {
this.queueSize = queueSize;
}
@Override
public String toString() {
return "ThreadPoolProperties{" +
"coreSize=" + coreSize +
", maxSize=" + maxSize +
", keepAlive=" + keepAlive +
", queueSize=" + queueSize +
'}';
}
}
public static final class Builder {
private String applicationName;
private Boolean enableAdmin;
private Boolean enableBucket;
private Boolean enableObject;
private Boolean enableHystrix;
private ConnectorProperties connector;
private Map<String, ThreadPoolProperties> threadPools;
private Map<String, String> hystrix;
public Builder() {
this.threadPools = new HashMap<>(2);
this.hystrix = new HashMap<>();
}
public Builder withApplicationName(String applicationName) {
this.applicationName = applicationName;
return this;
}
public Builder withEnableAdmin(Boolean enableAdmin) {
this.enableAdmin = enableAdmin;
return this;
}
public Builder withEnableBucket(Boolean enableBucket) {
this.enableBucket = enableBucket;
return this;
}
public Builder withEnableObject(Boolean enableObject) {
this.enableObject = enableObject;
return this;
}
public Builder withEnableHystrix(Boolean enableHystrix) {
this.enableHystrix = enableHystrix;
return this;
}
public Builder withConnector(ConnectorProperties connector) {
this.connector = connector;
return this;
}
public ConnectorPropertiesBuilder withConnector() {
return new ConnectorPropertiesBuilder(this);
}
public ThreadPoolPropertiesBuilder withActionThreadPool() {
return new ThreadPoolPropertiesBuilder("action", this);
}
public ThreadPoolPropertiesBuilder withListenerThreadPool() {
return new ThreadPoolPropertiesBuilder("listener", this);
}
private Builder withThreadPool(String name, ThreadPoolProperties threadPool) {
this.threadPools.put(name, threadPool);
return this;
}
public Builder addHystrix(String key, String value) {
this.hystrix.put(key, value);
return this;
}
public RGWClientProperties build() {
return new RGWClientProperties(this);
}
}
public static class ConnectorPropertiesBuilder {
final Builder builder;
private List<EndpointProperties> storages;
private List<EndpointProperties> subscribes;
private Integer maxConnections;
private Integer connectionTimeout;
private Integer socketTimeout;
private Long connectionMaxIdle;
private Boolean enableGzip;
private Boolean enableKeepAlive;
private Boolean enableRetry;
private Integer maxRetries;
private Integer baseDelayTime;
private Integer maxBackoffTime;
private ConnectorPropertiesBuilder(Builder builder) {
this.builder = builder;
this.storages = new LinkedList<>();
this.subscribes = new LinkedList<>();
}
public ConnectorPropertiesBuilder withStorages(List<EndpointProperties> storages) {
this.storages.clear();
this.storages.addAll(storages);
return this;
}
public ConnectorPropertiesBuilder withStorage(EndpointProperties storage) {
this.storages.add(storage);
return this;
}
public StorageEndpointPropertiesBuilder withStorage() {
return new StorageEndpointPropertiesBuilder(this);
}
public ConnectorPropertiesBuilder withSubscribes(List<EndpointProperties> subscribes) {
this.subscribes.clear();
this.subscribes.addAll(subscribes);
return this;
}
public ConnectorPropertiesBuilder withSubscribe(EndpointProperties subscribe) {
this.subscribes.add(subscribe);
return this;
}
public SubscribeEndpointPropertiesBuilder withSubscribe() {
return new SubscribeEndpointPropertiesBuilder(this);
}
public ConnectorPropertiesBuilder withMaxConnections(Integer maxConnections) {
this.maxConnections = maxConnections;
return this;
}
public ConnectorPropertiesBuilder withConnectionTimeout(Integer connectionTimeout) {
this.connectionTimeout = connectionTimeout;
return this;
}
public ConnectorPropertiesBuilder withSocketTimeout(Integer socketTimeout) {
this.socketTimeout = socketTimeout;
return this;
}
public ConnectorPropertiesBuilder withConnectionMaxIdle(Long connectionMaxIdle) {
this.connectionMaxIdle = connectionMaxIdle;
return this;
}
public ConnectorPropertiesBuilder withEnableGzip(Boolean enableGzip) {
this.enableGzip = enableGzip;
return this;
}
public ConnectorPropertiesBuilder withEnableKeepAlive(Boolean enableKeepAlive) {
this.enableKeepAlive = enableKeepAlive;
return this;
}
public ConnectorPropertiesBuilder withEnableRetry(Boolean enableRetry) {
this.enableRetry = enableRetry;
return this;
}
public ConnectorPropertiesBuilder withMaxRetries(Integer maxRetries) {
this.maxRetries = maxRetries;
return this;
}
public ConnectorPropertiesBuilder withBaseDelayTime(Integer baseDelayTime) {
this.baseDelayTime = baseDelayTime;
return this;
}
public ConnectorPropertiesBuilder withMaxBackoffTime(Integer maxBackoffTime) {
this.maxBackoffTime = maxBackoffTime;
return this;
}
public Builder endConnector() {
return builder.withConnector(new ConnectorProperties(this));
}
}
public static class StorageEndpointPropertiesBuilder extends EndpointPropertiesBuilder<StorageEndpointPropertiesBuilder> {
private StorageEndpointPropertiesBuilder(ConnectorPropertiesBuilder builder) {
super(builder);
}
public ConnectorPropertiesBuilder endStorage() {
return builder.withStorage(build());
}
}
public static class SubscribeEndpointPropertiesBuilder extends EndpointPropertiesBuilder<SubscribeEndpointPropertiesBuilder> {
private SubscribeEndpointPropertiesBuilder(ConnectorPropertiesBuilder builder) {
super(builder);
}
public ConnectorPropertiesBuilder endSubscribe() {
return builder.withSubscribe(build());
}
}
public static class EndpointPropertiesBuilder<T extends EndpointPropertiesBuilder<T>> {
final ConnectorPropertiesBuilder builder;
private String endpoint;
private String region;
private String protocol;
private String accessKey;
private String secretKey;
private EndpointPropertiesBuilder(ConnectorPropertiesBuilder builder) {
this.builder = builder;
}
public T withEndpoint(String endpoint) {
this.endpoint = endpoint;
return self();
}
public T withRegion(String region) {
this.region = region;
return self();
}
public T withProtocol(String protocol) {
this.protocol = protocol;
return self();
}
public T withAccessKey(String accessKey) {
this.accessKey = accessKey;
return self();
}
public T withSecretKey(String secretKey) {
this.secretKey = secretKey;
return self();
}
@SuppressWarnings("unchecked")
private T self() {
return (T) this;
}
EndpointProperties build() {
return new EndpointProperties(this);
}
}
public static final class ThreadPoolPropertiesBuilder {
private final String name;
private final Builder builder;
private Integer coreSize;
private Integer maxSize;
private Integer keepAlive;
private Integer queueSize;
private ThreadPoolPropertiesBuilder() {
this.name = null;
this.builder = null;
}
private ThreadPoolPropertiesBuilder(String name, Builder builder) {
this.name = name;
this.builder = builder;
}
public ThreadPoolPropertiesBuilder withCoreSize(Integer coreSize) {
this.coreSize = coreSize;
return this;
}
public ThreadPoolPropertiesBuilder withMaxSize(Integer maxSize) {
this.maxSize = maxSize;
return this;
}
public ThreadPoolPropertiesBuilder withKeepAlive(Integer keepAlive) {
this.keepAlive = keepAlive;
return this;
}
public ThreadPoolPropertiesBuilder withQueueSize(Integer queueSize) {
this.queueSize = queueSize;
return this;
}
private ThreadPoolProperties build() {
return new ThreadPoolProperties(this);
}
public Builder endThreadPool() {
return builder.withThreadPool(name, build());
}
}
public static RGWClientProperties loadFromFile(String file) {
try {
return loadFromConfig(new Configuration(new File(file)));
} catch (IOException e) {
throw new RGWException(e);
}
}
public static RGWClientProperties loadFromResource(String resource) {
try {
return loadFromConfig(new Configuration(resource));
} catch (IOException e) {
throw new RGWException(e);
}
}
public static RGWClientProperties loadFromConfig(Configuration config) {
return new RGWClientProperties(config);
}
}
|
package gestionEleves;
import java.util.ArrayList;
public class Eleve implements Comparable<Eleve> {
private String nom;
private ArrayList<Integer> listeNotes = new ArrayList();
private double moyenne = 0;
public Eleve(String nom) {
super();
this.nom = nom;
}
public double getMoyenne() {
return moyenne;
}
public String getNom() {
return nom;
}
public ArrayList<Integer> getListeNotes() {
return listeNotes;
}
public void ajouterNote(int note) {
// Normalisation
if (note < 0)
note = 0;
if (note > 20)
note = 20;
// ajout
listeNotes.add(note);
// recalcul moyenne
// méthode classique
double sommeNotes = 0;
for (int n : listeNotes)
sommeNotes += n;
moyenne = sommeNotes / listeNotes.size();
// Méthode rusée
// int k = listeNotes.size();
// moyenne = ((moyenne *(k-1))+note)/k;
}
@Override
public String toString() {
return nom + ": " + moyenne;
}
@Override
public int compareTo(Eleve autreEleve) {
double epsilon = 0.01;
if (this.getMoyenne() < autreEleve.getMoyenne() - epsilon)
return -1;
if (moyenne == autreEleve.moyenne)
return 0;
if (this.getMoyenne() > autreEleve.getMoyenne() - epsilon)
return 1;
return 0;
}
}
|
package cn.hrbcu.com.servlet.adminServlet;
import cn.hrbcu.com.entity.Books;
import cn.hrbcu.com.entity.Page;
import cn.hrbcu.com.entity.User;
import cn.hrbcu.com.service.BooksService;
import cn.hrbcu.com.service.UserService;
import cn.hrbcu.com.service.impl.BooksServiceImpl;
import cn.hrbcu.com.service.impl.UserServiceImpl;
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 java.io.IOException;
import java.util.Map;
/**
* @author: XuYi
* @date: 2021/5/30 14:10
* @description: 用户管理列表
*/
@WebServlet("/UsersListServlet")
public class UsersListServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
/*设置编码*/
req.setCharacterEncoding("utf-8");
/*获取状态参数*/
String status = req.getParameter("status");
/*获取当前页码*/
String currentPage = req.getParameter("currentPage");
/*获取总页数*/
String totalPage = req.getParameter("totalPage");
/*每页条数*/
String rows = req.getParameter("rows");
/*初始化转发路径*/
String path = null;
// if("PageList".equals(status)) {
/*边界处理*/
if (currentPage == null || "".equals(currentPage)) {
currentPage = "1";
if (currentPage == null || "".equals(currentPage)) {
currentPage = "1";
}
}
if (rows == null || "".equals(rows)) {
rows = "5";
}
if (currentPage == totalPage) {
currentPage = "1";
}
/*获取条件查询参数*/
Map<String, String[]> condition = req.getParameterMap();
/*调用服务层*/
UserService userService = new UserServiceImpl();
Page<User> pb = userService.findUserByPage(currentPage, rows, condition);
System.out.println(pb + "\n");
/*往request注入值*/
req.setAttribute("pb", pb);
/*将查询条件注入request*/
req.setAttribute("condition", condition);
/*设置并转发*/
path = "/Users.jsp";
if("delBooks".equals(status)){
/*获取所选id*/
String[] id = req.getParameterValues("id");
/*调用服务层完成删除*/
UserService userService_del = new UserServiceImpl();
userService_del.delSelectedUser(id);
/*设置跳转页面*/
resp.sendRedirect(req.getContextPath()+"/UsersListServlet");
}
req.getRequestDispatcher(path).forward(req,resp);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
}
|
/**
*
*/
package com.DB.model;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;
/**
* @author Bruce GONG
*
*/
public class Role {
private String Role;
private Date createTime;
private List<View> views = new ArrayList<View>();
/**
* @return the views
*/
public List<View> getViews() {
return views;
}
/**
* @param views the views to set
*/
public void setViews(List<View> views) {
this.views = views;
}
public void addView(View view)
{
this.views.add(view);
}
public void removeView(View view)
{
this.views.remove(view);
}
/**
* @return the creatTime
*/
public Date getCreateTime() {
return createTime;
}
/**
* @param creatTime the creatTime to set
*/
public void setCreateTime(Date creatTime) {
this.createTime = creatTime;
}
public Role(String role) {
super();
Role = role;
}
public Role() {
// TODO Auto-generated constructor stub
}
/**
* @return the role
*/
public String getRole() {
return Role;
}
/**
* @param role the role to set
*/
public void setRole(String role) {
Role = role;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((Role == null) ? 0 : Role.hashCode());
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Role other = (Role) obj;
if (Role == null) {
if (other.Role != null)
return false;
} else if (!Role.equals(other.Role))
return false;
return true;
}
}
|
package nesto.rxtest.func;
import android.support.annotation.NonNull;
import android.view.View;
import java.util.concurrent.TimeUnit;
import rx.Observable;
import rx.Subscriber;
import rx.functions.Func1;
import rx.schedulers.TimeInterval;
/**
* Created on 2016/6/27.
* By nesto
* <p>
* convert click event to time interval
*/
public class ViewBinder {
public static Observable<Long> bind(@NonNull View view) {
return bind(view, null);
}
public static Observable<Long> bind(@NonNull View view, View.OnClickListener listener) {
return Observable.create(new ClickOnSubscribe(view, listener))
.timeInterval()
.map(new Func1<TimeInterval<Void>, Long>() {
@Override
public Long call(TimeInterval<Void> interval) {
return interval.getIntervalInMilliseconds();
}
});
}
public static Observable<Void> bindWithDebounce(@NonNull View view, View.OnClickListener listener) {
return bind(view, listener)
.debounce(500, TimeUnit.MILLISECONDS)
.map(new Func1<Long, Void>() {
@Override
public Void call(Long aLong) {
return null;
}
});
}
public static Observable<Void> bindWithDebounce(@NonNull View view) {
return bindWithDebounce(view, null);
}
private static class ClickOnSubscribe implements Observable.OnSubscribe<Void> {
private View view;
private View.OnClickListener listener;
public ClickOnSubscribe(View view, View.OnClickListener listener) {
this.view = view;
this.listener = listener;
}
@Override
public void call(final Subscriber<? super Void> subscriber) {
final View.OnClickListener listener = new View.OnClickListener() {
@Override
public void onClick(View v) {
subscriber.onNext(null);
if (ClickOnSubscribe.this.listener != null) {
ClickOnSubscribe.this.listener.onClick(v);
}
}
};
view.setOnClickListener(listener);
}
}
}
|
package Hw.Tz;
public interface SuperEncoder {
byte[] serialize(Object anyBean);
Object deserialize(byte[] date);
}
|
package team.groupproject.service;
import java.util.List;
import java.util.Optional;
import team.groupproject.entity.Material;
public interface MaterialService {
List<Material> findAll();
Optional<Material> findByName(String name);
Optional<Material> findById(Integer id);
Material updateMaterial(Integer id, String newName);
void deleteMaterial(Material material);
Material saveMaterial(Material material);
}
|
package com.stk123.common.ml.jamlab;
import Jama.Matrix;
public final class JDatafun
{
private JDatafun()
{
}
public static Matrix min(Matrix X, Matrix Y)
{
int x_rows = X.getRowDimension();
int x_cols = X.getColumnDimension();
int y_rows = Y.getRowDimension();
int y_cols = Y.getColumnDimension();
double Xarray[][] = X.getArray();
double Yarray[][] = Y.getArray();
Matrix result = null;
if(x_rows != y_rows || x_cols != y_rows)
throw new IllegalArgumentException("Error : Incompatible matrix dimensions.");
result = new Matrix(x_rows, x_cols);
for(int i = 0; i < x_rows; i++)
{
for(int j = 0; j < x_cols; j++)
result.set(i, j, Xarray[i][j] >= Yarray[i][j] ? Yarray[i][j] : Xarray[i][j]);
}
return result;
}
public static Matrix sum(Matrix matrix)
{
return sum(matrix, 1);
}
public static Matrix sum(Matrix matrix, int Dim)
{
double internal[][] = matrix.getArrayCopy();
double temp = 0.0D;
Dim = Math.abs(Dim);
Dim %= 2;
int row = matrix.getRowDimension();
int col = matrix.getColumnDimension();
double summing[][];
if(Dim == 1)
{
summing = new double[1][col];
for(int j = 0; j < col; j++)
{
for(int i = 0; i < row; i++)
temp += internal[i][j];
summing[0][j] = temp;
temp = 0.0D;
}
} else
{
summing = new double[row][1];
for(int i = 0; i < row; i++)
{
for(int j = 0; j < col; j++)
temp += internal[i][j];
summing[i][0] = temp;
temp = 0.0D;
}
}
return new Matrix(summing);
}
} |
package com.ms.module.wechat.clear.activity.scan;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.ms.module.wechat.clear.R;
import com.ms.module.wechat.clear.WeChatClearModule;
import com.ms.module.wechat.clear.activity.clear.WeChatClearActivity;
import com.ms.module.wechat.clear.base.BaseAppCompatActivity;
import com.ms.module.wechat.clear.base.RxView;
import com.ms.module.wechat.clear.base.StatusBarUtil;
import com.ms.module.wechat.clear.utils.ByteSizeToStringUnitUtils;
import com.ms.view.loading.FastChargeView;
import java.util.ArrayList;
import java.util.List;
/**
* 扫描中页面
*/
public class WeChatClearScanIngActivity extends BaseAppCompatActivity implements RxView.Action1<View> {
private static final String TAG = "WeChatClearScanIngActiv";
private WeChatClearScanIngActivityViewModel weChatClearScanIngActivityViewModel;
private TextView textViewTotalScanGarbageSize;
private RecyclerView recyclerView;
private WeChatScanIngRecyclerViewAdapter weChatScanIngRecyclerViewAdapter;
private List<WeChatScanIngRecyclerViewAdapter.WeChatScanIngRecyclerViewAdapterItem> datas = new ArrayList<>();
private Observer<Long> observerTotalScanGarbageSize;
private Observer<List<String>> observerRubbish;
private Observer<List<String>> observerMp4;
private Observer<List<String>> observerImage;
private Observer<List<String>> observerVoice;
private Observer<List<String>> observerReceiveFile;
private Observer<List<String>> observerEmoji;
private boolean rubbishFinish = false;
private boolean mp4Finish = false;
private boolean imageFinish = false;
private boolean voiceFinish = false;
private boolean receiveFileFinish = false;
private boolean emojiFinish = false;
private ImageView imageViewBack;
private FastChargeView fastChargeView;
@Override
protected void setStatusBar() {
super.setStatusBar();
StatusBarUtil.setColor(this, Color.parseColor("#4FACF2"), 0);
StatusBarUtil.setDarkMode(this);
}
@Override
protected int getLayout() {
return R.layout.activity_wechat_clear_scan_ing;
}
@Override
protected void initView() {
super.initView();
textViewTotalScanGarbageSize = findViewById(R.id.textViewTotalScanGarbageSize);
imageViewBack = findViewById(R.id.imageViewBack);
fastChargeView = findViewById(R.id.fastChargeView);
RxView.setOnClickListeners(this::onClick, imageViewBack);
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 进入扫描页面
WeChatClearModule.getWeChatClearCallBack().onEnterWeChatClearScan(this);
weChatClearScanIngActivityViewModel = new ViewModelProvider(this).get(WeChatClearScanIngActivityViewModel.class);
weChatClearScanIngActivityViewModel.clearData();
fastChargeView.setDuration(800);
fastChargeView.startAnimation();
observerTotalScanGarbageSize = new Observer<Long>() {
@Override
public void onChanged(Long size) {
if (size != null) {
textViewTotalScanGarbageSize.setText(ByteSizeToStringUnitUtils.byteToStringUnit(size) + "");
}
}
};
weChatClearScanIngActivityViewModel.getMutableLiveDataTotalScanGarbageSize().observe(this, observerTotalScanGarbageSize);
observerRubbish = new Observer<List<String>>() {
@Override
public void onChanged(List<String> strings) {
if (!rubbishFinish) {
rubbishFinish = true;
datas.get(0).status = WeChatScanIngRecyclerViewAdapter.SCAN_STATUS.FINISH;
weChatClearScanIngActivityViewModel.getMutableLiveDataVideo().postValue(null);
datas.get(1).status = WeChatScanIngRecyclerViewAdapter.SCAN_STATUS.ING;
weChatScanIngRecyclerViewAdapter.notifyDataSetChanged();
}
}
};
weChatClearScanIngActivityViewModel.getLiveDataRubbish().observe(this, observerRubbish);
observerMp4 = new Observer<List<String>>() {
@Override
public void onChanged(List<String> strings) {
if (!mp4Finish) {
mp4Finish = true;
datas.get(1).status = WeChatScanIngRecyclerViewAdapter.SCAN_STATUS.FINISH;
weChatClearScanIngActivityViewModel.getMutableLiveDataImage().postValue(null);
datas.get(2).status = WeChatScanIngRecyclerViewAdapter.SCAN_STATUS.ING;
weChatScanIngRecyclerViewAdapter.notifyDataSetChanged();
}
}
};
weChatClearScanIngActivityViewModel.getLiveDataVideo().observe(this, observerMp4);
observerImage = new Observer<List<String>>() {
@Override
public void onChanged(List<String> strings) {
if (!imageFinish) {
imageFinish = true;
datas.get(2).status = WeChatScanIngRecyclerViewAdapter.SCAN_STATUS.FINISH;
weChatClearScanIngActivityViewModel.getMutableLiveDataVoice().postValue(null);
datas.get(3).status = WeChatScanIngRecyclerViewAdapter.SCAN_STATUS.ING;
weChatScanIngRecyclerViewAdapter.notifyDataSetChanged();
}
}
};
weChatClearScanIngActivityViewModel.getLiveDataImage().observe(this, observerImage);
observerVoice = new Observer<List<String>>() {
@Override
public void onChanged(List<String> strings) {
if (!voiceFinish) {
voiceFinish = true;
datas.get(3).status = WeChatScanIngRecyclerViewAdapter.SCAN_STATUS.FINISH;
weChatClearScanIngActivityViewModel.getMutableLiveDataReceiveFile().postValue(null);
datas.get(4).status = WeChatScanIngRecyclerViewAdapter.SCAN_STATUS.ING;
weChatScanIngRecyclerViewAdapter.notifyDataSetChanged();
}
}
};
weChatClearScanIngActivityViewModel.getLiveDataVoice().observe(this, observerVoice);
observerReceiveFile = new Observer<List<String>>() {
@Override
public void onChanged(List<String> strings) {
if (!receiveFileFinish) {
receiveFileFinish = true;
datas.get(4).status = WeChatScanIngRecyclerViewAdapter.SCAN_STATUS.FINISH;
weChatClearScanIngActivityViewModel.getMutableLiveDataEmoji().postValue(null);
datas.get(5).status = WeChatScanIngRecyclerViewAdapter.SCAN_STATUS.ING;
weChatScanIngRecyclerViewAdapter.notifyDataSetChanged();
}
}
};
weChatClearScanIngActivityViewModel.getLiveDataReceiveFile().observe(this, observerReceiveFile);
observerEmoji = new Observer<List<String>>() {
@Override
public void onChanged(List<String> strings) {
if (!emojiFinish) {
emojiFinish = true;
datas.get(5).status = WeChatScanIngRecyclerViewAdapter.SCAN_STATUS.FINISH;
weChatScanIngRecyclerViewAdapter.notifyDataSetChanged();
Intent intent = new Intent(WeChatClearScanIngActivity.this, WeChatClearActivity.class);
startActivity(intent);
finish();
}
}
};
weChatClearScanIngActivityViewModel.getLiveDataEmoji().observe(this, observerEmoji);
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
datas.add(new WeChatScanIngRecyclerViewAdapter.WeChatScanIngRecyclerViewAdapterItem("垃圾文件", R.drawable.image_rubbish));
datas.add(new WeChatScanIngRecyclerViewAdapter.WeChatScanIngRecyclerViewAdapterItem("聊天小视频", R.drawable.image_video));
datas.add(new WeChatScanIngRecyclerViewAdapter.WeChatScanIngRecyclerViewAdapterItem("聊天图片", R.drawable.image_image));
datas.add(new WeChatScanIngRecyclerViewAdapter.WeChatScanIngRecyclerViewAdapterItem("聊天语音", R.drawable.image_voice));
datas.add(new WeChatScanIngRecyclerViewAdapter.WeChatScanIngRecyclerViewAdapterItem("文件", R.drawable.image_file));
datas.add(new WeChatScanIngRecyclerViewAdapter.WeChatScanIngRecyclerViewAdapterItem("聊天表情包", R.drawable.image_emoji));
weChatScanIngRecyclerViewAdapter = new WeChatScanIngRecyclerViewAdapter(this, datas);
recyclerView.setAdapter(weChatScanIngRecyclerViewAdapter);
datas.get(0).status = WeChatScanIngRecyclerViewAdapter.SCAN_STATUS.ING;
weChatClearScanIngActivityViewModel.getMutableLiveDataRubbish().postValue(null);
weChatScanIngRecyclerViewAdapter.notifyDataSetChanged();
}
@Override
protected void onResume() {
super.onResume();
if (!weChatClearScanIngActivityViewModel.getLiveDataRubbish().hasActiveObservers()) {
weChatClearScanIngActivityViewModel.getLiveDataRubbish().observe(this, observerRubbish);
}
if (!weChatClearScanIngActivityViewModel.getLiveDataVideo().hasActiveObservers()) {
weChatClearScanIngActivityViewModel.getLiveDataVideo().observe(this, observerMp4);
}
if (!weChatClearScanIngActivityViewModel.getLiveDataImage().hasActiveObservers()) {
weChatClearScanIngActivityViewModel.getLiveDataImage().observe(this, observerImage);
}
if (!weChatClearScanIngActivityViewModel.getLiveDataVoice().hasActiveObservers()) {
weChatClearScanIngActivityViewModel.getLiveDataVoice().observe(this, observerVoice);
}
if (!weChatClearScanIngActivityViewModel.getLiveDataReceiveFile().hasActiveObservers()) {
weChatClearScanIngActivityViewModel.getLiveDataReceiveFile().observe(this, observerReceiveFile);
}
if (!weChatClearScanIngActivityViewModel.getLiveDataEmoji().hasActiveObservers()) {
weChatClearScanIngActivityViewModel.getLiveDataEmoji().observe(this, observerEmoji);
}
}
@Override
protected void onStop() {
super.onStop();
if (weChatClearScanIngActivityViewModel.getLiveDataRubbish().hasActiveObservers()) {
weChatClearScanIngActivityViewModel.getLiveDataRubbish().removeObservers(this);
}
if (weChatClearScanIngActivityViewModel.getLiveDataVideo().hasActiveObservers()) {
weChatClearScanIngActivityViewModel.getLiveDataVideo().removeObservers(this);
}
if (weChatClearScanIngActivityViewModel.getLiveDataImage().hasActiveObservers()) {
weChatClearScanIngActivityViewModel.getLiveDataImage().removeObservers(this);
}
if (weChatClearScanIngActivityViewModel.getLiveDataVoice().hasActiveObservers()) {
weChatClearScanIngActivityViewModel.getLiveDataVoice().removeObservers(this);
}
if (weChatClearScanIngActivityViewModel.getLiveDataReceiveFile().hasActiveObservers()) {
weChatClearScanIngActivityViewModel.getLiveDataReceiveFile().removeObservers(this);
}
if (weChatClearScanIngActivityViewModel.getLiveDataEmoji().hasActiveObservers()) {
weChatClearScanIngActivityViewModel.getLiveDataEmoji().removeObservers(this);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (weChatClearScanIngActivityViewModel.getLiveDataRubbish().hasObservers()) {
weChatClearScanIngActivityViewModel.getLiveDataRubbish().removeObservers(this);
}
if (weChatClearScanIngActivityViewModel.getLiveDataVideo().hasObservers()) {
weChatClearScanIngActivityViewModel.getLiveDataVideo().removeObservers(this);
}
if (weChatClearScanIngActivityViewModel.getLiveDataImage().hasObservers()) {
weChatClearScanIngActivityViewModel.getLiveDataImage().removeObservers(this);
}
if (weChatClearScanIngActivityViewModel.getLiveDataVoice().hasObservers()) {
weChatClearScanIngActivityViewModel.getLiveDataVoice().removeObservers(this);
}
if (weChatClearScanIngActivityViewModel.getLiveDataReceiveFile().hasObservers()) {
weChatClearScanIngActivityViewModel.getLiveDataReceiveFile().removeObservers(this);
}
if (weChatClearScanIngActivityViewModel.getLiveDataEmoji().hasObservers()) {
weChatClearScanIngActivityViewModel.getLiveDataEmoji().removeObservers(this);
}
}
@Override
public void onClick(View view) {
if (view.getId() == R.id.imageViewBack) {
finish();
WeChatClearModule.getWeChatClearCallBack().onClose(this);
}
}
}
|
package com.healthyteam.android.healthylifers.Data;
import com.google.android.gms.tasks.Task;
public interface OnRunTaskListener {
void OnStart();
void OnComplete(Task<?> task);
}
|
package me.ThaH3lper.com;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import me.ThaH3lper.com.Crehop.EventListener;
import me.ThaH3lper.com.Grades.Grade;
import me.ThaH3lper.com.Grades.Wave;
import me.ThaH3lper.com.Portals.Portal;
import me.ThaH3lper.com.Reward.PlayerTimes;
import me.ThaH3lper.com.Reward.Rewards;
import me.ThaH3lper.com.dungeon.SaveLoad;
import me.ThaH3lper.com.dungeon.SpawnEntitys;
import me.ThaH3lper.com.dungeon.TempletFloor;
import me.ThaH3lper.com.dungeon.Tower;
import me.ThaH3lper.com.dungeon.commands.BlockListener;
import me.ThaH3lper.com.dungeon.commands.CommandHandle;
import me.ThaH3lper.com.party.CommandParty;
import me.ThaH3lper.com.party.PartyListener;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.java.JavaPlugin;
public class Dungeon extends JavaPlugin
{
public Logger logger = Logger.getLogger("Minecraft");
public PlayerListener pl = new PlayerListener(this);
public PartyListener pal = new PartyListener();
public BlockListener blocklistener = new BlockListener(this);
public static Dungeon plugin;
public List<TempletFloor> templetFloorList = new ArrayList<TempletFloor>();
public List<Tower> towerList = new ArrayList<Tower>();
public List<Portal> portalList = new ArrayList<Portal>();
public List<Wave> waveList = new ArrayList<Wave>();
public DungeonHandler dungeonHandler;
public SaveLoad saveload;
public Save settings, save, options, waves, player;
public SpawnEntitys spawnEntitys;
public PlayerTimes playerTimes;
public Rewards rewEasy, rewNormal, rewHard, rewTop;
public Grade graEasy, graNormal, graHard;
public Location exit;
public void onDisable()
{
PluginDescriptionFile pdfFile = getDescription();
this.logger.info(pdfFile.getName() + " Has Been Disabled!");
saveload.SaveAll();
}
public void onEnable()
{
getServer().getPluginManager().registerEvents(this.pl, this);
getServer().getPluginManager().registerEvents(this.pal, this);
getServer().getPluginManager().registerEvents(this.blocklistener, this);
getServer().getPluginManager().registerEvents(new EventListener(this), this);
PluginDescriptionFile pdfFile = getDescription();
this.logger.info(pdfFile.getName() + " Version " + pdfFile.getVersion() + " Has Been Enabled!");
settings = new Save(this, "Settings.yml");
options = new Save(this, "Options.yml");
save = new Save(this, "Save.yml");
waves = new Save(this, "Waves.yml");
player = new Save(this, "PlayerData.yml");
dungeonHandler = new DungeonHandler(this);
dungeonHandler.load();
spawnEntitys = new SpawnEntitys(this);
saveload = new SaveLoad(this);
rewEasy = new Rewards("Easy.Reward", this);
rewNormal = new Rewards("Normal.Reward", this);
rewHard = new Rewards("Hard.Reward", this);
//rewTop = new Rewards("TopKiller", this);
LoadGrades();
playerTimes = new PlayerTimes(this);
getCommand("dungeon").setExecutor(new CommandHandle(this));
getCommand("party").setExecutor(new CommandParty(this));
for(Tower t : towerList)
{
if(t.hasTower)
t.Generate(0, 1);
}
}
public void LoadGrades()
{
graEasy = new Grade((float)options.getCustomConfig().getDouble("Easy.Boost"), options.getCustomConfig().getInt("Easy.Levels"), options.getCustomConfig().getStringList("Easy.Level"), options.getCustomConfig().getInt("Easy.Lives"), this);
graNormal = new Grade((float)options.getCustomConfig().getDouble("Normal.Boost"), options.getCustomConfig().getInt("Normal.Levels"), options.getCustomConfig().getStringList("Normal.Level"), options.getCustomConfig().getInt("Normal.Lives"), this);
graHard = new Grade((float)options.getCustomConfig().getDouble("Hard.Boost"), options.getCustomConfig().getInt("Hard.Levels"), options.getCustomConfig().getStringList("Hard.Level"), options.getCustomConfig().getInt("Hard.Lives"), this);
}
} |
package SecondTask;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class DataWrite {
public static void main(String[] args) {
List<Person> people = new ArrayList<>();
people.add(new Person("Samat", "Kadyrov", 19, true));
people.add(new Person("Sergey", "Gordeev", 19, true));
people.add(new Person("Marat", "Shigabutdinov", 18, true));
people.add(new Person("Bulat", "Gimazov", 19, true));
people.add(new Person("Radimir", "Mamedov", 19, true));
write(people);
}
private static void write(List<Person> people) {
try (FileOutputStream fileOutputStream = new FileOutputStream("data.txt")) {
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
DataOutputStream dataOutputStream = new DataOutputStream(bufferedOutputStream);
for (Person person : people) {
String s = person + "\n";
dataOutputStream.write(s.getBytes());
}
dataOutputStream.close();
bufferedOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
/*
* The contents of this file are subject to the GNU Lesser General Public
* License Version 2.1 (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.gnu.org/copyleft/lesser.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Developer:
* Todd Ditchendorf, todd@ditchnet.org
*
*/
/**
* @author Todd Ditchendorf
* @version 0.8
* @since 0.8
*/
package it.blueocean.acanto.taglibrary.jsp.taglib.tabs.handler;
import it.blueocean.acanto.taglibrary.jsp.taglib.tabs.listener.TabServletContextListener;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.SimpleTagSupport;
/**
* @author Todd Ditchendorf
* @since 0.8
*
* JSP Tag that renders XHTML </code>script</code> and
* </code>style</code> elements that link to the CSS and JavaScript
* resources necessary to render the tab components on the current page.
* The resources that are linked to are the resources placed in a
* directory named </code>/org.ditchnet.taglib/</code> in the web app's
* root directory. These resources were placed there by the
* {@link org.ditchnet.jsp.taglib.tabs.listener.TabServletContextListener}
* .
*/
public final class TabConfigTag extends SimpleTagSupport
{
private String contextPath;
public void doTag() throws JspException, IOException
{
StringBuffer buff = new StringBuffer();
findContextPath();
renderScriptTag(buff);
renderStyleTag(buff);
getJspContext().getOut().print(buff);
}
private void findContextPath()
{
PageContext pageContext = (PageContext) getJspContext();
HttpServletRequest req = (HttpServletRequest) pageContext.getRequest();
contextPath = req.getContextPath();
}
private void renderScriptTag(final StringBuffer buff)
{
String uri = getEncodedContextRelativePath(TabServletContextListener.SCRIPT_URI);
buff.append("\n\n\t<script type=\"text/javascript\" ")
.append("src=\"")
.append(uri)
.append("\">")
.append("</script>\n");
}
private void renderStyleTag(final StringBuffer buff)
{
String uri = getEncodedContextRelativePath(TabServletContextListener.STYLE_URI);
buff.append("\t<link type=\"text/css\" rel=\"stylesheet\" ")
.append("href=\"")
.append(uri)
.append("\" />\n\n");
}
private String getEncodedContextRelativePath(final String uri)
{
return contextPath + uri;
}
}
|
package employeeScheduler.model;
import java.util.HashMap;
import java.util.Map;
/**
* Enum helping to use specific acceptance Level
*/
public enum AcceptanceLevel {
VERY_LOW(0.01),
LOW(0.1),
MEDIUM(0.4),
HIGH(0.6),
VERY_HIGH(1);
private double value;
private static Map map = new HashMap<>();
private AcceptanceLevel(double value) {
this.value = value;
}
static {
for (AcceptanceLevel acceptanceLevel : AcceptanceLevel.values()) {
map.put(acceptanceLevel.value, acceptanceLevel);
}
}
public static AcceptanceLevel valueOf(int acceptanceLevel) {
return (AcceptanceLevel) map.get(acceptanceLevel);
}
public double getValue() {
return value;
}
}
|
package com.cwelth.industrialessentials.tileentities;
import com.cwelth.industrialessentials.blocks.Anvil;
import com.cwelth.industrialessentials.inits.IEContent;
import com.cwelth.industrialessentials.inits.InitCommon;
import com.cwelth.industrialessentials.networking.AnvilSync;
import com.cwelth.industrialessentials.networking.NetworkingSetup;
import com.cwelth.industrialessentials.recipes.AnvilRecipe;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.play.server.SUpdateTileEntityPacket;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.Hand;
import net.minecraft.util.SoundCategory;
import net.minecraft.util.SoundEvents;
import net.minecraftforge.fml.network.PacketDistributor;
import javax.annotation.Nullable;
public class AnvilTE extends TileEntity {
private ItemStack containedItem = ItemStack.EMPTY;
private int currentHits = 0;
private ItemStack resultStack = ItemStack.EMPTY;
private String recipe = "";
public boolean clientOnLookAt = false;
public AnvilTE() {
super(IEContent.ANVIL_TE.get());
}
@Override
public void read(CompoundNBT compound) {
if(compound.contains("containedItem"))containedItem = ItemStack.read(compound.getCompound("containedItem"));
if(compound.contains("currentHits"))currentHits = compound.getInt("currentHits");
if(compound.contains("resultStack"))resultStack = ItemStack.read(compound.getCompound("resultStack"));
if(compound.contains("recipe"))recipe = compound.getString("recipe");
if(compound.contains("clientOnLookAt"))clientOnLookAt = compound.getBoolean("clientOnLookAt");
super.read(compound);
}
@Override
public CompoundNBT write(CompoundNBT compound) {
compound.put("containedItem", containedItem.serializeNBT());
compound.putInt("currentHits", currentHits);
compound.put("resultStack", resultStack.serializeNBT());
compound.putString("recipe", recipe);
compound.putBoolean("clientOnLookAt", clientOnLookAt);
return super.write(compound);
}
public boolean isHammerPresent()
{
return !containedItem.isEmpty() && ( containedItem.getItem() == IEContent.HAMMER_PART.get() || containedItem.getItem() == IEContent.HAMMER_DIAMOND_PART.get() );
}
public ItemStack getContainedItem()
{
return containedItem;
}
public void setCurrentHits(int currentHits)
{
this.currentHits = currentHits;
markDirty();
}
public boolean hasValidRecipe()
{
return !resultStack.isEmpty();
}
public String getRecipe()
{
return recipe;
}
public int getCurrentHits()
{
return currentHits;
}
public ItemStack interact(ItemStack itemStack)
{
if(!containedItem.isEmpty())
{
if(itemStack.isEmpty())
{
ItemStack retVal = containedItem.copy();
if(isHammerPresent())
getWorld().setBlockState(getPos(), getWorld().getBlockState(getPos()).with(Anvil.HAMMER_PRESENT, false), 2);
containedItem = ItemStack.EMPTY;
currentHits = 0;
recipe = "";
resultStack = ItemStack.EMPTY;
markDirty();
world.notifyBlockUpdate(getPos(), getBlockState(), getBlockState(), 2);
return retVal;
} else {
if(itemStack.getItem() == containedItem.getItem())
{
if(itemStack.getCount() + containedItem.getCount() <= itemStack.getMaxStackSize())
{
itemStack.grow(containedItem.getCount());
containedItem = ItemStack.EMPTY;
currentHits = 0;
recipe = "";
resultStack = ItemStack.EMPTY;
markDirty();
world.notifyBlockUpdate(getPos(), getBlockState(), getBlockState(), 2);
return itemStack;
}
}
return itemStack;
}
} else
{
if(itemStack.isEmpty())
return ItemStack.EMPTY;
else
{
containedItem = itemStack.copy();
containedItem.setCount(1);
markDirty();
if(isHammerPresent())
getWorld().setBlockState(getPos(), getWorld().getBlockState(getPos()).with(Anvil.HAMMER_PRESENT, true), 2);
else
{
AnvilRecipe recipe = InitCommon.anvilRecipes.getMatchedRecipe(containedItem);
if(recipe != null)
{
this.recipe = recipe.hits;
currentHits = 0;
resultStack = recipe.output.copy();
markDirty();
}
}
itemStack.shrink(1);
world.notifyBlockUpdate(getPos(), getBlockState(), getBlockState(), 2);
return itemStack;
}
}
}
public boolean bash(Hand hand)
{
if(!containedItem.isEmpty())
{
if(!isHammerPresent())
{
//Process recipe
if(!resultStack.isEmpty())
{
if(recipe.charAt(currentHits) == 'R' && hand == Hand.OFF_HAND || recipe.charAt(currentHits) == 'L' && hand == Hand.MAIN_HAND) {
currentHits++;
if(hand == Hand.OFF_HAND)
world.playSound(null, getPos(), SoundEvents.BLOCK_ANVIL_PLACE, SoundCategory.BLOCKS, 1.0F, world.rand.nextFloat()*.1F + 0.6F);
else
world.playSound(null, getPos(), SoundEvents.BLOCK_ANVIL_PLACE, SoundCategory.BLOCKS, 1.0F, world.rand.nextFloat()*.1F + 0.8F);
}
else {
currentHits = 0;
world.playSound(null, getPos(), SoundEvents.ENTITY_ITEM_BREAK, SoundCategory.BLOCKS, 1.0F, 0.6F);
markDirty();
NetworkingSetup.INSTANCE.send(PacketDistributor.NEAR.with(PacketDistributor.TargetPoint.p(getPos().getX(), getPos().getY(), getPos().getZ(), 16D, world.getDimension().getType())), new AnvilSync(currentHits, getPos()));
return false;
}
if(currentHits == recipe.length())
{
containedItem = resultStack.copy();
resultStack = ItemStack.EMPTY;
currentHits = 0;
recipe = "";
world.notifyBlockUpdate(getPos(), getBlockState(), getBlockState(), 2);
}
markDirty();
NetworkingSetup.INSTANCE.send(PacketDistributor.NEAR.with(PacketDistributor.TargetPoint.p(getPos().getX(), getPos().getY(), getPos().getZ(), 16D, world.getDimension().getType())), new AnvilSync(currentHits, getPos()));
return true;
}
}
}
return true;
}
@Nullable
@Override
public SUpdateTileEntityPacket getUpdatePacket() {
CompoundNBT nbtTag = new CompoundNBT();
nbtTag = write(nbtTag);
return new SUpdateTileEntityPacket(getPos(), 1, nbtTag);
}
@Override
public void onDataPacket(NetworkManager net, SUpdateTileEntityPacket pkt) {
read(pkt.getNbtCompound());
}
@Override
public CompoundNBT getUpdateTag() {
CompoundNBT nbtTag = new CompoundNBT();
nbtTag = write(nbtTag);
return nbtTag;
}
@Override
public void handleUpdateTag(CompoundNBT tag) {
read(tag);
}
}
|
package action.com.task;
import com.opensymphony.xwork2.ActionSupport;
import net.sf.json.JSONObject;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;
import pojo.DAO.ProjectDAO;
import pojo.DAO.TaskDAO;
import pojo.businessObject.TaskBO;
import pojo.valueObject.DTO.TaskDTO;
import pojo.valueObject.domain.ProjectVO;
import tool.BeanFactory;
import tool.JSONHandler;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.Map;
/**
* Created by GR on 2017/4/16.
*/
public class GetMyTaskAction extends ActionSupport implements SessionAware, ServletRequestAware, ServletResponseAware {
private HttpServletRequest request;
private HttpServletResponse response;
private Map<String, Object> session;
private JSONObject jsonObject;
//jsp
private Integer projectId;
@Override
public String execute() throws Exception {
try {
ProjectDAO projectDAO = BeanFactory.getBean("projectDAO", ProjectDAO.class);
TaskBO taskBO = BeanFactory.getBean("taskBO", TaskBO.class);
ProjectVO projectVO = projectDAO.getProjectVO(projectId);
if (projectVO != null) {
jsonObject = taskBO.getMyTask(projectVO);
JSONHandler.sendJSON(jsonObject, response);
System.out.println("获取我的任务");
System.out.println(jsonObject);
return "success";
}else{
jsonObject.put("result","SQLException");
JSONHandler.sendJSON(jsonObject, response);
return "fail";
}
}catch(Exception e){
jsonObject.put("result","SQLException");
JSONHandler.sendJSON(jsonObject, response);
return "fail";
}
}
@Override
public void setServletRequest(HttpServletRequest request) {
this.request = request;
try {
request.setCharacterEncoding("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
@Override
public void setServletResponse(HttpServletResponse response) {
this.response = response;
this.response.setCharacterEncoding("UTF-8");
}
@Override
public void setSession(Map<String, Object> session) {
this.session = session;
}
public JSONObject getJsonObject() {
return jsonObject;
}
public void setJsonObject(JSONObject jsonObject) {
this.jsonObject = jsonObject;
}
public Integer getProjectId() {
return projectId;
}
public void setProjectId(Integer projectId) {
this.projectId = projectId;
}
}
|
package com.pagelibrary.com.ranfordbank;
import org.openqa.selenium.WebElement;
import testbase.base;
public class Employee extends base
{
public static WebElement Employee_click()
{
return driver.findElement(getElement("Employee"));
}
public static WebElement newemployee_click()
{
return driver.findElement(getElement("newemployee"));
}
public static WebElement employername_name()
{
return driver.findElement(getElement("employername"));
}
public static WebElement loginpassword_password()
{
return driver.findElement(getElement("loginpassword"));
}
public static WebElement Employee_role()
{
return driver.findElement(getElement("role"));
}
public static WebElement Employee_branch()
{
return driver.findElement(getElement("branch1"));
}
public static WebElement employer_submit3()
{
return driver.findElement(getElement("submit3"));
}
}
|
package kompressor.huffman.structures;
public class HuffmanNode {
private Character c;
private int freq;
private HuffmanNode parent;
private HuffmanNode right;
private HuffmanNode left;
private int id; //equals:ia varten, voidaan joutua verrata solmuja joiden c ja freq ovat samat
private static int num = 0;
public HuffmanNode(Character c, int freq) {
this.c = c;
this.freq = freq;
id = ++num;
}
public HuffmanNode(Character c) {
this.c = c;
}
public Character getCharacter() {
return c;
}
public int getFrequency() {
return freq;
}
public HuffmanNode getParent() {
return parent;
}
public HuffmanNode getLeft() {
return left;
}
public HuffmanNode getRight() {
return right;
}
public void setParent(HuffmanNode n) {
this.parent = n;
}
public void setLeft(HuffmanNode n) {
this.left = n;
}
public void setRight(HuffmanNode n) {
this.right = n;
}
@Override
public boolean equals(Object o) {
if (o instanceof HuffmanNode) {
HuffmanNode n = (HuffmanNode) o;
if (id == n.id) return true;
}
return false;
}
} |
package strings_stringbuffer;
import java.util.Scanner;
public class Program5 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String str=sc.nextLine();
System.out.println(str.substring(1,str.length()-1));
}
}
|
package com.company;
import java.util.Date;
public class ComplaintTicket extends Ticket{
//Constructor
public ComplaintTicket(String desciption, int roomID, Date openTime, boolean complete)
{
super(desciption, roomID, openTime, complete);
}
}
|
package webDriveDemo;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeTest;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterTest;
public class OpenBrowser
{
WebDriver driver;
@BeforeTest
public void beforeTest()
{
System.setProperty("webdriver.chrome.driver", "Resources/chromedriver.exe");
//open chrome browser
driver = new ChromeDriver();
//to maximize the window
driver.manage().window().maximize();
}
@Test
public void f() throws InterruptedException
{
//navigate to website
driver.get("https://mvnrepository.com/");
//wait for 3 seconds
Thread.sleep(3000);
}
@AfterTest
public void afterTest()
{
//close the browser
driver.close();
}
}
|
package com.perfect.web.controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.baomidou.mybatisplus.plugins.Page;
import com.perfect.core.bean.DataGrid;
import com.perfect.core.bean.Pager;
import com.perfect.entity.User;
import com.perfect.web.form.UserForm;
import com.perfect.web.service.UserService;
/**
* <p>
* 用户表 前端控制器
* </p>
*
* @author Ben.
* @since 2017-03-15
*/
@Controller
@RequestMapping("/user")
public class UserController extends BaseController {
@Autowired
private UserService userService;
@RequestMapping(value = "/index", method = RequestMethod.GET)
public String index(ModelMap modelMap, HttpServletRequest request) {
return "/user/index";
}
@ResponseBody
@RequestMapping(value = "/list", method = RequestMethod.POST)
public DataGrid list(Pager pager, UserForm form) {
Page<User> page = this.initQueryPage(pager);
return toJsonDataGrid(this.userService.pageList(page, form));
}
@RequestMapping(value = "/add", method = RequestMethod.GET)
public String add() {
return "/user/add";
}
@RequestMapping(value = "/edit", method = RequestMethod.GET)
public String edit() {
return "/user/edit";
}
}
|
/*
* 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 com.navegador.recreio.entity;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* @author snnangolaPC
*/
@Entity
@Table(name = "competencia")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Competencia.findAll", query = "SELECT c FROM Competencia c"),
@NamedQuery(name = "Competencia.findByIdCompetencia", query = "SELECT c FROM Competencia c WHERE c.idCompetencia = :idCompetencia"),
@NamedQuery(name = "Competencia.findByDescricaoCompetenciaCategoriaNavegadorRecreio", query = "SELECT c FROM Competencia c WHERE c.descricaoCompetenciaCategoriaNavegadorRecreio = :descricaoCompetenciaCategoriaNavegadorRecreio")})
public class Competencia implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id_competencia")
private Integer idCompetencia;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 510)
@Column(name = "descricao_competencia_categoria_navegador_recreio")
private String descricaoCompetenciaCategoriaNavegadorRecreio;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "competencia")
private List<Categoria> categoriaList;
//@Transient
//Categoria categoria;
//@Transient
//NavegadorRecreio navegadorRecreio;
public Competencia() {
// categoria = new Categoria();
// navegadorRecreio = new NavegadorRecreio();
}
public Competencia(Integer idCompetencia) {
this.idCompetencia = idCompetencia;
}
public Competencia(Integer idCompetencia, String descricaoCompetenciaCategoriaNavegadorRecreio) {
this.idCompetencia = idCompetencia;
this.descricaoCompetenciaCategoriaNavegadorRecreio = descricaoCompetenciaCategoriaNavegadorRecreio;
}
public Integer getIdCompetencia() {
return idCompetencia;
}
public void setIdCompetencia(Integer idCompetencia) {
this.idCompetencia = idCompetencia;
}
public String getDescricaoCompetenciaCategoriaNavegadorRecreio() {
return descricaoCompetenciaCategoriaNavegadorRecreio;
}
public void setDescricaoCompetenciaCategoriaNavegadorRecreio(String descricaoCompetenciaCategoriaNavegadorRecreio) {
this.descricaoCompetenciaCategoriaNavegadorRecreio = descricaoCompetenciaCategoriaNavegadorRecreio;
}
@XmlTransient
public List<Categoria> getCategoriaList() {
return categoriaList;
}
public void setCategoriaList(List<Categoria> categoriaList) {
this.categoriaList = categoriaList;
}
@Override
public int hashCode() {
int hash = 0;
hash += (idCompetencia != null ? idCompetencia.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Competencia)) {
return false;
}
Competencia other = (Competencia) object;
if ((this.idCompetencia == null && other.idCompetencia != null) || (this.idCompetencia != null && !this.idCompetencia.equals(other.idCompetencia))) {
return false;
}
return true;
}
@Override
public String toString() {
return "com.navegador.recreio.entity.Competencia[ idCompetencia=" + idCompetencia + " ]";
}
}
|
package com.t.admin.request;
import lombok.Getter;
import lombok.Setter;
import java.util.Date;
import java.util.Map;
/**
* @author tb
* @date 2018/12/17 14:31
*/
@Getter
@Setter
public class JobQueueReq extends PageReq {
// ------------ 下面是查询条件值 ---------------
private String jobId;
private String jobType;
private String taskId;
private String realTaskId;
private String submitNodeGroup;
private String taskTrackerNodeGroup;
private Date startGmtCreated;
private Date endGmtCreated;
private Date startGmtModified;
private Date endGmtModified;
// ------------ 下面是能update的值 -------------------
private String cronExpression;
private Boolean needFeedback;
private Map<String, String> extParams;
private Date triggerTime;
private Integer priority;
private Integer maxRetryTimes;
private Integer repeatCount;
private Long repeatInterval;
private Boolean relyOnPrevCycle;
}
|
package com.appspot.smartshop.map;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.location.Address;
import android.location.Geocoder;
import android.util.Log;
import com.appspot.smartshop.R;
import com.appspot.smartshop.utils.Global;
import com.appspot.smartshop.utils.RestClient;
import com.google.android.maps.GeoPoint;
public class MapService {
public static final String TAG = "[MapService]";
public static final String GET_DIRECTION_URL = "http://maps.google.com/maps/api/directions/json?" +
"origin=%f,%f" +
"&destination=%f,%f" +
"&sensor=true&language=vi&units=metric";
public static DirectionResult getDirectionResult(
double latitude1, double longtitude1,
double latitude2, double longtitude2) {
String url = String.format(GET_DIRECTION_URL, latitude1, longtitude1, latitude2, longtitude2);
// parse direction
DirectionParser directionParser = new DirectionParser() {
@Override
public void onSuccess(JSONObject json) throws JSONException {
// process response status
String status = json.getString("status");
if (!status.equals("OK")) {
String error = null;
if (status.equals("NOT_FOUND") || status.equals("ZERO_RESULTS")) {
error = Global.application.getString(R.string.errCantGetDirection);
} else {
error = Global.application.getString(R.string.errGetDirection);
}
result.instructions = new String[] {error};
result.hasError = true;
return;
}
/*
* routes[]
legs[]
steps[]
html_instructions
*/
JSONArray arrRoutes = json.getJSONArray("routes");
// no routes found
if (arrRoutes.length()==0) {
result.instructions = new String[] {
Global.application.getString(R.string.errCantGetDirection)};
result.hasError = true;
return;
}
JSONArray arrLegs = arrRoutes.getJSONObject(0).getJSONArray("legs");
JSONObject firstLeg = arrLegs.getJSONObject(0);
JSONArray arrSteps = firstLeg.getJSONArray("steps");
int len = arrSteps.length();
result.instructions = new String[len];
// result.points = new GeoPoint[len + 1];
result.points = new LinkedList<GeoPoint>();
JSONObject leg = null;
// JSONObject location = null;
// get instructions
for (int i = 0; i < len; ++i) {
leg = arrSteps.getJSONObject(i);
// location = leg.getJSONObject("start_location");
String encoded = leg.getJSONObject("polyline").getString("points");
result.points.addAll(decodePoly(encoded));
result.instructions[i] = leg.getString("html_instructions");
// result.points[i] = new GeoPoint(
// (int) (location.getDouble("lat") * 1E6),
// (int) (location.getDouble("lng") * 1E6));
}
// location = leg.getJSONObject("end_location");
// result.points[len] = new GeoPoint(
// (int) (location.getDouble("lat") * 1E6),
// (int) (location.getDouble("lng") * 1E6));
// distance and duration info
JSONObject distance = firstLeg.getJSONObject("distance");
if (distance != null) {
result.distance = distance.getString("text");
}
JSONObject duration = firstLeg.getJSONObject("duration");
if (duration != null) {
result.duration = duration.getString("text");
}
}
@Override
public void onFailure(String message) {
String error = Global.application.getString(R.string.errGetDirection);
result.instructions = new String[] {error};
result.hasError = true;
}
};
// return direction result
RestClient.getData(url, directionParser);
return directionParser.result;
}
private static List<GeoPoint> decodePoly(String encoded) {
List<GeoPoint> poly = new ArrayList<GeoPoint>();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
GeoPoint p = new GeoPoint((int) (((double) lat / 1E5) * 1E6),
(int) (((double) lng / 1E5) * 1E6));
poly.add(p);
}
return poly;
}
public static GeoPoint locationToGeopoint(String locationName) {
Geocoder geocoder = new Geocoder(Global.application);
try {
Log.d(TAG, "Find address of " + locationName);
List<Address> addresses = geocoder.getFromLocationName(locationName, 5);
if (addresses != null && addresses.size() > 0) {
Address add = addresses.get(0);
return new GeoPoint((int) (add.getLatitude() * 1E6), (int) (add.getLongitude() * 1E6));
} else {
Log.d(TAG, "No address found");
return null;
}
} catch (IOException e) {
Log.e(TAG, "Cannot get location from server");
e.printStackTrace();
}
return null;
}
}
|
package com.mi9dev.soapclient;
import java.net.MalformedURLException;
import java.net.URL;
import com.mi9dev.customerorders.CustomerOrders;
import com.mi9dev.customerorders.CustomerOrdersService;
import com.mi9dev.customerorders.GetOrdersRequest;
import com.mi9dev.customerorders.GetOrdersResponse;
public class CustomerOrdersWSClient {
public GetOrdersResponse getOrdersByCustomerId(GetOrdersRequest getOrdersRequest) throws MalformedURLException {
CustomerOrdersService customerOrdersService = new CustomerOrdersService(
new URL("http://localhost:8080/webservices-approach-topdown/services/customerOrders?wsdl"));
CustomerOrders customerOrdersSOAP = customerOrdersService.getCustomerOrdersSOAP();
GetOrdersResponse ordersResponse = customerOrdersSOAP.getOrders(getOrdersRequest);
return ordersResponse;
}
}
|
package core.path;
import core.graph.Graph;
import java.util.List;
public interface PathFindingAlgorithm {
void solve(Graph g, int start);
boolean checkPath(int end);
List<Integer> getBacktrace(int start, int end);
}
|
package com.alibaba.druid.sql.dialect.mysql.ast.statement;
import com.alibaba.druid.sql.ast.SQLName;
import com.alibaba.druid.sql.dialect.mysql.ast.FullTextType;
import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlASTVisitor;
public class MysqlShowCreateFullTextStatement extends MySqlStatementImpl implements MySqlShowStatement {
private FullTextType type;
private SQLName name;
public SQLName getName() {
return name;
}
public void setName(SQLName name) {
if (name != null) {
name.setParent(this);
}
this.name = name;
}
public FullTextType getType() {
return type;
}
public void setType(FullTextType type) {
this.type = type;
}
@Override
public void accept0(MySqlASTVisitor visitor) {
visitor.visit(this);
visitor.endVisit(this);
}
}
|
package com.codigo.smartstore.xbase.database.structure.table;
public interface IXbDataTable {
}
|
package liu.lang.Class;
/*getClassLoader():ClassLoader 获取该类被加载时所用的类加载器。
*
*/
public class About_getClassLoader {
public static void main(String[] args) throws ClassNotFoundException {
System.out.println(About_getClassLoader.class.getClassLoader().toString());
}
}
|
package com.gutotech.consultacep.presenter;
import android.app.Activity;
import android.content.Context;
import android.database.sqlite.SQLiteConstraintException;
import com.gutotech.consultacep.Contract;
import com.gutotech.consultacep.R;
import com.gutotech.consultacep.db.AppDatabase;
import com.gutotech.consultacep.model.GetZipCodeTask;
import com.gutotech.consultacep.db.ZipCodeDao;
import com.gutotech.consultacep.db.ZipCodeEntity;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class MainPresenter implements Contract.Presenter {
private Contract.View mView;
private AppDatabase database;
private ZipCodeDao zipCodeDAO;
private List<ZipCodeEntity> zipCodeEntityList;
public MainPresenter(Contract.View view) {
mView = view;
database = AppDatabase.getInstance((Context) mView);
zipCodeDAO = database.getZipCodeDAO();
zipCodeEntityList = new ArrayList<>();
}
@Override
public void searchZipCode(String zipCode) {
if (isFormatValidZipCode(zipCode)) {
URL url = createURL(zipCode);
if (url != null)
new GetZipCodeTask(getZipCodeListener, this).execute(url);
} else
mView.setError(R.string.invalid_zip_code);
}
private boolean isFormatValidZipCode(String zipCode) {
return zipCode.matches("\\d{8}");
}
private URL createURL(String query) {
try {
return new URL(((Activity) mView).getString(R.string.baseUrl) + query);
} catch (MalformedURLException e) {
e.printStackTrace();
}
return null;
}
private final GetZipCodeTask.GetZipCodeListener getZipCodeListener = new GetZipCodeTask.GetZipCodeListener() {
@Override
public void onZipCodeReceived(ZipCodeEntity zipCodeEntity) {
if (zipCodeEntity != null) {
mView.displayZipCodeInfo(zipCodeEntity);
insertZipCode(zipCodeEntity);
mView.hideProgressBar();
} else {
mView.hideProgressBarAndGrid();
mView.setError(R.string.zip_code_not_found);
}
}
};
@Override
public List<ZipCodeEntity> getZipCodeEntityList() {
return zipCodeEntityList;
}
@Override
public void getAllZipCodes() {
zipCodeEntityList.clear();
zipCodeEntityList.addAll(zipCodeDAO.getAll());
mView.updateList();
}
@Override
public void deleteZipCode(int position) {
zipCodeDAO.delete(getZipCodeEntityList().get(position));
getZipCodeEntityList().remove(position);
mView.updateList();
}
@Override
public void insertZipCode(ZipCodeEntity zipCodeEntity) {
try {
zipCodeDAO.insert(zipCodeEntity);
} catch (SQLiteConstraintException e) { // if exception occurred Postal Code already in List and in database
zipCodeEntity.dateSearched = new Date().getTime();
zipCodeDAO.updateDateSearched(zipCodeEntity);
removeZipCodeFromList(zipCodeEntity);
}
getZipCodeEntityList().add(0, zipCodeEntity);
mView.updateList();
}
private void removeZipCodeFromList(ZipCodeEntity zipCodeEntity) {
for (ZipCodeEntity currentZipCodeEntity : getZipCodeEntityList()) {
if (currentZipCodeEntity.zipCode.equals(zipCodeEntity.zipCode)) {
getZipCodeEntityList().remove(currentZipCodeEntity);
break;
}
}
}
@Override
public void showProgressBar() {
mView.showProgressBar();
}
@Override
public void close() {
database.close();
}
}
|
package com.learn.leetcode.week3;
public class SolutionMajorityElement {
/**
* 给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。
*
* 你可以假设数组是非空的,并且给定的数组总是存在多数元素。
*
* @param nums
* @return
*/
public static int majorityElement(int[] nums) {
if(0 == nums.length)
return -1;
int major = nums[0];
int count = 1;
for (int i = 1; i < nums.length; i++) {
if(major!=nums[i]){
count--;
}else{
count++;
}
if(0 > count){
major = nums[i];
count = 1;
}
}
return major;
}
}
|
package edu.ifma.programacaoextrema;
import edu.ifma.programacaoextrema.model.Aluno;
import edu.ifma.programacaoextrema.model.Banca;
import edu.ifma.programacaoextrema.model.Professor;
import edu.ifma.programacaoextrema.model.Portaria;
import edu.ifma.programacaoextrema.service.BancaService;
import edu.ifma.programacaoextrema.util.exception.MontagemBancaException;
public class App {
public static void main(String[] args) throws MontagemBancaException {
BancaService bancaService = new BancaService();
Professor professor = new Professor();
professor.setId(3L);
professor.setMatricula("SI354654");
professor.setNome("Jeane Ferreira");
professor.setCurso("Sistemas de Informação");
Aluno aluno = new Aluno(professor);
aluno.setId(1L);
aluno.setMatricula("SI164578");
aluno.setNome("Daiane Silva");
aluno.setCurso("Sistemas de Informação");
aluno.atualizaPercentualConclusao(0.9);
Banca banca = bancaService.montaBanca(aluno);
Portaria portaria = bancaService.consultaPortaria();
System.out.println("BANCA: " + banca.toString());
System.out.println("PORTARIA: " + portaria);
}
}
|
package skollur1.msse.asu.edu.graduatestudentassignment;
/*
* Copyright 2016 Supraj Kolluri,
*
*
* The contents of the file can only be used for the purpose of grading and reviewing.
* The instructor and the University have the right to build and evaluate the
* software package for the purpose of determining the grade and program assessment.
*
*
* @author Supraj Kolluri mailto:supraj.kolluri@asu.edu
* Software Engineering, CIDSE, IAFSE, ASU Poly
* @version April 28, 2016
*/
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import com.facebook.AccessToken;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.login.widget.ProfilePictureView;
import org.json.JSONObject;
/*
This class allows us to connect to Facebook using the Facebook graph API and pull user details.
Currently the profile picture, name, date of birth, email address, gender and location of the user are displayed.
Please note this information will only be visible if it is specified in the users facebook profile
and the visibility is set to public.
*/
public class DisplayFBDetails extends AppCompatActivity {
private TextView name;
private TextView dob;
private TextView email;
private TextView location;
private TextView gender;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_fb_details);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
name = (TextView)findViewById(R.id.nameview);
dob = (TextView)findViewById(R.id.dobview);
email = (TextView)findViewById(R.id.emailview);
location = (TextView)findViewById(R.id.locationview);
gender = (TextView)findViewById(R.id.genderview);
Intent intent = getIntent();
String userid = intent.getStringExtra("userid");
//Getting the users profile picture
ProfilePictureView profilePictureView;
profilePictureView = (ProfilePictureView) findViewById(R.id.image);
profilePictureView.setProfileId(userid);
//Submitting a new Graph request which will execute as an async task to pull users details.
GraphRequest request = GraphRequest.newMeRequest(
AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(JSONObject object, GraphResponse response) {
Log.v("LoginActivity", response.toString());
try {
name.setText(object.getString("name"));
email.setText(object.getString("email"));
dob.setText(object.getString("birthday"));
gender.setText(object.getString("gender"));
if (object.getJSONObject("location") == null) {
location.setText("NA");
} else {
location.setText(object.getJSONObject("location").getString("name"));
}
} catch (Exception e) {
Log.e("Error ", e.getMessage());
}
}
});
Bundle parameters = new Bundle();
//Setting parameters to the request.
parameters.putString("fields", "name,email,gender,birthday,location");
request.setParameters(parameters);
request.executeAsync();
}
//Adding back button to the page
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.backmenu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem menuItem){
switch (menuItem.getItemId()){
case R.id.backMenu:
this.finish();
default:
super.onOptionsItemSelected(menuItem);
}
return true;
}
}
|
package com.zc.pivas.statistics.bean.medicalAdvice;
import java.util.ArrayList;
import java.util.List;
/**
* 按病区和状态统计
*
* @author jagger
* @version 1.0
*/
public class StaticDoctorDeptStatusBarBean {
/**
* 病区名称列表
*/
private List<String> deptNameList = new ArrayList<String>();
/**
* 医嘱状态 -> 医生状态 统计
*/
private List<StaticDoctorStatus2DeptBean> status2DeptList = new ArrayList<StaticDoctorStatus2DeptBean>();
public List<String> getDeptNameList() {
return deptNameList;
}
public void setDeptNameList(List<String> deptNameList) {
this.deptNameList = deptNameList;
}
public void addDeptNameList(String deptName) {
this.deptNameList.add(deptName);
}
public List<StaticDoctorStatus2DeptBean> getStatus2DeptList() {
return status2DeptList;
}
public void setStatus2DeptList(List<StaticDoctorStatus2DeptBean> status2DeptList) {
this.status2DeptList = status2DeptList;
}
public void setStatus2DeptList(StaticDoctorStatus2DeptBean status2Dept) {
this.status2DeptList.add(status2Dept);
}
}
|
package CollectionProgram;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class keyInaHashMap {
public static void main(String[] args)
{
HashMap<Integer, String>
map = new HashMap<>();
map.put(1, "Nirbhay");
map.put(2, "Gupta");
map.put(3, "Sdet");
int keyToBeChecked = 2;
System.out.println("HashMap: "
+ map);
Iterator<Map.Entry<Integer, String> >
iterator = map.entrySet().iterator();
boolean isKeyPresent = false;
while (iterator.hasNext()) {
Map.Entry<Integer, String>
entry
= iterator.next();
if (keyToBeChecked == entry.getKey()) {
isKeyPresent = true;
}
}
System.out.println("Does key "
+ keyToBeChecked
+ " exists: "
+ isKeyPresent);
}
}
|
package com.game.cwtetris.ui.shape;
/**
* Created by gena on 12/15/2016.
*/
public enum ShapeType {
S010_111_000(0),
S100_111_000(1),
S001_111_000(2),
S110_010_011(3),
S110_011_000(4),
S011_110_000(5),
S010_111_010(6),
S100_011_001(7),
S010_010_010(8),
S010_011_000(9),
S010_111_101(10);
private final int value;
private ShapeType(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
|
/*
* Copyright 2013 Himanshu Bhardwaj
*
* 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.himanshu.poc.springbootsec.service;
import java.util.UUID;
import org.springframework.stereotype.Component;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
@Component
public class TokenKeeperService {
//Key username and Value is token
private BiMap<String, String> userTokenMap = HashBiMap.<String, String>create();
public String generateNewToken(String username) {
if (! userTokenMap.containsKey(username)) {
String token = UUID.randomUUID().toString();
userTokenMap.put(username, token);
}
return userTokenMap.get(username);
}
public String queryUserByToken(String token) {
//Map inversed now the token is key and value is username
return userTokenMap.inverse().get(token);
}
}
|
package br.com.deguste.model.entity;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
@Entity
@SequenceGenerator(name = "seqAvaria", sequenceName = "seq_avaria", allocationSize = 1)
public class Avaria implements Serializable {
/**
*
*/
private static final long serialVersionUID = -1350877055036791999L;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seqAvaria")
private Long id;
@Column (nullable = false)
private String descricao;
@Column
private boolean ativo;
@Override
public boolean equals(Object obj) {
if(obj == null) return false;
if(obj instanceof Avaria)
if(((Avaria)obj).getId().equals(this.id)) return true;
return false;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getDescricao() {
return descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
public boolean isAtivo() {
return ativo;
}
public void setAtivo(boolean ativo) {
this.ativo = ativo;
}
}
|
package com.javasampleapproach.mysql.hall.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.javasampleapproach.mysql.hall.model.Stuff;
import com.javasampleapproach.mysql.hall.repo.StuffRepository;
import com.javasampleapproach.mysql.model.Admission;
import com.javasampleapproach.mysql.model.Api;
import com.javasampleapproach.mysql.repo.ApiRepository;
@Service
public class StuffService {
@Autowired
private StuffRepository stuffrepo;
public void addstuff(Stuff stuff){
stuffrepo.save(stuff);
}
public void deletestuff(long id) {
stuffrepo.delete(id);
}
public void updatestuff(long id,Stuff stuff) {
stuffrepo.save(stuff);
}
public Stuff getstuff(long id)
{
return (Stuff) stuffrepo.findOne(id);
}
public List<Stuff>getallstuff()
{
List<Stuff> stuff=new ArrayList<>();
stuffrepo.findAll()
.forEach(stuff::add);
return stuff;
}
}
|
package com.example.test_2;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.SimpleExpandableListAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.material.navigation.NavigationView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AlertDialog;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.FragmentTransaction;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
DrawerLayout drawer;
Button btn, btn2;
public static Toolbar toolbar;
static SharedPreferences Table;
static Context context;
private static final String ListDays="Days",ListChild="ListChild";
static ExpandableListView ListDays_ID;
static SimpleExpandableListAdapter adapter;
static ArrayList<ArrayList<Map<String, String>>> childData;
static ArrayList<Map<String, String>> groupData;
static ArrayList<Map<String, String>> childDataItem;
private RelativeLayout Setting_Container;
static Map<String, String> m;
static String[] groups;
static ProgressBar bar;
static Spinner spinner;
static ConstraintLayout content_layout;
private DatabaseReference firebaseDatabase;
TextView navUsername,setting_click;
private LinearLayout MainLiner;
GetDataBase toolbar_text;
View view;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
content_layout=findViewById(R.id.content_cordinatal);
Start();
CheckUserOnline(false);
}
private boolean CheckUserOnline(boolean IsOnline){
if(FirebaseAuth.getInstance().getCurrentUser()!=null){
IsOnline=true;
}else {
Table.edit().clear().commit();
Table.edit().apply();
Intent Login_main = new Intent(MainActivity.this,LoginMain.class);
startActivity(Login_main);
finish();
}
return IsOnline;
}
private void Start(){
toolbar = findViewById(R.id.toolbar);
drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View headerView = navigationView.getHeaderView(0);
navUsername = (TextView) headerView.findViewById(R.id.profilename);
setting_click =headerView.findViewById(R.id.setting_textview);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
btn = findViewById(R.id.button_taber_1);
btn2 = findViewById(R.id.button2);
ListDays_ID = findViewById(R.id.ListDays);
Table = getSharedPreferences("TABLE", MODE_PRIVATE);
context=MainActivity.this;
ClickButton();
bar=findViewById(R.id.ProgresBarLoad);
spinner=findViewById(R.id.spinner);
AdapterViewList(this,false,false);
NewWeek newWeek = new NewWeek(null,Table,context);
newWeek.setSpinner();
GetValue();
setHeaderName(view);
MainLiner = findViewById(R.id.MainLiner);
Setting_Container = findViewById(R.id.SettingFragment);
}
private void setHeaderName(View view){
if(isOnline(MainActivity.this)==true) {
firebaseDatabase = FirebaseDatabase.getInstance().getReference("Users");
firebaseDatabase.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
Users user = snapshot.getValue(Users.class);
navUsername.setText(user.Name);
Toast.makeText(MainActivity.this, "Name = " + user.Name, Toast.LENGTH_LONG).show();
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}else{Toast.makeText(MainActivity.this, "Не подключен к интернету",Toast.LENGTH_LONG).show();}
}
private void GetValue(){
String VALUE_data_Fac,VALUE_data_Spec,VALUE_data_Group;
if(Table.getString("ValueFac","404").equals("404")&&Table.getString("ValueSpec","404").equals("404")&&Table.getString("ValueGroup","404").equals("404")){
Bundle arguments = getIntent().getExtras();
VALUE_data_Fac = arguments.get("ValueFac").toString();
VALUE_data_Spec = arguments.get("ValueSpec").toString();
VALUE_data_Group = arguments.get("ValueGroup").toString();
SharedPreferences.Editor editor = Table.edit();
editor.putString("ValueFac", VALUE_data_Fac);
editor.putString("ValueSpec", VALUE_data_Spec);
editor.putString("ValueGroup", VALUE_data_Group);
editor.apply();
}else
Toast.makeText(context,"Уже существует данные",Toast.LENGTH_LONG);
}
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_list:
GetDataBase.GetGroup();
MainLiner.setVisibility(View.VISIBLE);
Setting_Container.setVisibility(View.INVISIBLE);
AdapterViewList(this,false,false);
break;
case R.id.nav_chat:
Intent intent = new Intent(MainActivity.this,Chat.class);
startActivity(intent);
break;
case R.id.nav_book:
break;
case R.id.setting_listview:
toolbar.setTitle("Настройка");
RelativeLayout r = findViewById(R.id.SettingFragment);
r.bringToFront();
SettingFragment setting = new SettingFragment();
FragmentTransaction fr = getSupportFragmentManager().beginTransaction();
fr.replace(R.id.SettingFragment,setting);
fr.commit();
MainLiner.setVisibility(View.INVISIBLE);
Setting_Container.setVisibility(View.VISIBLE);
break;
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
void ClickButton() {
btn2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Table.edit().clear().commit();
Table.edit().apply();
AdapterViewList(context,false,false);
Intent NewStart = new Intent(MainActivity.this,LoginMain.class);
startActivity(NewStart);
finish();
}
});
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
isOnline(MainActivity.this);
if (isOnline(MainActivity.this) == true) {
ParsingList pars= new ParsingList(Table,context,"TT_2_15_02_2021",Table.getString("ValueFac","404"),
Table.getString("ValueSpec","404"),
Table.getString("ValueGroup","404"));
pars.StartThreadParsing();
}
}
});
}
public static boolean isOnline(Context context) {
ConnectivityManager cm =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
} else {
Toast.makeText(context, "Не подключен", Toast.LENGTH_SHORT).show();
return false;
}
}
public static Boolean AdapterViewList(Context context,boolean check, boolean errors) {
if(check){
bar.setVisibility(View.GONE);
check=false;
AlertDialog.Builder dialog = new AlertDialog.Builder(context);
dialog.setTitle("Готово");
dialog.setMessage("Расписание успешно загружено, теперь расписание можно смотреть оффлайн");
AlertDialog dialog1=dialog.create();
dialog1.show();
}
if(errors)
{
bar.setVisibility(View.GONE);
AlertDialog.Builder dialog = new AlertDialog.Builder(context);
dialog.setTitle("Ошибка");
dialog.setMessage("Перезагрузите приложения, если ничего не случилось то проблема с сервером");
AlertDialog dialog1=dialog.create();
dialog1.show();
}
groups = new String[]{Table.getString("Day", "Нет данных"), Table.getString("Day1", "Нет данных"), Table.getString("Day2", "Нет данных"),
Table.getString("Day3", "Нет данных"), Table.getString("Day4", "Нет данных")};
String[] Monday = new String[]{Table.getString("Monday", "Пусто")};
String[] Tuesday = new String[]{Table.getString("Tuesday", "Пусто")};
String[] Wednesday = new String[]{Table.getString("Wednesday", "Пусто")};
String[] Thursday = new String[]{Table.getString("Thursday", "Пусто")};
String[] Friday = new String[]{Table.getString("Friday", "Пусто")};
groupData = new ArrayList<>();
for (String group : groups) {
m = new HashMap<>();
m.put(ListDays, group);
groupData.add(m);
}
childData = new ArrayList<>();
// создаем коллекцию элементов для первой группы
childDataItem = new ArrayList<>();
// заполняем список атрибутов для каждого элемента
for (String list : Monday) {
m = new HashMap<String, String>();
m.put(ListChild, list);
childDataItem.add(m);
}
// добавляем в коллекцию коллекций
childData.add(childDataItem);
// создаем коллекцию элементов для второй группы
childDataItem = new ArrayList<Map<String, String>>();
for (String list : Tuesday) {
m = new HashMap<String, String>();
m.put(ListChild, list);
childDataItem.add(m);
}
childData.add(childDataItem);
childDataItem = new ArrayList<>();
for (String monday : Wednesday) {
m = new HashMap<>();
m.put(ListChild, monday);
childDataItem.add(m);
}
childData.add(childDataItem);
childDataItem = new ArrayList<Map<String, String>>();
for (String list : Thursday) {
m = new HashMap<>();
m.put(ListChild, list);
childDataItem.add(m);
}
childData.add(childDataItem);
childDataItem = new ArrayList<Map<String, String>>();
for (String list : Friday) {
m = new HashMap<>();
m.put(ListChild, list);
childDataItem.add(m);
}
childData.add(childDataItem);
String groupFrom[] = new String[]{ListDays};
// список ID view-элементов, в которые будет помещены атрибуты групп
int groupTo[] = new int[]{android.R.id.text1};
String childFrom[] = new String[]{ListChild};
int childTo[] = new int[]{android.R.id.text1};
adapter = new SimpleExpandableListAdapter(
context,
groupData,
android.R.layout.simple_expandable_list_item_1,
groupFrom,
groupTo,
childData,
android.R.layout.simple_list_item_1,
childFrom,
childTo);
ListDays_ID.setAdapter(adapter);
return false;
}
}
|
/*
* ################################################################
*
* ProActive Parallel Suite(TM): The Java(TM) library for
* Parallel, Distributed, Multi-Core Computing for
* Enterprise Grids & Clouds
*
* Copyright (C) 1997-2011 INRIA/University of
* Nice-Sophia Antipolis/ActiveEon
* Contact: proactive@ow2.org or contact@activeeon.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation; version 3 of
* the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
* If needed, contact us to obtain a release under GPL Version 2 or 3
* or a different license than the AGPL.
*
* Initial developer(s): The ProActive Team
* http://proactive.inria.fr/team_members.htm
* Contributor(s):
*
* ################################################################
* $$PROACTIVE_INITIAL_DEV$$
*/
package org.ow2.proactive.resourcemanager.core.history;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.apache.log4j.Logger;
import org.hibernate.annotations.Index;
import org.objectweb.proactive.core.util.log.ProActiveLogger;
import org.ow2.proactive.db.Condition;
import org.ow2.proactive.db.ConditionComparator;
import org.ow2.proactive.resourcemanager.authentication.Client;
import org.ow2.proactive.resourcemanager.db.DatabaseManager;
import org.ow2.proactive.resourcemanager.utils.RMLoggers;
/**
*
* This class represents the users connection history.
*
*/
@Entity
@Table(name = "UserHistory")
public class UserHistory {
public static final Logger logger = ProActiveLogger.getLogger(RMLoggers.DATABASE);
@Id
@GeneratedValue
@SuppressWarnings("unused")
protected long id;
@Column(name = "userName")
@Index(name = "userNameIndex")
private String userName;
@Column(name = "startTime")
protected long startTime;
@Column(name = "endTime")
protected long endTime;
/**
* Default constructor for Hibernate
*/
public UserHistory() {
}
/**
* Constructs new history record.
*/
public UserHistory(Client client) {
this.userName = client.getName();
this.startTime = System.currentTimeMillis();
}
/**
* Saves user connection information
*/
public void save() {
// registering the new history record
DatabaseManager.getInstance().register(this);
}
/**
* Updates the time when user disconnects
*/
public void update() {
this.endTime = System.currentTimeMillis();
DatabaseManager.getInstance().update(this);
}
/**
* After the resource manager is terminated some history records may not have the end time stamp.
* We set it at the moment of next RM start taking the time from Alive table.
*/
public static void recover(Alive alive) {
List<UserHistory> records = DatabaseManager.getInstance().recover(UserHistory.class,
new Condition("endTime", ConditionComparator.EQUALS_TO, new Long(0)));
for (UserHistory record : records) {
if (record.startTime < alive.getTime()) {
// alive time bigger than start time of the history record
// marking the end of this record as last RM alive time
record.endTime = alive.getTime();
} else {
// the event happened after last RM alive time update
// just put endTime = startTime
record.endTime = record.startTime;
}
DatabaseManager.getInstance().update(record);
}
logger.debug("Restoring the user history: " + records.size() + " raws updated");
}
}
|
package tool.scanner;
public class ScannerTest
{
public static void main(String args[])
{
// 标准输入 --> 键盘输入
java.util.Scanner scanner = new java.util.Scanner(System.in);
// 将 回车符 作为分隔符
scanner.useDelimiter("\n");
while (scanner.hasNext())
{
System.out.println("键盘输入的内容为:" + scanner.next());
}
scanner.close();
}
/**
* 针对 long 方式
*/
public void testLong()
{
// 标准输入 --> 键盘输入
java.util.Scanner scanner = new java.util.Scanner(System.in);
while (scanner.hasNextLong())
{
System.out.println("键盘输入的内容为:" + scanner.nextLong());
}
scanner.close();
}
}
|
package org.celllife.stock.application.service.alert;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.celllife.stock.domain.alert.Alert;
import org.celllife.stock.domain.alert.AlertDto;
import org.celllife.stock.domain.alert.AlertRepository;
import org.celllife.stock.domain.alert.AlertStatus;
import org.celllife.stock.domain.alert.AlertSummaryDto;
import org.celllife.stock.domain.drug.Drug;
import org.celllife.stock.domain.drug.DrugRepository;
import org.celllife.stock.domain.exception.StockException;
import org.celllife.stock.domain.user.User;
import org.celllife.stock.domain.user.UserRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class AlertServiceImpl implements AlertService {
private static Logger log = LoggerFactory.getLogger(AlertServiceImpl.class);
@Autowired
AlertRepository alertRepository;
@Autowired
UserRepository userRepository;
@Autowired
DrugRepository drugRepository;
@Override
@Transactional
public AlertDto createAlert(AlertDto alert) {
User user = getUser(alert); // will use either msisdn or cliniccode to locate the user
Drug drug = getDrug(alert);
// update latest alert to be expired (latest alert is only status NEW or SENT)
Alert oldAlert = alertRepository.findOneLatestByUserAndDrug(user, drug);
if (oldAlert != null) {
if (log.isDebugEnabled()) {
log.warn("Expiring related alert '"+alert.getId()+"' (status='"+alert.getStatus()+"') for " +
"user '"+user.getMsisdn()+"' in clinic '"+user.getClinicName()+"' for " +
"drug '"+drug.getDescription()+"'");
}
oldAlert.setStatus(AlertStatus.EXPIRED);
alertRepository.save(oldAlert);
}
// save new alert
Alert newAlert = convertAlert(alert, user, drug);
newAlert.setStatus(AlertStatus.NEW);
log.debug("saving alert "+newAlert+" for user="+user+" and drug="+drug);
Alert savedAlert = alertRepository.save(newAlert);
return new AlertDto(savedAlert);
}
@Override
@Transactional(readOnly = true)
public Set<AlertDto> getOpenAlerts(String msisdn) {
User user = userRepository.findOneByMsisdn(msisdn);
List<Alert> alerts = alertRepository.findOpenByUser(user);
return convertAlertCollection(alerts);
}
@Override
@Transactional
public Set<AlertDto> getNewAlerts(String msisdn) {
User user = userRepository.findOneByMsisdn(msisdn);
List<Alert> alerts = alertRepository.findNewByUser(user);
Set<AlertDto> alertDTOs = convertAlertCollection(alerts);
// mark alerts as sent
for (Alert alert : alerts) {
alert.setStatus(AlertStatus.SENT);
alertRepository.save(alert);
}
return alertDTOs;
}
@Override
@Transactional(readOnly = true)
public AlertDto getAlert(Long id) {
Alert alert = alertRepository.findOne(id);
if (alert != null) {
return new AlertDto(alert);
} else {
return null;
}
}
@Override
@Transactional(readOnly = true)
public Set<AlertSummaryDto> getAlertSummary() {
List<AlertSummaryDto> summary = alertRepository.calculateAlertSummary();
Set<AlertSummaryDto> alertSummary = new HashSet<AlertSummaryDto>();
for (AlertSummaryDto dto : summary) {
alertSummary.add(dto);
}
return alertSummary;
}
private User getUser(AlertDto alert) {
if (alert.getUser() == null) {
throw new StockException("No user specified for alert. "+alert);
}
User user = null;
if (alert.getUser().getMsisdn() != null && !alert.getUser().getMsisdn().trim().equals("")) {
user = userRepository.findOneByMsisdn(alert.getUser().getMsisdn());
}
if (alert.getUser().getClinicCode() != null && !alert.getUser().getClinicCode().trim().equals("")) {
List<User> users = userRepository.findByClinicCode(alert.getUser().getClinicCode());
if (users != null && users.size() > 0) {
user = users.get(0);
}
}
if (user == null) {
throw new StockException("Could not find user with msisdn '"+alert.getUser().getMsisdn()+" or clinicCode '"+alert.getUser().getClinicCode()+"'.");
}
return user;
}
private Drug getDrug(AlertDto alert) {
if (alert.getDrug() == null) {
throw new StockException("No drug specified for alert. "+alert);
}
Drug drug = drugRepository.findOneByBarcode(alert.getDrug().getBarcode());
if (drug == null) {
throw new StockException("Could not find drug with barcode '"+alert.getDrug().getBarcode()+"'.");
}
return drug;
}
private Set<AlertDto> convertAlertCollection(List<Alert> alerts) {
Set<AlertDto> alertDTOs = new HashSet<AlertDto>();
for (Alert alert : alerts) {
alertDTOs.add(new AlertDto(alert));
}
return alertDTOs;
}
private Alert convertAlert(AlertDto alert, User user, Drug drug) {
Alert newAlert = new Alert(alert.getDate(), alert.getLevel(), alert.getMessage(), alert.getStatus(),
user, drug);
return newAlert;
}
}
|
package com.gsccs.sme.api.service;
import java.util.List;
import com.gsccs.sme.api.domain.site.Banner;
import com.gsccs.sme.api.domain.site.Link;
/**
* 友情链接
* @author x.d zhang
*
*/
public interface LinkServiceI {
/**
* 查询友情链接
* @param param
* @return
*/
public List<Link> find(Link param,int page,int pagesize);
}
|
/*
* SingleApnsConnection.java
*
**********************************************************************
Copyright (c) 2013 - 2014 netty-apns
***********************************************************************/
package apns.netty.connection.impl;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import apns.netty.config.ApnsConfig;
import apns.netty.connection.Connection;
import apns.netty.constants.ApplicationContextComponents;
import apns.netty.handlers.single.SingleMessageInitializer;
import apns.netty.queues.single.SingleMessageQueue;
import apns.netty.queues.single.SingleMessageQueuePoller;
/**
* The Class SingleConnection.
* @author arung
*/
@Component
public class SingleApnsConnection implements Connection {
/** The Constant CLOSING_SINGLE_CONNECTION_CHANNEL. */
private static final String CLOSING_SINGLE_CONNECTION_CHANNEL = "Closing SingleConnection channel";
/** The Constant SINGLE_CONNECTION_CHANNEL_IS. */
private static final String SINGLE_CONNECTION_CHANNEL_IS = "SingleConnection channel is:";
/** The logger. */
Logger logger = Logger.getLogger(SingleApnsConnection.class);
/** The apns config. */
@Autowired
ApnsConfig apnsConfig;
/** The application context. */
@Autowired
ApplicationContext applicationContext;
/** The single message queue. */
@Autowired
SingleMessageQueue singleMessageQueue;
/** The single bootstrap. */
@Autowired
private Bootstrap singleBootstrap;
/** The single nio event loop group. */
private final EventLoopGroup singleNioEventLoopGroup = new NioEventLoopGroup();
/**
* Inits the.
*/
@PostConstruct
public void init() {
singleBootstrap = new Bootstrap();
singleBootstrap.group(singleNioEventLoopGroup)
.channel(NioSocketChannel.class)
.option(ChannelOption.SO_KEEPALIVE, true)
// .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000)
.handler(
applicationContext
.getBean(SingleMessageInitializer.class));
bootstrap();
}
/*
* (non-Javadoc)
* @see apns.netty.connection.Connection#connect()
*/
@Override
public void bootstrap() {
// // Make the connection attempt.
// ChannelFuture f = b.connect(host, port).sync();
//
// // Wait until the connection is closed.
// f.channel().closeFuture().sync();
// } finally {
// group.shutdownGracefully();
// }
// Start the connection attempt.
new Thread(new Runnable() {
@Override
public void run() {
try {
final ChannelFuture f = singleBootstrap.connect(
apnsConfig.getPushHost(),
apnsConfig.getPushPort()).sync();
final Channel outChannel = f.channel();
logger.trace(SingleApnsConnection.SINGLE_CONNECTION_CHANNEL_IS
+ outChannel);
final SingleMessageQueuePoller singleMessageQueuePoller = (SingleMessageQueuePoller) applicationContext.getBean(ApplicationContextComponents.SINGLE_MESSAGE_QUEUE_POLLER);
singleMessageQueuePoller.setOutChannel(outChannel);
if (!singleMessageQueuePoller.isAlive()) {
singleMessageQueuePoller.start();
}
outChannel.closeFuture().sync();
logger.trace(SingleApnsConnection.CLOSING_SINGLE_CONNECTION_CHANNEL);
} catch (final InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
// TODO: Logger
}
}
}, "APNSSingleConnectorThread").start();
// while (outChannel == null || !outChannel.isActive()) {
// logger.trace("Not connected:");
// }
}
/**
* Destroy.
*/
@PreDestroy
public void destroy() {
singleNioEventLoopGroup.shutdownGracefully();
}
// public void write(final ApnsMessage msg) {
// logger.trace("Writing message to single connection");
// outChannel.write(msg);
// logger.trace("Flusing connetion");
// outChannel.flush();
// logger.trace("Flusing the data");
// }
}
|
package com.wh.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.wh.entity.User;
import java.util.List;
/**
* @program: maven-modules
* @description:
* @author: wh
* @create: 2021-07-12 13:51
**/
public interface UserMapper extends BaseMapper<User> {
/**
* 获取
* @return
*/
List<User> selectAll();
}
|
package Controller.shop;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import command.shop.shopCommand;
import service.shop.cartInsertService;
import service.shop.goodsInsertService;
@Controller
@RequestMapping(value = "/delshop/InsertCart")
public class shopCartController {
@Autowired
cartInsertService cartInsertService;
@RequestMapping(method = RequestMethod.GET)
public String insert() {
return "shop/product-page";
}
@RequestMapping(method = RequestMethod.POST)
public String insertPro(shopCommand shopcommand , HttpServletRequest request, HttpSession session) {
cartInsertService.execute(shopcommand, request, session);
return "redirect:/delshop/main";
}
}
|
package sonar.socket;
// Hola ale
public class HolaAle {
private boolean hola = false;
private void decirHola(){
System.out.println();
}
}
|
package org.digdata.swustoj.mybatis.dao;
import java.util.List;
import org.digdata.swustoj.model.annotation.CacheAccess;
import org.digdata.swustoj.model.annotation.CacheFlush;
import org.digdata.swustoj.mybatis.entiy.Tags;
public interface TagsDao {
int deleteByPrimaryKey(Integer id);
int insert(Tags record);
int insertSelective(Tags record);
Tags selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(Tags record);
int updateByPrimaryKey(Tags record);
// =====================================
public String PREFIX = "org.digdata.swustoj.mybatis.dao.TagsMapper.";
/**
*
* @author wwhhf
* @since 2016年5月26日
* @comment 条件查询标签
* @param search_ids
* @param search_name
* @param page
* @param rows
* @return
*/
@CacheAccess(type = List.class, subType = Tags.class)
public List<Tags> selectTags(List<Integer> search_ids, String search_name,
Integer page, Integer rows);
/**
*
* @author wwhhf
* @since 2016年5月26日
* @comment 条件查询标签的数量
* @param search_ids
* @param search_name
* @param page
* @param rows
* @return
*/
@CacheAccess(type = Integer.class)
public Integer selectTagsNum(List<Integer> search_ids, String search_name);
/**
*
* @author wwhhf
* @since 2016年5月26日
* @comment 批量删除标签
* @param tids
* @return
*/
@CacheFlush
public Boolean deleteTags(List<Integer> tids);
/**
*
* @author wwhhf
* @since 2016年5月26日
* @comment 添加标签
* @param record
* @return
*/
@CacheFlush
public Boolean insertTags(Tags record);
/**
*
* @author wwhhf
* @since 2016年5月26日
* @comment 更新标签
* @param record
* @return
*/
@CacheFlush
public Boolean updateTags(Tags record);
} |
package com.example.fklubben;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class AboutUs extends AppCompatActivity {
public void onClickAboutUs(View view){
Intent intent = new Intent(this, AboutUs.class);
startActivity(intent);
}
public void onClickDrinks(View view){
Intent intent = new Intent(this, DrinksActivity.class);
startActivity(intent);
}
public void onClickContact(View view){
Intent intent = new Intent(this, contact.class);
startActivity(intent);
}
public void onClickMap(View view){
Intent intent = new Intent(this, map.class);
startActivity(intent);
}
public void onClickTest(View view){
Intent intent = new Intent(this, test.class);
startActivity(intent);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about_us);
}
}
|
package com.shangdao.phoenix.entity.entityManager;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.shangdao.phoenix.entity.act.Act;
import com.shangdao.phoenix.entity.interfaces.IBaseEntity;
import com.shangdao.phoenix.entity.state.State;
import com.shangdao.phoenix.entity.tag.Tag;
import com.shangdao.phoenix.entity.user.User;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
import java.util.Set;
@Entity
@Table(name = "entity_manager")
public class EntityManager implements IBaseEntity, Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private long id;
@Column(name = "name", unique = true)
private String name;
@Column(name = "has_log")
private Boolean hasLog;
@Column(name = "has_project")
private Boolean hasProject;
@Column(name = "has_state_machine")
private Boolean hasStateMachine;
@Column(name = "has_tag")
private Boolean hasTag;
@Column(name = "deleted_at")
@JsonIgnore
private Date deletedAt;
@ManyToOne
@JoinColumn(name = "entity_manager_id")
private EntityManager entityManager;
@OneToMany(mappedBy = "entityManager")
private Set<State> states;
@OneToMany(mappedBy = "entityManager")
private Set<Act> acts;
@OneToMany(mappedBy = "entityManager")
private Set<Tag> tags;
@Column(name = "created_at")
@JsonIgnore
private Date createdAt;
@ManyToOne
@JoinColumn(name = "created_by")
@JsonIgnore
private User createdBy;
@ManyToOne
@JoinColumn(name = "state_id")
private State state;
@Column(name = "manager_group")
@Enumerated(EnumType.STRING)
private ManagerGroup managerGroup;
@Override
public long getId() {
return id;
}
@Override
public void setId(long id) {
this.id = id;
}
@Override
public String getName() {
return name;
}
@Override
public void setName(String name) {
this.name = name;
}
public Boolean getHasLog() {
return hasLog;
}
public void setHasLog(Boolean hasLog) {
this.hasLog = hasLog;
}
public Boolean getHasProject() {
return hasProject;
}
public void setHasProject(Boolean hasProject) {
this.hasProject = hasProject;
}
public Boolean getHasStateMachine() {
return hasStateMachine;
}
public void setHasStateMachine(Boolean hasStateMachine) {
this.hasStateMachine = hasStateMachine;
}
public Boolean getHasTag() {
return hasTag;
}
public void setHasTag(Boolean hasTag) {
this.hasTag = hasTag;
}
@Override
public Date getDeletedAt() {
return deletedAt;
}
@Override
public void setDeletedAt(Date deletedAt) {
this.deletedAt = deletedAt;
}
@Override
public EntityManager getEntityManager() {
return entityManager;
}
@Override
public void setEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
}
public Set<State> getStates() {
return states;
}
public void setStates(Set<State> states) {
this.states = states;
}
public Set<Act> getActs() {
return acts;
}
public void setActs(Set<Act> acts) {
this.acts = acts;
}
public Set<Tag> getTags() {
return tags;
}
public void setTags(Set<Tag> tags) {
this.tags = tags;
}
@Override
public Date getCreatedAt() {
return createdAt;
}
@Override
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
@Override
public User getCreatedBy() {
return createdBy;
}
@Override
public void setCreatedBy(User createdBy) {
this.createdBy = createdBy;
}
@Override
public State getState() {
return state;
}
@Override
public void setState(State state) {
this.state = state;
}
public ManagerGroup getManagerGroup() {
return managerGroup;
}
public void setManagerGroup(ManagerGroup managerGroup) {
this.managerGroup = managerGroup;
}
public enum ManagerGroup {
DEVELOPER, ADMIN
}
}
|
package forms;
import models.NPVTableModel;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;
public class NPVCalculator extends JFrame {
private JTable calcTable;
private JPanel mainPanel;
private JTextField incomesInput;
private JTextField expensesInput;
private JButton addRowButton;
private JLabel errorMessage;
private JLabel npv;
private JButton plotButton;
private NPVTableModel tableModel;
public NPVCalculator(double discount, double investments) {
super();
tableModel = new NPVTableModel(discount, investments);
calcTable.setModel(tableModel);
addRowButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
calcPeriod();
}
});
plotButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
showPlot();
}
});
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setContentPane(mainPanel);
pack();
setVisible(true);
}
private void calcPeriod() {
try {
double incomes = Double.parseDouble(incomesInput.getText());
double expenses = Double.parseDouble(expensesInput.getText());
tableModel.addRow(incomes, expenses);
npv.setText("NPV: " + tableModel.getNPV());
incomesInput.setText("");
expensesInput.setText("");
errorMessage.setText("");
} catch (NumberFormatException e) {
errorMessage.setText("Неверный формат чисел");
}
}
private void showPlot() {
Vector x = tableModel.getColumn(NPVTableModel.PERIOD_COLUMN);
Vector y = tableModel.getColumn(NPVTableModel.NPV_COLUMN);
PlotDialog plotDialog = new PlotDialog(x, y, "NPV", "время", "тыс. руб.");
plotDialog.pack();
plotDialog.setVisible(true);
}
{
// GUI initializer generated by IntelliJ IDEA GUI Designer
// >>> IMPORTANT!! <<<
// DO NOT EDIT OR ADD ANY CODE HERE!
$$$setupUI$$$();
}
/**
* Method generated by IntelliJ IDEA GUI Designer
* >>> IMPORTANT!! <<<
* DO NOT edit this method OR call it in your code!
*
* @noinspection ALL
*/
private void $$$setupUI$$$() {
mainPanel = new JPanel();
mainPanel.setLayout(new com.intellij.uiDesigner.core.GridLayoutManager(3, 1, new Insets(0, 0, 0, 0), -1, -1));
final JScrollPane scrollPane1 = new JScrollPane();
mainPanel.add(scrollPane1, new com.intellij.uiDesigner.core.GridConstraints(1, 0, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_BOTH, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_WANT_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false));
calcTable = new JTable();
calcTable.setAutoCreateRowSorter(true);
calcTable.setAutoResizeMode(2);
calcTable.setFillsViewportHeight(true);
calcTable.setShowVerticalLines(true);
scrollPane1.setViewportView(calcTable);
final JPanel panel1 = new JPanel();
panel1.setLayout(new com.intellij.uiDesigner.core.GridLayoutManager(2, 4, new Insets(0, 0, 0, 0), -1, -1));
mainPanel.add(panel1, new com.intellij.uiDesigner.core.GridConstraints(0, 0, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_BOTH, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
incomesInput = new JTextField();
panel1.add(incomesInput, new com.intellij.uiDesigner.core.GridConstraints(1, 0, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_WEST, com.intellij.uiDesigner.core.GridConstraints.FILL_HORIZONTAL, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_WANT_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final com.intellij.uiDesigner.core.Spacer spacer1 = new com.intellij.uiDesigner.core.Spacer();
panel1.add(spacer1, new com.intellij.uiDesigner.core.GridConstraints(1, 2, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_HORIZONTAL, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false));
expensesInput = new JTextField();
panel1.add(expensesInput, new com.intellij.uiDesigner.core.GridConstraints(1, 1, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_WEST, com.intellij.uiDesigner.core.GridConstraints.FILL_HORIZONTAL, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_WANT_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
addRowButton = new JButton();
addRowButton.setLabel("Добавить период");
addRowButton.setText("Добавить период");
panel1.add(addRowButton, new com.intellij.uiDesigner.core.GridConstraints(1, 3, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_HORIZONTAL, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final JLabel label1 = new JLabel();
label1.setText("Доходы, тыс. руб");
panel1.add(label1, new com.intellij.uiDesigner.core.GridConstraints(0, 0, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_WEST, com.intellij.uiDesigner.core.GridConstraints.FILL_NONE, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final JLabel label2 = new JLabel();
label2.setText("Затраты, тыс. руб.");
panel1.add(label2, new com.intellij.uiDesigner.core.GridConstraints(0, 1, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_WEST, com.intellij.uiDesigner.core.GridConstraints.FILL_NONE, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
errorMessage = new JLabel();
errorMessage.setText("");
panel1.add(errorMessage, new com.intellij.uiDesigner.core.GridConstraints(0, 3, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_WEST, com.intellij.uiDesigner.core.GridConstraints.FILL_NONE, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final JPanel panel2 = new JPanel();
panel2.setLayout(new com.intellij.uiDesigner.core.GridLayoutManager(1, 2, new Insets(0, 0, 0, 0), -1, -1));
mainPanel.add(panel2, new com.intellij.uiDesigner.core.GridConstraints(2, 0, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_BOTH, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
npv = new JLabel();
npv.setText("");
panel2.add(npv, new com.intellij.uiDesigner.core.GridConstraints(0, 1, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_EAST, com.intellij.uiDesigner.core.GridConstraints.FILL_NONE, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
plotButton = new JButton();
plotButton.setText("Построить график NPV");
panel2.add(plotButton, new com.intellij.uiDesigner.core.GridConstraints(0, 0, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_WEST, com.intellij.uiDesigner.core.GridConstraints.FILL_NONE, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
}
/**
* @noinspection ALL
*/
public JComponent $$$getRootComponent$$$() {
return mainPanel;
}
}
|
package xtrus.user.comp.dbl.util;
import java.io.File;
import java.lang.reflect.Constructor;
import xtrus.user.comp.dbl.DbLCode;
import xtrus.user.comp.dbl.DbLConfig;
import xtrus.user.comp.dbl.DbLException;
import xtrus.user.comp.dbl.table.DbLDocInfo;
import xtrus.user.comp.dbl.table.DbLDocInfoRecord;
import com.esum.comp.dbm.DBCode;
import com.esum.framework.core.component.ComponentException;
import com.esum.framework.core.component.post.JavaClassProcessable;
/**
* 메모리에 로딩한다.
*
* Copyright(c) eSum Technologies., Inc. All rights reserved.
*/
public class DBXmapInfo {
private static DBXmapInfo instance;
/**
* DBXmapInfo를 리턴한다.
*/
public synchronized static DBXmapInfo getInstance() {
if (instance == null)
instance = new DBXmapInfo();
return instance;
}
public File getInXmapFile(String docName, String senderTp, String receiverTp) throws DbLException {
DbLDocInfoRecord docInfo = null;
try {
docInfo = DbLUtil.getDblDocInfo(docName, senderTp, receiverTp);
} catch (ComponentException e) {
throw new DbLException(DbLCode.ERROR_NOT_FOUND_DOCINFO, "getInXmapFile()",
"Cannot find document info. (" + docName + ", " + senderTp + ", " + receiverTp + "). Check the table 'DBL_DOC_INFO'.", e);
}
String xmapName = docInfo.getDblDocInfo().getInDblXmap();
if (xmapName == null || xmapName.trim().equals("")) {
throw new DbLException(DbLCode.ERROR_SETUP_DOCINFO, "getInXmapFile()",
"DBL inbound xmap is NULL, Check the inbound xmap setup on 'DBL_DOC_INFO' table.");
}
return new File(DbLConfig.DBL_SCRIPT_PATH
+ File.separator + "xmap"
+ File.separator + xmapName);
}
public String getDBSavePriority(String docName, String senderTp, String receiverTp) throws DbLException {
DbLDocInfoRecord docInfo = null;
try {
docInfo = DbLUtil.getDblDocInfo(docName, senderTp, receiverTp);
} catch (ComponentException e) {
throw new DbLException(DbLCode.ERROR_NOT_FOUND_DOCINFO, "getDBSavePriority()",
"Cannot find document info. (" + docName + ", " + senderTp + ", " + receiverTp + "). Check the table 'DBL_DOC_INFO'.", e);
}
DbLDocInfo dblDocInfo = docInfo.getDblDocInfo();
return dblDocInfo.getInsertType();
}
/**
* 중복이 발생한 경우 처리 방안(무시, 업데이트, 에러) 정보를 리턴한다.
*/
public String getDupProcType(String docName, String senderTp, String receiverTp) throws DbLException {
DbLDocInfoRecord docInfo = null;
try {
docInfo = DbLUtil.getDblDocInfo(docName, senderTp, receiverTp);
} catch (ComponentException e) {
throw new DbLException(DbLCode.ERROR_NOT_FOUND_DOCINFO, "getDupProcType()",
"Cannot find document info. (" + docName + ", " + senderTp + ", " + receiverTp + "). Check the table 'DBL_DOC_INFO'.", e);
}
DbLDocInfo dbmDocInfo = docInfo.getDblDocInfo();
return dbmDocInfo.getDupProcType();
}
public JavaClassProcessable getPostProcessor(String docName, String senderTp, String receiverTp, String InOut) throws DbLException {
DbLDocInfoRecord docInfo = null;
try {
docInfo = DbLUtil.getDblDocInfo(docName, senderTp, receiverTp);
} catch (ComponentException e) {
throw new DbLException(DBCode.ERROR_NOT_FOUND_DOCINFO, "getPostProcessor()",
"Cannot find document info. (" + docName + ", " + senderTp + ", " + receiverTp + "). Check the table 'DOC_INFO'.", e);
}
DbLDocInfo dblDocInfo = docInfo.getDblDocInfo();
// load Class
String className = "";
String [] paramList = null;
if (InOut.equals("I")) {
className = dblDocInfo.getInPostProcessorClassName();
paramList = dblDocInfo.getInPostProcessorParamList();
}
if (className != null && !className.equals("")) {
try {
Class<?> c = Class.forName(className);
Class<?>[] clazzList = new Class[paramList.length];
for (int i = 0; i < paramList.length; i++)
clazzList[i] = paramList[i].getClass();
Constructor<?> constructor = c.getDeclaredConstructor(clazzList);
if (constructor == null)
throw new Exception(className + " constructor is not found. argument(" + paramList.length + ")");
Object instance = constructor.newInstance(paramList);
if (!(instance instanceof JavaClassProcessable))
throw new Exception(className + " must be implement the JavaClassProcessable interface.");
return (JavaClassProcessable)instance;
} catch (Exception e) {
throw new DbLException(DBCode.ERROR_CALL_JAVACLASS, "getPostProcessor()",
"cannot create an instance of 'JavaClassProcessable'.", e);
}
}
return null;
}
}
|
package com.dbs.portal.ui.component.view;
import java.util.List;
public interface ITableGridResultView extends IResultView{
public List<GridHeaderField> getHeaderFieldList();
}
|
package test;
import java.io.IOException;
import java.io.InputStream;
import java.sql.ResultSet;
import java.sql.SQLClientInfoException;
import java.util.Date;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import com.mybatis.dao.CommentsDao;
public class regTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String resource = "mybatis-config.xml";
SqlSession sqlsession = null;
try {
InputStream is = Resources.getResourceAsStream(resource);
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
sqlsession = factory.openSession();
CommentsDao dao = sqlsession.getMapper(CommentsDao.class);
int res = dao.deleteTopicByTid(1);
System.out.println(res);
sqlsession.commit();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO: handle exception
}finally{
sqlsession.close();
}
}
}
|
package local;
import java.util.Arrays;
import java.util.Random;
/*******************************************************************
* Questions / Fragen
*
* The english questions are provided on the exercise sheet
*
*******************************************************************
* a) Wie verhaelt sich die gemessene Laufzeit von den Methoden
* insertElement und insertElementFast zueinander?
* Erklaeren Sie das Ergebnis!
* ----------------------------------------------------------------
*
* Die insertElementFast Methode hatte beim Profiling einen Speedup
* von ~10. Das liegt daran, das schlau eingefuegt wird. Dadurch das
* durch das Array wie durch einen Baum traversiert wird, muessen nur
* n/4 Elemente geprueft werden. Bei der langsamen Methode hingegen
* kommt ein Sortier Algorithmus(Quicksort) zum tragen der bei fast
* vorsortierten Listen sehr langsam ist O(n^2).
*
*
* b) Warum ist es schneller die Methode System.arraycopy zu
* verwenden anstatt alle Werte einzeln in einer for-Schleife
* zuzuweisen? Beachte hierbei den Java-SourceCode zu dieser
* Methode!
* ----------------------------------------------------------------
*
* *** Auszug des openjdk sourcecodes ***
* FILE: java/lang/System.java
* ...
* 1 public static native void arraycopy(Object src, int srcPos,
* 2 Object dest, int destPos,
* 3 int length);
* ...
* *** Auszug Ende ***
*
* Das Schluesselwort 'native' in Zeile 1 sagt aus, das die Methode in
* einer anderen Sprache definiert ist. deswegen befindet sich unter der
* Methode auch kein Koerper. Da in der JNINativeInterface.c keine solche
* Methode definiert wurde, ist die Funktion in der JVM implimentiert.
*
* *** Auszug von der Hotspot JVM aus dem openjdk ***
* FILE: share/vm/c1/c1_Runtime1.cpp
* ...
* 1 JRT_LEAF(int, Runtime1::arraycopy(oopDesc* src, int src_pos, oopDesc* dst, int dst_pos, int length))
* 2 #ifndef PRODUCT
* 3 _generic_arraycopy_cnt++; // Slow-path oop array copy
* 4 #endif
* 5
* 6 if (src == NULL || dst == NULL || src_pos < 0 || dst_pos < 0 || length < 0) return ac_failed;
* 7 if (!dst->is_array() || !src->is_array()) return ac_failed;
* 8 if ((unsigned int) arrayOop(src)->length() < (unsigned int)src_pos + (unsigned int)length) return ac_failed;
* 9 if ((unsigned int) arrayOop(dst)->length() < (unsigned int)dst_pos + (unsigned int)length) return ac_failed;
* 10
* 11 if (length == 0) return ac_ok;
* 12 if (src->is_typeArray()) {
* 13 const klassOop klass_oop = src->klass();
* 14 if (klass_oop != dst->klass()) return ac_failed;
* 15 typeArrayKlass* klass = typeArrayKlass::cast(klass_oop);
* 16 const int l2es = klass->log2_element_size();
* 17 const int ihs = klass->array_header_in_bytes() / wordSize;
* 18 char* src_addr = (char*) ((oopDesc**)src + ihs) + (src_pos << l2es);
* 19 char* dst_addr = (char*) ((oopDesc**)dst + ihs) + (dst_pos << l2es);
* 20 // Potential problem: memmove is not guaranteed to be word atomic
* 21 // Revisit in Merlin
* 22 memmove(dst_addr, src_addr, length << l2es);
* 23 return ac_ok;
* 24 } else if (src->is_objArray() && dst->is_objArray()) {
* 25 if (UseCompressedOops) {
* 26 narrowOop *src_addr = objArrayOop(src)->obj_at_addr<narrowOop>(src_pos);
* 27 narrowOop *dst_addr = objArrayOop(dst)->obj_at_addr<narrowOop>(dst_pos);
* 28 return obj_arraycopy_work(src, src_addr, dst, dst_addr, length);
* 29 } else {
* 30 oop *src_addr = objArrayOop(src)->obj_at_addr<oop>(src_pos);
* 31 oop *dst_addr = objArrayOop(dst)->obj_at_addr<oop>(dst_pos);
* 32 return obj_arraycopy_work(src, src_addr, dst, dst_addr, length);
* 33 }
* 34 }
* 35 return ac_failed;
* 36 JRT_END
* ...
* *** Auszug Ende ***
*
* Wie man in Zeile 22 erkennen kann wird memmove dazu verwendet um den
* Speicherbereich eines Arrays eines primitiven datentyps byteweise zu
* kopieren.
*
* Resume: Da Java immer noch eine interpretierte Sprache ist, ist es
* performanter, haufig verwendete und zeitkritische Funktionen in
* Hadware naehere Sprachen wie C oder C++ auszulagern, anstatt sie in
* Java selbst zu implimentieren.
*
*******************************************************************/
/**
* provides the main that interacts with the class ArraySort.
*
* @author Jakob Karolus, Kevin Munk
* @version 1.0
*
*/
public class Main {
/**
* calls the method insertElement and insertElementFast 1000 times.
* Every time it generates a new array with 10000 elements and inserts a random number.
*
* @param args unused
*/
public static void main(String[] args){
// Random number generator for the element to insert
Random random = new Random();
for (int i = 0; i< 1000; i++){
// Generate a sorted array
int[] sortedArray = Main.getSortedArray(10000);
// Generate the element to insert
int element = random.nextInt();
// Call both insertElement methods
ArraySort.insertElement(element, sortedArray);
ArraySort.insertElementFast(element, sortedArray);
}
}
/**
*
* @param count the size of the array
* @return sorted array with random numbers.
*/
public static int[] getSortedArray(int count){
// Generate random numbers and assign them to the array
Random random = new Random();
int[] array = new int[count];
for (int i = 0; i < count; i++) {
array[i] = random.nextInt();
}
// Sort the array
Arrays.sort(array);
return array;
}
}
|
package com.performance.optimization.design.singleton;
/**
* 最简单的单例模式
* 不足之处:无法实现instance的延迟加载,
* 由于instance是static的,因此在JVM加载单例类时,单例对象会被创建,
* 如果此时单例类还扮演其他角色,则在使用单例类的这个地方都会实例化单例类。
* @author qiaolin
*
*/
public class SimpleSingleton {
private SimpleSingleton(){
System.out.println("create singleton instance ");
}
private static SimpleSingleton instance = new SimpleSingleton();
public static SimpleSingleton getInstance(){
return instance;
}
/**
* 当调用此方法时会实例化单例
*/
public static void createString(){
System.out.println("create string ... ");
}
public static void main(String[] args) {
SimpleSingleton.createString();
}
}
|
package com.gyorog.filepusher;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.core.app.JobIntentService;
import com.hierynomus.msdtyp.AccessMask;
import com.hierynomus.msdtyp.FileTime;
import com.hierynomus.msfscc.FileAttributes;
import com.hierynomus.msfscc.fileinformation.FileIdBothDirectoryInformation;
import com.hierynomus.mssmb2.SMB2CreateDisposition;
import com.hierynomus.mssmb2.SMB2CreateOptions;
import com.hierynomus.mssmb2.SMB2ShareAccess;
import com.hierynomus.protocol.commons.EnumWithValue;
import com.hierynomus.protocol.transport.TransportException;
import com.hierynomus.smbj.SMBClient;
import com.hierynomus.smbj.auth.AuthenticationContext;
import com.hierynomus.smbj.connection.Connection;
import com.hierynomus.smbj.session.Session;
import com.hierynomus.smbj.share.DiskShare;
import com.hierynomus.smbj.share.File;
import com.hierynomus.smbj.share.Share;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static com.hierynomus.msfscc.FileAttributes.FILE_ATTRIBUTE_DIRECTORY;
public class SmbIntentService extends JobIntentService {
private static final String TAG = "com.gyorog.filepusher.SmbIntentService";
private static final int JOB_ID = 29326;
String action;
String username;
String password;
String hostname;
String sharename;
String remotepath;
DiskShare ds = null;
public SmbIntentService() {
super();
}
static void enqueueWork(Context context, Intent work) {
enqueueWork(context, SmbIntentService.class, JOB_ID, work);
}
@Override
protected void onHandleWork(@NonNull Intent intent) { // JobIntentService entry
action = intent.getStringExtra("action");
assert action != null;
username = intent.getStringExtra("str-username");
password = intent.getStringExtra("str-password");
hostname = intent.getStringExtra("str-hostname");
sharename = intent.getStringExtra("str-sharename");
remotepath = intent.getStringExtra("str-remotepath");
PendingIntent reply = intent.getParcelableExtra("pendintent-result");
SMBClient client = null;
Connection conn = null;
Session ses = null;
Share share = null;
try {
assert password != null;
assert sharename != null;
client = new SMBClient();
conn = client.connect(hostname);
Log.d(TAG, "Negotiated protocol " + conn.getNegotiatedProtocol() + " with " + getString(R.string.smb_path, hostname, sharename, remotepath));
AuthenticationContext auth = new AuthenticationContext(username, password.toCharArray(), null);
ses = conn.authenticate(auth);
Log.d(TAG, "Authenticated as " + username + " for Session ID " + ses.getSessionId());
share = ses.connectShare(sharename);
if (share instanceof DiskShare) {
ds = (DiskShare) share;
} else {
Log.e(TAG, "Share was not a disk share: " + getString(R.string.smb_path, hostname, sharename, ""));
}
} catch (IOException e) {
Log.d(TAG, "Exception: " + e);
}
if ( action.equals("RequestPathContents") || action.equals("RequestPathContents-Dirs") || action.equals("RequestPathContents-Files") ) {
ArrayList<String> pathList = new ArrayList<String>();
Log.d(TAG, "Received intent to list " + getString(R.string.smb_path, hostname, sharename, remotepath) );
List<FileIdBothDirectoryInformation> contents = ds.list(remotepath);
for (FileIdBothDirectoryInformation item : contents) {
String file_name = item.getFileName();
long file_attributes = item.getFileAttributes();
if (!(file_name.equals(".") || file_name.equals(".."))) {
if (action.equals("RequestPathContents-Dirs") && EnumWithValue.EnumUtils.isSet(file_attributes, FILE_ATTRIBUTE_DIRECTORY)) {
//Log.d(TAG, "accepted-Dirs: " + file_name);
pathList.add(file_name);
} else if (action.equals("RequestPathContents-Files") && !EnumWithValue.EnumUtils.isSet(file_attributes, FILE_ATTRIBUTE_DIRECTORY)) {
//Log.d(TAG, "accepted-Files: " + file_name);
pathList.add(file_name);
} else if (action.equals("RequestPathContents")) {
//Log.d(TAG, "accepted: " + file_name);
pathList.add(file_name);
}
}
}
//Log.e(TAG, "Found list: " + pathlist.toString());
// Assuming that your List is a list of strings make data an ArrayList<String> and use intent.putStringArrayListExtra("data", data)
// private List<String> test;
// test = new ArrayList<String>();
// intent.putStringArrayListExtra("test", (ArrayList<String>) test);
// ArrayList<String> test = getIntent().getStringArrayListExtra("test");
// For more complicated list types: If you implement the Parcelable interface in your object then you can use the putParcelableArrayListExtra() method to add it to the Intent.
try {
if (reply != null) {
Log.d(TAG, "Returning path contents");
Intent result = new Intent();
result.putStringArrayListExtra("liststr-pathcontents", pathList);
result.putExtra("str-path", remotepath);
reply.send(this, MainActivity.CODE_SUCCESS, result);
} else {
Log.e(TAG, "'reply' not received in intent.");
}
} catch (PendingIntent.CanceledException exc) {
Log.i(TAG, "reply cancelled", exc);
}
} else if ( action.equals("RequestRecursiveReport") ) {
String report_name = getString(R.string.recursive_report, System.currentTimeMillis());
//Uri report_uri = null;
FileOutputStream report_stream = null;
try {
//report_uri = Uri.fromFile( new java.io.File(report_name) );
report_stream = openFileOutput(report_name, Context.MODE_PRIVATE);
RunRecursiveReport(report_stream, remotepath);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (report_stream != null) {
try {
report_stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
try {
if (reply != null) {
Log.d(TAG, "Returning report filename");
Intent result = new Intent();
result.putExtra("str-report_name", report_name);
reply.send(this, MainActivity.CODE_SUCCESS, result);
} else {
Log.e(TAG, "'reply' not received in intent.");
}
} catch (PendingIntent.CanceledException exc) {
Log.i(TAG, "reply cancelled", exc);
}
} else if ( action.equals("WriteFile") ) {
if (share instanceof DiskShare) {
Uri source_uri = intent.getParcelableExtra("str-sourceurl");
String filename = intent.getStringExtra("str-filename");
boolean overwrite = intent.getBooleanExtra("opt-overwrite", false);
String path_filename = remotepath + "/" + filename;
DiskShare ds = (DiskShare) share;
if( !overwrite && ds.fileExists(path_filename) ){
Log.e(TAG, "Already Exists");
//FIXME: return error
} else {
InputStream instream = null;
try {
instream = getContentResolver().openInputStream(source_uri);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
File outfile = ds.openFile(path_filename,
EnumSet.of(AccessMask.FILE_READ_DATA, AccessMask.FILE_WRITE_DATA),
new HashSet<FileAttributes>(),
new HashSet<SMB2ShareAccess>(),
SMB2CreateDisposition.FILE_OVERWRITE_IF,
EnumSet.of(SMB2CreateOptions.FILE_NON_DIRECTORY_FILE, SMB2CreateOptions.FILE_SEQUENTIAL_ONLY)
);
OutputStream outstream = outfile.getOutputStream();
byte[] buf = new byte[8192];
int length;
try {
while ((length = instream.read(buf)) > 0) {
outstream.write(buf, 0, length);
}
} catch (IOException e) {
e.printStackTrace();
}
}
try {
reply.send(this, MainActivity.CODE_SUCCESS, new Intent());
} catch (PendingIntent.CanceledException e) {
e.printStackTrace();
}
} else {
Log.e(TAG, "Got WriteFile but share was not a DiskShare");
}
} else {
Log.e(TAG, "Unrecognized action " + action);
}
// Log out from SMB session
if (ses != null) {
Log.d(TAG, "Logging off session...");
try {
ses.logoff();
} catch (TransportException e) {
e.printStackTrace();
}
//Log.d(TAG, "Closing session...");
//ses.close(); // Execution would hang here, so I commented it out.
}
if (conn != null) {
Log.d(TAG, "Closing connection...");
try {
conn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (client != null) {
Log.d(TAG, "Closing client...");
client.close();
}
}
private void RunRecursiveReport(FileOutputStream report_stream, String dir_path) throws IOException {
// We do not start by listing dir_path itself.
List<FileIdBothDirectoryInformation> contents = ds.list(dir_path);
for (FileIdBothDirectoryInformation item : contents) {
String file_name = item.getFileName();
String file_fullpath = dir_path + "/" + file_name;
long file_attributes = item.getFileAttributes();
if (file_name.equals(".") || file_name.equals("..")) { continue; }
FileTime mTime = item.getLastWriteTime();
FileTime cTime = item.getChangeTime();
if (EnumWithValue.EnumUtils.isSet(file_attributes, FILE_ATTRIBUTE_DIRECTORY)) {
String line = "d " + mTime.toEpoch(TimeUnit.SECONDS) + " " + cTime.toEpoch(TimeUnit.SECONDS) + " " + file_fullpath + "\n";
report_stream.write(line.getBytes());
RunRecursiveReport(report_stream, file_fullpath);
} else {
long sizeInBytes = item.getEndOfFile();
Log.d(TAG, "EOF: " + sizeInBytes + " and Allocation: " + item.getAllocationSize() + " for " + file_fullpath);
String line = "f " + mTime.toEpoch(TimeUnit.SECONDS) + " " + cTime.toEpoch(TimeUnit.SECONDS) + " " + sizeInBytes + " " + file_fullpath + "\n";
report_stream.write(line.getBytes());
}
}
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "All work complete");
}
}
|
package EntityManagers;
import java.util.List;
import Entities.Customer;
import Entities.Film;
import Entities.Ticket;
public interface TicketManager {
// Create
public void persistTicket(Ticket input);
// Read
public List<Ticket> getTicketByFilm(int id);
public List<Ticket> getTicketByCustomer(String email);
// Delete
public void deleteTicket(int id);
}
|
package gov.nih.mipav.plugins;
/**
* This interface binds a PlugIn to a PlugInBundle. Every PlugInBundle contains a list of BundledPlugInInfos
* that may also be PlugIns. These BundledPlugInInfos can be run by specifying an index of the PlugInBundle's
* <code>run(int index)</code> method.
*
* @author mccreedy
*/
public interface BundledPlugInInfo {
/**
* Specifies the menu structure of a particular plug-in. This menu structure is,
* by default, displayed as a sub-menu of a given PlugInBundle.
*/
public String[] getCategory();
/**
* Returns the name of the plug-in. This could possibly be used for scripting purposes.
*/
public String getName();
}
|
package ru.client.model;
public class Products {
private int id;
private int type;
private String name;
public Products() {
}
public Products(int type, String name) {
this.type = type;
this.name = name;
}
public Products(int id, int type, String name) {
this.id = id;
this.type = type;
this.name = name;
}
@Override
protected Object clone() throws CloneNotSupportedException {
Products products = new Products(this.id, this.type, this.name);
return products;
}
@Override
public String toString() {
return "Products{" +
" id=" + id +
", type=" + type +
", name=" + name +
'}';
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
|
package am.bit.guessnumber;
import java.util.Random;
public class NumberGenrator {
private int number;
int getNumber() {
return number;
}
void setNumber(int number) {
this.number = number;
}
NumberGenrator() {
Random random = new Random(15);
this.number = random.nextInt(100);
}
}
|
package model;
/**
* @author Qi Yin
*/
public class Name {
private String firstName;
private String middleName;
private String lastName;
private String fullName;
public Name(){
firstName = "";
middleName = "";
lastName = "";
fullName = "";
}
public Name(String firstName, String middleName, String lastName){
this();
setFirstName(firstName);
setMiddleName(middleName);
setLastName(lastName);
String fullName = "";
fullName += firstName;
fullName += middleName.isEmpty() || middleName == null ? "" : " " + middleName;
fullName += " " + lastName;
setFullName(fullName);
}
public Name(String fullName){
this();
setFullName(fullName);
String[] names = fullName.split(" ");
setFirstName(names[0]);
if(names.length == 3) {
setMiddleName(names[1]);
}
setLastName(names[names.length - 1]);
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getMiddleName() {
return middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String toString() {
return fullName;
}
}
|
package sop.util.io;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TimeZone;
import java.util.UUID;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import eu.medsea.mimeutil.MimeUtil;
import sop.util.BaseSys;
import sop.util.Sys;
/**
* @Author: LCF
* @Date: 2020/1/9 11:17
* @Package: sop.util.io
*/
public class FileUtil {
public static final String MIME_TXT = "text/plain";
public static final String MIME_RTF = "application/rtf";
public static final String MIME_HTM = "text/html";
public static final String MIME_PDF = "application/pdf";
public static final String MIME_PS = "application/postscript";
public static final String MIME_TIF = "image/tiff";
public static final String MIME_PNG = "image/png";
public static final String MIME_GIF = "image/gif";
public static final String MIME_JPG = "image/jpeg";
protected static final int BUFFER_SIZE = 4096;
private static final Logger logger = LoggerFactory.getLogger(FileUtil.class);
private static final Hashtable<String, String> mimeSet;
static {
mimeSet = new Hashtable<String, String>();
mimeSet.put("txt", MIME_TXT);
mimeSet.put("rtf", MIME_RTF);
mimeSet.put("htm", MIME_HTM);
mimeSet.put("html", MIME_HTM);
mimeSet.put("pdf", MIME_PDF);
mimeSet.put("eps", MIME_PS);
mimeSet.put("tif", MIME_TIF);
mimeSet.put("png", MIME_PNG);
mimeSet.put("gif", MIME_GIF);
mimeSet.put("jpg", MIME_JPG);
}
static {
eu.medsea.mimeutil.MimeUtil.registerMimeDetector("eu.medsea.mimeutil.detector.MagicMimeMimeDetector");
eu.medsea.mimeutil.MimeUtil.registerMimeDetector("eu.medsea.mimeutil.detector.ExtensionMimeDetector");
}
/**
* Append input to the output file
*
* @param input File input
* @param output Output file
* @throws IOException
*/
public static void appendFile(File input, File output) throws IOException {
copyFile(input, output, true);
}
/**
* Append content to the inFile
*
* @param inFile File to be append on
* @param content String content to append
* @throws IOException
*/
public static void appendFile(File inFile, String content) throws IOException {
appendFile(inFile, content, true);
}
/**
* Append content to the inFile
*
* @param inFile File to be append on
* @param content String content to append
* @param append whether append content to file or not
* @throws IOException
*/
public static void appendFile(File inFile, String content, boolean append) throws IOException {
FileWriter oFW = null;
BufferedWriter oBW = null;
PrintWriter out = null;
File parentD = inFile.getParentFile();
if (!parentD.exists()) {
boolean mkD = parentD.mkdirs();
if (!mkD) {
throw new IOException("Unable to make parent diretory," + parentD);
}
}
try {
oFW = new FileWriter(inFile, append);
oBW = new BufferedWriter(oFW);
out = new PrintWriter(oBW, true);
out.println(content);
} catch (IOException ioe) {
throw ioe;
} finally {
if (out != null)
out.close();
if (oBW != null)
oBW.close();
if (oFW != null)
oFW.close();
}
}
/**
* Build file's parent dir if not exists
*
* @param inFile File to be checked.
* @throws IOException
*/
public static void buildDir(File inFile) throws IOException {
File parentD = inFile.getParentFile();
if (!parentD.exists()) {
boolean mkD = parentD.mkdirs();
if (!mkD) {
throw new IOException("Unable to make parent diretory," + parentD);
}
}
}
/**
* Build file's parent dir if not exists
*
* @param inFile File to be checked.
* @throws IOException
*/
public static void buildDir(String inFile) throws IOException {
File parentD = new File(inFile).getParentFile();
if (!parentD.exists()) {
boolean mkD = parentD.mkdirs();
if (!mkD) {
throw new IOException("Unable to make parent diretory," + parentD);
}
}
}
/**
* Concat input1 & input2 and the generate the output file
*
* @param input1 First file
* @param input2 Second file
* @param output Write the output to this file
* @throws IOException
*/
public static void concatFile(File input1, File input2, File output) throws IOException {
copyFile(input1, output);
appendFile(input2, output);
}
/**
* Copy only the content of a directory into another directory.
*
* @param srcPath the source directory
* @param destinationPath the destination directory
*/
public static void copyDir(File srcDir, File destDir) throws IOException {
if (srcDir.isDirectory()) {
if (destDir.exists() != true) {
boolean mkD = destDir.mkdirs();
if (!mkD) {
throw new IOException("Unable to make destDir," + destDir);
}
}
String list[] = srcDir.list();
for (int i = 0; i < list.length; i++) {
String src = srcDir.getAbsolutePath() + System.getProperty("file.separator") + list[i];
String dest = destDir.getAbsolutePath() + System.getProperty("file.separator") + list[i];
copyDir(new File(src), new File(dest));
}
}
}
public static void purgeFiles(File purgeDir, Date currDate, int retentionPeriod,
String dirPurgeType) throws IOException {
FilesRemover.purgeFiles(purgeDir, currDate, retentionPeriod, dirPurgeType);
}
public static void removeFiles(List<File> fileL, File houseKeepDir) {
FilesRemover.removeFiles(fileL, houseKeepDir);
}
public static void removeFolder(File folder) {
FilesRemover.removeFolder(folder);
}
public static void removeFile(File file) {
FilesRemover.removeFile(file);
}
/**
* Copy input file to the output
*
* @param input Input
* @param output Output
* @throws IOException
*/
public static void copyFile(File input, File output) throws IOException {
copyFile(input, output, false);
}
/**
* Read the file to string
*
* @param inFile input file
* @return String content
* @throws IOException
*/
public static String readFile(File inFile) throws IOException {
return FileUtils.readFileToString(inFile);
}
/**
* Write content to the inFile
*
* @param inFile File to write upon
* @param content String content
* @throws IOException
*/
public static void writeFile(File inFile, String content) throws IOException {
DataOutputStream dos = null;
try {
dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(inFile)));
dos.writeBytes(content);
} catch (IOException ioe) {
ioe.printStackTrace();
throw ioe;
} finally {
if (dos != null)
dos.close();
}
}
/**
* Write map entries to the file
*
* @param <T> Key
* @param <E> Value
* @param map Write the map entries to the file
* @param inFile File to write upon
* @throws IOException
*/
public static <T, E> void writeFile(Map<T, E> map, File inFile) throws IOException {
FileOutputStream fos = null;
BufferedOutputStream bos = null;
PrintWriter out = null;
try {
fos = new FileOutputStream(inFile);
bos = new BufferedOutputStream(fos);
out = new PrintWriter(bos);
Iterator<Entry<T, E>> entryI = map.entrySet().iterator();
Entry<T, E> entry;
while (entryI.hasNext()) {
entry = entryI.next();
out.println(entry.getKey() + "=" + entry.getValue());
}
out.flush();
} catch (IOException ioe) {
ioe.printStackTrace();
throw ioe;
} finally {
try {
if (out != null)
out.close();
if (bos != null)
bos.close();
if (fos != null)
fos.close();
} catch (IOException ioe) {
}
}
}
/**
* Copy input file to the output
*
* @param input Input
* @param output Output
* @param append true if append
* @throws IOException
*/
private static void copyFile(File input, File output, boolean append) throws IOException {
FileInputStream in = new FileInputStream(input);
FileOutputStream out = new FileOutputStream(output.getPath(), append);
byte[] buffer = new byte[BUFFER_SIZE];
int numRead = in.read(buffer);
while (numRead > 0) {
out.write(buffer, 0, numRead);
numRead = in.read(buffer);
}
out.close();
in.close();
}
/*
* Get the extension of a file.
*/
public static String getExtension(String fileName) {
String ext = "";
int i = fileName.lastIndexOf('.');
if (i > 0) {
ext = fileName.substring(i + 1).toLowerCase();
}
return ext;
}
public static String getMimeType(URL url) {
try {
return getMimeType(url.openStream());
} catch (Exception e) {
logger.error("", e);
return null;
}
}
public static String getMimeType(File file) {
String typeStr = null;
Collection types = MimeUtil.getMimeTypes(file);
if (types != null && types.size() >= 1) {
for (Object type : types) {
logger.debug("" + type);
typeStr = String.valueOf(type);
break;
}
}
return typeStr;
}
public static String getMimeType(InputStream ins) {
String typeStr = null;
Collection types = MimeUtil.getMimeTypes(ins);
if (types != null && types.size() >= 1) {
for (Object type : types) {
logger.debug("" + type);
typeStr = String.valueOf(type);
break;
}
}
return typeStr;
}
public static String getMimeType(byte[] b) {
String typeStr = null;
Collection types = MimeUtil.getMimeTypes(b);
if (types != null && types.size() >= 1) {
for (Object type : types) {
logger.debug("" + type);
typeStr = String.valueOf(type);
}
}
return typeStr;
}
/***********************************
*
* @param InputStream
* @param String
* @return ture = no virus false = has virus and delete file
* @throws Exception
*/
public static boolean checkVirus(InputStream fileinputstream, String filepath) throws IOException {
boolean result = false;
String filename = UUID.randomUUID().toString() + ".tmp";
// String filepath = System.props.getProperty("antivirus.file.path");
// InputStream in = new BufferedInputStream(new
// FileInputStream("avparam.properties"));
// InputStream in = (new
// FileUtils()).getClass().getResourceAsStream("/"+"avparam.properties");
// System.out.println("avparam.properties " + in);
// PropertyResourceBundle properties = new PropertyResourceBundle(in);
// String filepath = "d:\\testing\\";
// String filepath = properties.getString("antivirus.file.path");
createFile(fileinputstream, filename, filepath);
File file = new File(filepath, filename);
result = file.exists();
file.delete();
return result;
}
/**
* create file
*
* @param fileinputstream
* @param filename
* @param filepath
*/
public static void createFile(InputStream fileinputstream, String filename, String filepath) {
try {
// FileInputStream fIn = new FileInputStream("e:/in.txt");
System.out.println("File Name: " + filename);
File dir = new File(filepath);
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir, filename);
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream fOut = new FileOutputStream(file);
while (fileinputstream.available() > 0) {
byte[] b = new byte[10];
int nResult = fileinputstream.read(b);
if (nResult == -1)
break;
fOut.write(b, 0, nResult);
}
fileinputstream.close();
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Generate a unique file name
*
* @return string
*/
public static String getUniqueFileName(String originalName) {
originalName = StringUtils.trimToEmpty(originalName);
String hash = StringUtils.leftPad(String.valueOf(Math.abs(originalName.hashCode() + BaseSys.getTimestamp().hashCode())), 10, "0");
originalName = StringUtils.deleteWhitespace(originalName);
String[] tokens = StringUtils.split(originalName, ".");
String ext = null;
String name = "";
if (tokens != null && tokens.length > 0) {
name = tokens[0];
if (tokens.length > 1) {
ext = tokens[tokens.length - 1];
}
}
if (name != null && name.length() > 20) {
name = StringUtils.left(name, 20);
}
name = StringUtils.rightPad(name, 20, "a");
name = StringUtils.lowerCase(name);
if (ext != null) {
return StringUtils.join(new String[]{name, "_", hash, ".", ext});
} else {
return StringUtils.join(new String[]{name, "_", hash,});
}
}
/**
* Generate a unique file name
*
* @return string
*/
public static String getUniqueFileName() {
return getUniqueFileName(null);
}
/**
* Format the status file name
*
* @param oriFileName Original file name
* @return Formatted file name
*/
public static String appendDateTimeToFileName(String oriFileName) {
StringBuffer buf = new StringBuffer();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSS");
sdf.setTimeZone(TimeZone.getTimeZone("GMT+08:00"));
String dateS = sdf.format(new Date());
buf.append(dateS);
buf.append("-");
buf.append(oriFileName);
return buf.toString();
}
public static String mergeSubDirectory(String[] array) {
if (array == null) {
return null;
}
StringBuilder sb = new StringBuilder();
for (String p : array) {
if (p != null) {
p = p.replace('\\', '/');
if (!p.startsWith("/")) {
p = "/" + p;
}
if (p.endsWith("/")) {
p = StringUtils.removeEnd(p, "/");
}
}
sb.append(p);
}
sb.append("/");
String path = sb.toString();
if (Sys.isUnix()) {
return path;
} else {
return StringUtils.removeStart(path, "/");
}
}
/**
* @param response - HTTP servlet response
* @param io - input Stream.
* @param mimeType - context type
* @param fileName - download save as file name.
* @return
*/
public static boolean downloadFile(HttpServletResponse response, InputStream inputStream, String mimeType, String fileName) {
ServletOutputStream os = null;
try {
String contentDisposition = "attachment; filename=\"" + fileName + "\";";
response.setHeader("Content-Disposition", new String(contentDisposition.getBytes("UTF-8"), "ISO-8859-1"));
response.setContentType(mimeType);
os = response.getOutputStream();
writeToOutputStream(inputStream, os);
return true;
} catch (Exception e) {
logger.error("error in downloading file.", e);
return false;
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
}
}
if (os != null) {
try {
os.close();
} catch (IOException e) {
}
}
}
}
private static void writeToOutputStream(InputStream fis, OutputStream os) throws IOException {
byte[] buffer = new byte[1024];
int length = 0;
while (true) {
length = fis.read(buffer);
if (length == -1) {
break;
}
os.write(buffer, 0, length);
}
}
public boolean isMimeMatchExt(String fileName, String mime) {
return mime.equals(mimeSet.get(getExtension(fileName)));
}
}
|
package edu.mum.sonet.models;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.OnDelete;
import org.hibernate.annotations.OnDeleteAction;
import javax.persistence.*;
import javax.validation.constraints.NotEmpty;
import java.time.LocalDateTime;
@Data
@NoArgsConstructor
@Entity
public class Comment extends BaseEntity {
@Lob
@NotEmpty
private String text;
private Boolean isHealthy = true;
private Boolean isDisabled = false;
@ManyToOne
@JsonIgnoreProperties(value = {"authProvider", "posts", "oldPassword", "claims", "followers", "following", "unhealthyContentCount"})
private User author;
@CreationTimestamp
private LocalDateTime creationDate;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "post_id", nullable = false)
@OnDelete(action = OnDeleteAction.CASCADE)
@JsonIgnore
private Post post;
}
|
package teste;
import controller.ClienteController;
import controller.PetsController;
import model.Cliente;
import model.Pets;
import java.util.List;
import static org.junit.Assert.*;
public class PetsControllerTest {
private PetsController petsController = new PetsController();
private ClienteController clienteController = new ClienteController();
@org.junit.Test
public void cadastrarPet() {
Cliente cliente = new Cliente("Carlos", "15975325896", "88996358596");
clienteController.cadastrarCliente(cliente);
boolean resultado = petsController.cadastrarPet(new Pets("","Poodle", cliente));
boolean resultado2 = petsController.cadastrarPet(new Pets("Bob","", cliente ));
boolean resultado3 = petsController.cadastrarPet(new Pets("Bob","Poodle", null ));
boolean resultado4 = petsController.cadastrarPet(new Pets("Bo1b","Poodle", cliente ));
boolean resultado5 = petsController.cadastrarPet(new Pets("Bob","Poo1dle", cliente ));
boolean resultado6 = petsController.cadastrarPet(new Pets("Bob","Poodle", cliente ));
assertFalse(resultado);
assertFalse(resultado2);
assertFalse(resultado3);
assertFalse(resultado4);
assertFalse(resultado5);
assertTrue(resultado6);
}
@org.junit.Test
public void removerPet() {
Cliente cliente = new Cliente("Carlos", "15975325896", "88996358596");
clienteController.cadastrarCliente(cliente);
petsController.cadastrarPet(new Pets("Bob","Poodle",cliente));
petsController.cadastrarPet(new Pets("Bobo","Chihuahua",cliente));
boolean resultado = petsController.removerPet(1);
assertTrue(resultado);
}
@org.junit.Test
public void editarPet() {
Cliente cliente = new Cliente("Carlos", "15975325896", "88996358596");
clienteController.cadastrarCliente(cliente);
boolean resultado = petsController.cadastrarPet(new Pets("Bob","Poodle",cliente));
assertTrue(resultado);
Pets pet = new Pets("Bobo", "Poodle", cliente);
boolean resultado2 = petsController.editarPet(pet,1);
assertTrue(resultado2);
Pets pet2 = new Pets("", "", cliente);
boolean resultado3 = petsController.editarPet(pet2,1);
assertFalse(resultado3);
}
@org.junit.Test
public void listarPet() {
Cliente clientee = new Cliente("Carloss", "15975325896", "88996358596");
clienteController.cadastrarCliente(clientee);
petsController.cadastrarPet(new Pets("Bob","Poodle", clientee ));
petsController.cadastrarPet(new Pets("Bobe","Chitsu", clientee ));
List<Pets> pets = petsController.listarPet();
for (Pets pet: pets ) {
System.out.println(pet.toString());
}
}
@org.junit.Test
public void validarPet() {
Cliente cliente = new Cliente("Carlos", "15975325896", "88996358596");
clienteController.cadastrarCliente(cliente);
boolean resultado = petsController.validarPet(new Pets("","Poodle", cliente));
boolean resultado2 = petsController.validarPet(new Pets("Bob","", cliente ));
boolean resultado3 = petsController.validarPet(new Pets("Bob","Poodle", null ));
boolean resultado4 = petsController.validarPet(new Pets("Bo1b","Poodle", cliente ));
boolean resultado5 = petsController.validarPet(new Pets("Bob","Poo1dle", cliente ));
boolean resultado6 = petsController.validarPet(new Pets("Bob","Poodle", cliente ));
assertFalse(resultado);
assertFalse(resultado2);
assertFalse(resultado3);
assertFalse(resultado4);
assertFalse(resultado5);
assertTrue(resultado6);
}
@org.junit.Test
public void adicionarPetAoCliente(){
Cliente cliente = new Cliente("Carlos", "15975325896", "88996358596");
clienteController.cadastrarCliente(cliente);
boolean resultado = petsController.adicionarPetAoCliente(new Pets("Vampeta","vampetaço", cliente));
assertTrue(resultado);
}
@org.junit.Test
public void removerPetDoCliente(){
Cliente cliente = new Cliente("Carlos", "15975325896", "88996358596");
clienteController.cadastrarCliente(cliente);
boolean resultado = petsController.adicionarPetAoCliente(new Pets("Vampeta","vampetaço", cliente));
assertTrue(resultado);
boolean resultado2 = petsController.removerPetDoCliente(cliente.getPets().get(0));
assertTrue(resultado2);
}
} |
package com.pwc.io;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import static com.pwc.util.Convert.intToByte;
public class DataOutputBufferStream extends DataOutputStream {
private final int bufferSize = 1024 * 1024;
private byte[] buffer = new byte[bufferSize * 4];
private int size = 0;
public DataOutputBufferStream(OutputStream out) {
super(out);
}
public synchronized void write(int i) throws IOException {
if (isBufferFull()) {
this.flush();
this.put(i);
} else {
put(i);
}
}
private void put(int i) {
byte[] temp = intToByte(i);
buffer[size * 4] = temp[0];
buffer[size * 4 + 1] = temp[1];
buffer[size * 4 + 2] = temp[2];
buffer[size * 4 + 3] = temp[3];
this.size++;
}
@Override
public synchronized void flush() throws IOException {
if (this.size != 0) {
out.write(buffer, 0, size * 4);
this.size = 0;
}
out.flush();
}
private boolean isBufferFull() {
return this.size == bufferSize;
}
}
|
package com.tpg.brks.ms.expenses.persistence.repositories;
import com.tpg.brks.ms.expenses.persistence.entities.ExpenseEntity;
import org.springframework.data.repository.NoRepositoryBean;
import org.springframework.data.repository.Repository;
@NoRepositoryBean
public interface ExpenseRepository extends Repository<ExpenseEntity, Long> {
}
|
package com.mabang.android.widget;
import android.content.Context;
import android.support.annotation.AttrRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import com.mabang.android.R;
/**
* Created by walke on 2018/3/14.
* email:1032458982@qq.com
*/
public class MapOverlayView extends FrameLayout {
private ImageView ivOverlay;
private TextView tvNumber;
public MapOverlayView(@NonNull Context context, String number, int iconId) {
super(context);
LayoutInflater.from(context).inflate(R.layout.view_to_bitmap,this);
tvNumber = ((TextView) findViewById(R.id.vtb_tvNumber));
ivOverlay = ((ImageView) findViewById(R.id.vtb_ivOverlay));
ivOverlay.setScaleType(ImageView.ScaleType.FIT_CENTER);
tvNumber.setText(number+"");
ivOverlay.setImageResource(iconId);
}
public MapOverlayView(@NonNull Context context) {
this(context,null);
}
public MapOverlayView(@NonNull Context context, @Nullable AttributeSet attrs) {
this(context, attrs,0);
}
public MapOverlayView(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr) {
super(context, attrs, defStyleAttr);
LayoutInflater.from(context).inflate(R.layout.view_to_bitmap,this);
tvNumber = ((TextView) findViewById(R.id.vtb_tvNumber));
ivOverlay = ((ImageView) findViewById(R.id.vtb_ivOverlay));
}
public TextView getTvNumber() {
return tvNumber;
}
public void setNumber(@NonNull String number){
tvNumber.setText(number);
}
}
|
package com.solo.bakingapp.recipe.list;
import android.support.test.espresso.IdlingRegistry;
import android.support.test.espresso.IdlingResource;
import android.support.test.espresso.contrib.RecyclerViewActions;
import android.support.test.filters.LargeTest;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import com.solo.bakingapp.R;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
@LargeTest
@RunWith(AndroidJUnit4.class)
public class RecipeListActivityTest {
private IdlingResource idlingResource;
@Rule
public ActivityTestRule<RecipeListActivity> mActivityTestRule = new ActivityTestRule<>(RecipeListActivity.class);
@Before
public void registerIdlingResource() {
idlingResource = mActivityTestRule.getActivity().getRecipesListViewModel().getIdlingResource();
IdlingRegistry.getInstance().register(idlingResource);
}
@Test
public void showRecipeFirstItemTest() {
onView(withId(R.id.recipes_list_recyclerview))
.perform(RecyclerViewActions.scrollToPosition(0))
.check(matches(isDisplayed()));
}
@Test
public void ClickFirstRecipe_OpenRecipeDetails() {
onView(withId(R.id.recipes_list_recyclerview))
.perform(RecyclerViewActions.actionOnItemAtPosition(0, click()));
onView(withId(R.id.ingredients_label_text_view))
.check(matches(isDisplayed()));
}
@After
public void unregisterIdlingResource() {
IdlingRegistry.getInstance().unregister(idlingResource);
}
}
|
package com.ishare.conn;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Date;
import java.util.Properties;
import java.util.Vector;
public class DBConnPool{
private int inUsed = 0;
private Vector<Connection> connections = new Vector();
private String dbSource;
private String driver;
public static String url;
public static String userName;
public static String password;
private int minConn;
private int maxConn;
private long timeOut;
private static DBConnPool pool = null;
public static DBConnPool getInstance()
{
if (pool == null)
pool = new DBConnPool();
return pool;
}
private DBConnPool() {
readConfig();
}
private void readConfig()
{
InputStream ins = null;
try {
ins = DBConnPool.class.getResourceAsStream("/datasource.properties");
Properties p = new Properties();
p.load(ins);
this.dbSource = p.getProperty("dbsource").trim();
this.driver = p.getProperty("driver").trim();
this.url = p.getProperty("url").trim();
this.userName = p.getProperty("username").trim();
this.password = p.getProperty("password").trim();
this.maxConn = Integer.parseInt(p.getProperty("maxconn").trim());
this.timeOut = Long.parseLong(p.getProperty("timeOut").trim());
} catch (IOException e) {
e.printStackTrace();
try{
ins.close();
} catch (IOException e1) {
e.printStackTrace();
}
}
finally
{
try
{
ins.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static Connection getConnection(){
Connection connection = null;
try {
connection = DriverManager.getConnection(url, userName, password);
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
// public Connection getConnection()
// {
// Connection con = null;
// con = dbConnection();
// if (con == null)
// con = getConnection(this.timeOut);
//
// if (con != null)
// this.inUsed += 1;
//
// return con;
// }
private Connection dbConnection() {
Connection conn = null;
label84: synchronized (this.connections) {
if (this.connections.size() > 0) {
conn = (Connection)this.connections.elementAt(0);
this.connections.removeElement(conn);
try {
if (conn.isValid(10)) break label84;
conn = dbConnection();
}
catch (SQLException e) {
conn = dbConnection();
}
} else if (this.inUsed < this.maxConn) {
conn = newConnection();
}
}
return conn;
}
private synchronized Connection getConnection(long timeout)
{
Connection conn = null;
long startTime = new Date().getTime();
try
{
synchronized (this) {
super.wait(200L); }
} catch (InterruptedException e) {
do {
e.printStackTrace();
long endTime = new Date().getTime();
if (endTime - startTime >= timeout)
return null;
}
while ((conn = dbConnection()) == null);
}
return conn;
}
public void returnConnection(Connection conn){
synchronized (this.connections) {
if (!(this.connections.contains(conn)))
return;
this.connections.addElement(conn);
this.inUsed -= 1;
}
synchronized (this) {
super.notifyAll();
}
}
public synchronized void release()
{
Connection conn = null;
synchronized (this.connections) {
try {
for (int i = 0; i < this.connections.size(); ++i) {
conn = (Connection)this.connections.elementAt(i);
if ((conn != null) && (!(conn.isClosed())))
conn.close();
this.inUsed -= 1;
}
} catch (SQLException e) {
e.printStackTrace();
}
this.connections.removeAllElements();
}
}
private Connection newConnection()
{
Connection con = null;
try {
Class.forName(this.driver);
con = DriverManager.getConnection(this.url, this.userName, this.password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.out.println("sorry can't find db driver!");
} catch (SQLException e1) {
e1.printStackTrace();
System.out.println("sorry can't create Connection!");
}
return con;
}
}
|
public class AverageScoreofTwoStudInThreePapers {
public static void main(String[] args)
{
int iArr[][] = {{60,55,70},{80,60,41}};
for(int i=0;i<2;i++)
{
double sum=0; int count=0;
for(int j=0;j<3;j++)
{
sum= sum+iArr[i][j];
count++;
}
System.out.printf("Average marks of student " +(i+1)+" in three papers: %.2f",sum/count);
System.out.println();
}
}
}
|
package com.google;
import org.testng.annotations.Test;
public class GooglePageTest {
@Test
public void GoogleTitleTest() {
System.out.println("This is my google page");
}
@Test
public void LoginTest() {
System.out.println("Login Page");
}
@Test
public void homepage() {
System.out.println("Home Page");
}
@Test
public void signout() {
System.out.println("Sign Out");
}
}
|
package modelo;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import persistencia.ArbolDAO;
import persistencia.Conexion;
import utilidades.DateClass;
//import javax.swing.JTree;
public class Arbol {
ArbolDAO adao;
String [][] bom;
ArrayList<Nodo> padresPrincipales = new ArrayList<>();
ArrayList<String> padresDescripcion = new ArrayList<>();
ArrayList<Nodo> listaArt = new ArrayList<>();
Nodo NodobyID = new Nodo();
Nodo buscaNodo = new Nodo();
DateClass date = new DateClass();
Nodo aDesc=null;
ArbolDAO arbolDAO;
// public static void main(String[] args) {
// Arbol x = new Arbol();
//
// }
public Arbol(){
arbolDAO = new ArbolDAO();
bom=arbolDAO.getBomMatriz();
padresPrincipales = arbolDAO.obtenerPadresPrincipales();
padresDescripcion = arbolDAO.obtenerPadresDescripcion();
// BOM
// 0padre
// 1hijo
// 2descripcion
// 3cantidad
// 4descripcion cantidad
// 5tipo
// 6generico
InicializarArbol();
//ArrayList<Nodo> m=getNodoByArticulo(5);
}
public ArrayList<String> getpadresDescripcion()
{
return padresDescripcion;
}
private void InicializarArbol(){
try{
//Para cada padrePrincipal le arma el arbol
for(Nodo a: padresPrincipales)
{
ArmaArbol(bom, a);
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("Problema en armar arbol en Arbol.java");
}
}
//bom: lo que levanto de la tabla BOM transformado en un array
//k: posicion de la bom que se esta usando en este momento
private void ArmaArbol(String bom[][],Nodo nodo)
{
// La primera vez entra con el nodo padreprincipal
// recorre la bom hasta encontrar q el padre coincide,
// una vez que lo encuentra setea al hijo segun la segunda columna de la bom
// y llama a la funcion con el hijo
// cuando no tiene mas hijo, aumenta el k y pregunta de ahi para abajo (bom[k][0])= nodo.getPadre
//
try{
for (int k=0; k<bom.length;k++)
{ // obtengo el id del articulo de ese nodo
String padre= nodo.getArt().getValor().toString();
while (bom[k][0]!=null &&(bom[k][0].equals(padre)) && k<30)
{
//Seteo idArt, idNodo
Nodo h = new Nodo(Integer.parseInt(bom[k][1]),Integer.parseInt(bom[k][6]));
// System.out.println(bom[k][3]);
h.setDescripcion(bom[k][2]);
h.setCantidad(Integer.parseInt(bom[k][3]));
h.setUm(bom[k][4]);
h.setTipo(Integer.parseInt(bom[k][5]));
h.setFecha_inicio(bom[k][6]);
h.setFecha_fin(bom[k][7]);
// System.out.println("fecha inicio BOM: "+ h.getFecha_inicio());
nodo.AgregarHijo(h);
// System.out.println("Valor:"+nodo.getId()+" cantidad:"+h.getCantidad()+" desc:"+h.getDescripcion());
h.setPadre(nodo);
//System.out.println("ARBOL: ");
//System.out.println("Padre: "+nodo.getArt().getValor()+"--hijo:"+h.getArt().getValor());
ArmaArbol(bom,h);
k++;
}
}
}catch (Exception e) {
e.printStackTrace();
System.out.println("Error en ArmaArbol");
}
return;
}
// public void MostrarArbol(){
// Jtree j=new Jtree(padresPrincipales, padresPrincipalesE);
// }
public void MostrarArbol(String fecha){
//transformo fecha en un objeto tipo Date y lo paso por parametro
Jtree j=new Jtree(padresPrincipales, fecha);
}
public void MostrarArbol(Nodo a,float cant,String fecha){
//explosiona el nodo
Jtree j=new Jtree(a,cant,fecha);
}
public Nodo getNodoByDescripcion (String desc)
{
Nodo a= null;
aDesc=null;
for(Nodo padre: padresPrincipales)
{
a=IterarDesc(padre,desc);
if(aDesc!=null)
{System.out.println(aDesc.getDescripcion()+"Nodo:"+ aDesc.getId());
return aDesc;
}
}
return a;
}
private Nodo IterarDesc(Nodo nodo, String desc)
{
if (nodo.GetHijos()!= null)
{ Nodo a=nodo;
if(a.getDescripcion().equals(desc)){
aDesc=a;
return a;
}
Iterator<Nodo> ListaHijos = nodo.GetHijos().iterator();
while (ListaHijos.hasNext())
{
a= ListaHijos.next();
if (a.getDescripcion().equals(desc))
{
aDesc=a;
return a; }
else
IterarDesc(a,desc);
}
}
return null;
}
//Buscar nodo segun el arituclo devuelve una lista
public ArrayList<Nodo> getNodoByArticulo (Integer idArt)
{
//ArrayList<Nodo> a= null;
listaArt=new ArrayList<>();
Nodo resultado;
for(Nodo padre: padresPrincipales)
{
resultado=IterarArt(padre,idArt);
if(resultado!=null)
listaArt.add(resultado);
}
return listaArt;
}
/*
public Nodo getPrimerNodoByArticuloId (int articuloId)
{
Nodo a= null;
aDesc=null;
for(Nodo padre: padresPrincipales)
{
a=IterarDesc(padre,desc);
if(aDesc!=null)
{System.out.println(aDesc.getDescripcion()+"Nodo:"+ aDesc.getId());
return aDesc;
}
}
return a;
}
*/
private Nodo IterarArt(Nodo nodo, Integer idArt)
{
if (nodo.GetHijos()!= null)
{ Nodo a=nodo;
if(a.getArt().getValor().equals(idArt)){
listaArt.add(a);
return a;
}
Iterator<Nodo> ListaHijos = nodo.GetHijos().iterator();
while (ListaHijos.hasNext())
{
a= ListaHijos.next();
if (a.getArt().getValor().equals(idArt))
{
listaArt.add(a);
return a; }
else
IterarArt(a,idArt);
}
}
return null;
}
// public Nodo getNodoByArt (Integer idArt)
// {
// //ArrayList<Nodo> a= null;
// Nodo NodoArt=null;
// for(Nodo padre: padresPrincipales)
// {
// if(NodoArt!=null)
// {System.out.println(NodobyID.getDescripcion()+"Nodo:"+ NodobyID.getId());
// return NodobyID;
// }
// }
//
// return listaArt;
// }
//
// private Nodo IterarArt1(Nodo nodo, Integer idArt)
// {
// if (nodo.GetHijos()!= null)
// { Nodo a=nodo;
// if(a.getArt().getValor().equals(idArt)){
// listaArt.add(a);
// return a;
// }
// Iterator<Nodo> ListaHijos = nodo.GetHijos().iterator();
//
// while (ListaHijos.hasNext())
// {
// a= ListaHijos.next();
// if (a.getArt().getValor().equals(idArt))
// {
// listaArt.add(a);
// return a; }
// else
// IterarArt(a,idArt);
// }
//
// }
// return null;
//
// }
//
public ArrayList<Nodo> getNodoByIdBom (Integer id)
{
//Devuelve un ArrayList de Nodos, con dos nodos, el padre y el hijo para ese id
ArrayList<Nodo> nodosBom = new ArrayList<>();
ArrayList<Integer> intBom = new ArrayList<>();
intBom=arbolDAO.buscaBom(id);
nodosBom.add(getNodoByArticulo(intBom.get(0)).get(0));
nodosBom.add(getNodoByArticulo(intBom.get(1)).get(0));
return nodosBom;
}
//BUSCAR NODO POR ID
public Nodo getNodoById (Integer id)
{
Nodo a= null;
NodobyID=null;
for(Nodo padre: padresPrincipales)
{
a=IterarId(padre,id);
if(NodobyID!=null)
{System.out.println(NodobyID.getDescripcion()+"Nodo:"+ NodobyID.getId());
return NodobyID;
}
}
return a;
}
private Nodo IterarId(Nodo nodo, Integer id)
{
if (nodo.GetHijos()!= null)
{ Nodo a=nodo;
if(a.getId().equals(id)){
NodobyID=a;
return a;
}
Iterator<Nodo> ListaHijos = nodo.GetHijos().iterator();
while (ListaHijos.hasNext())
{
a= ListaHijos.next();
if (a.getId().equals(id))
{
NodobyID=a;
return a; }
else
IterarId(a,id);
}
}
return null;
}
// TERMINA BUSCAR NODO POR ID
//id del nodo hijo que hay que eliminar
public void eliminarHijo(Integer id)
{
//obtengo todos los nodos que tengan el articulo con el id que viene por parametro
ArrayList<Nodo> listaNodo=getNodoByArticulo(id);
for (Nodo nodo: listaNodo)
{
System.out.println("ElimarHijo "+nodo.getArt().getValor());
}
}
public ArrayList<StringBuilder> ArmaListaPadre (Nodo nodo)
{
ArrayList<StringBuilder> listaPadre = new ArrayList<>();// crear nuevos StringBuilder
for(Nodo padre: padresPrincipales)
{
//Encontre el nodo dentro del arbol, y llamo a una funcion con el nodo y un nuevo sb
buscaNodo=null;
Nodo a=BuscarNodo(padre,nodo.getId()); //cuando entra a la funcion lo setea
if(buscaNodo!=null)
{
listaPadre.add(new StringBuilder());
StringBuilder stringB= new StringBuilder();
stringB.append(ArmaLista(buscaNodo, listaPadre.get(listaPadre.size()-1),0)); //llama a la funcion con el nodo, un nuevo StringBuilder
stringB = new StringBuilder(stringB.substring(0, stringB.length()-2));
listaPadre.set(listaPadre.size()-1,stringB);
System.out.println(listaPadre.get(listaPadre.size()-1));
}
}
return listaPadre;
}
private Nodo BuscarNodo (Nodo nodo, Integer valor)
{
Nodo a= null;
if (nodo.GetHijos()!= null)
{ Iterator<Nodo> ListaHijos = nodo.GetHijos().iterator();
//Nodo a= new Nodo(-1);
while (ListaHijos.hasNext())
{
a= ListaHijos.next();
if (a.getId().equals(valor))
{ buscaNodo=a;
return null; }
else
BuscarNodo(a,valor);
//return a;
}
//return a;
}
return null;
}
//siempre llamar esta funcion con un 0 al final
private StringBuilder ArmaLista (Nodo nodo, StringBuilder sb, int primeraVezCero)
{
if(primeraVezCero==0)
sb.append("El Articulo "+nodo.getDescripcion()+" Compone a: ");
while (nodo.getPadre()!=null)
{
sb.append(nodo.getPadre().getDescripcion().toString()+", ");
ArmaLista(nodo.getPadre(), sb,primeraVezCero+1);
return sb;
//sigue llamando con un 5
}
return sb;
}
public ArrayList<Nodo> getPadresPrincipales ()
{
return padresPrincipales;
}
/*
public void getAlternativos (Nodo x)
{
Integer padre=null;
if(x.getPadre()!=null)
padre=x.getPadre().getId();
Integer hijo=x.getId();
Integer id_generico=null;
String principal_id= "Select generico_id from Bom where padre="+padre+" and hijo=" +hijo+ " and borrado=0";
PreparedStatement stm;
try {
Conexion cc= new Conexion();
Connection con= cc.getConexion();
stm = con.prepareStatement(principal_id);
ResultSet rs = stm.executeQuery();
rs.next();
id_generico=rs.getInt(1);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String alternativos = "Select artGenerico_id from [Articulos Alternativos] where artPrincipal_id="+ id_generico;
try {
Conexion cc2= new Conexion();
Connection con2= cc2.getConexion();
stm = con2.prepareStatement(alternativos);
ResultSet rs = stm.executeQuery();
while (rs.next())
{
System.out.println(rs.getInt(1));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}*/
public ArrayList<Nodo> obtenerPadres ()
{
arbolDAO = new ArbolDAO();
return arbolDAO.obtenerPadres();
}
}
|
package com.ms.module.wechat.clear.activity.clear;
import com.chad.library.adapter.base.entity.node.BaseExpandNode;
import com.chad.library.adapter.base.entity.node.BaseNode;
import org.jetbrains.annotations.Nullable;
import java.util.List;
public class UpGroupNode extends BaseExpandNode {
private List<BaseNode> childNode;
private long size;
private boolean check;
public long getSize() {
return size;
}
public void setSize(long size) {
this.size = size;
}
public UpGroupNode(List<BaseNode> childNode, long size, boolean check) {
this.childNode = childNode;
this.size = size;
this.check = check;
}
public UpGroupNode(List<BaseNode> datas) {
this.childNode = datas;
}
@Nullable
@Override
public List<BaseNode> getChildNode() {
return childNode;
}
public boolean isCheck() {
return check;
}
public void setCheck(boolean check) {
this.check = check;
}
}
|
package com.examples;
import java.util.List;
import net.droidsolutions.droidcharts.core.data.XYDataset;
import net.droidsolutions.droidcharts.core.data.xy.XYSeries;
import net.droidsolutions.droidcharts.core.data.xy.XYSeriesCollection;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
public class DemoCharts extends Activity {
private static final String TAG = "DemoCharts";
private final String chartTitle = "My Daily Starbucks Allowance";
private final String xLabel = "Week Day";
private final String yLabel = "Allowance";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "DemoCharts.onCreate()");
// Get the passed parameter values
List<double[]> wrappedList = (List<double[]>) getIntent().getSerializableExtra("param");
Log.d(TAG, "passed extra " + wrappedList + " is of type " + wrappedList.getClass());
double[][] data = (double[][]) wrappedList.toArray(new double[wrappedList.size()][]);
Log.d(TAG, "Data Param:= " + data);
XYDataset dataset = createDataset("My Daily Starbucks Allowance", data);
XYLineChartView graphView = new XYLineChartView(this, chartTitle,
xLabel, yLabel, dataset);
setContentView(graphView);
}
/**
* Creates an XYDataset from the raw data passed in.
*/
private XYDataset createDataset(String title, double[][] dataVals) {
final XYSeries series1 = new XYSeries(title);
for (double[] tuple : dataVals) {
series1.add(tuple[0], tuple[1]);
}
// Create a collection to hold various data sets
final XYSeriesCollection dataset = new XYSeriesCollection();
dataset.addSeries(series1);
return dataset;
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
Toast.makeText(this, "Orientation Change", Toast.LENGTH_SHORT).show();
// Let's get back to our DemoList view
Intent intent = new Intent(this, DemoList.class);
startActivity(intent);
// Finish current Activity
this.finish();
}
} |
package com.javabeans.orders;
import javax.faces.bean.ManagedBean;
import java.time.LocalDateTime;
@ManagedBean
public class Orders {
//Order_Details Table Fields
private int ref_no;
private int order_id;
private int product_id;
private int user_id;
private int quantity;
private float total_amount;
//Products Table Fields
private String product_category;
private String product_name;
private float price;
private String product_image;
//Order Summary Variables
private float gross;
private float vat;
private float shippingFee;
private float overallTotal;
//Orders Table Fields
private String status;
private LocalDateTime date_ordered;
//Users Table Fields
private String first_name;
private String last_name;
public Orders(float total_amount, float gross, float vat, float shippingFee, float overallTotal) {
this.total_amount = total_amount;
this.gross = gross;
this.vat = vat;
this.shippingFee = shippingFee;
this.overallTotal = overallTotal;
}
public Orders(int order_id, String product_name, float price, int quantity, String status, float total_amount,
String first_name, String last_name) {
this.order_id = order_id;
this.product_name = product_name;
this.price = price;
this.quantity = quantity;
this.status = status;
this.total_amount = total_amount;
this.first_name = first_name;
this.last_name = last_name;
}
public Orders(int ref_no, int order_id, int product_id, int user_id, int quantity, float total_amount,
String product_category, String product_name, float price, String product_image) {
this.ref_no = ref_no;
this.order_id = order_id;
this.product_id = product_id;
this.user_id = user_id;
this.quantity = quantity;
this.total_amount = total_amount;
this.product_category = product_category;
this.product_name = product_name;
this.price = price;
this.product_image = product_image;
}
public Orders() {
}
public int getRef_no() {
return ref_no;
}
public void setRef_no(int ref_no) {
this.ref_no = ref_no;
}
public int getOrder_id() {
return order_id;
}
public void setOrder_id(int order_id) {
this.order_id = order_id;
}
public int getProduct_id() {
return product_id;
}
public void setProduct_id(int product_id) {
this.product_id = product_id;
}
public int getUser_id() {
return user_id;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public float getTotal_amount() {
return total_amount;
}
public void setTotal_amount(float total_amount) {
this.total_amount = total_amount;
}
public String getProduct_category() {
return product_category;
}
public void setProduct_category(String product_category) {
this.product_category = product_category;
}
public String getProduct_name() {
return product_name;
}
public void setProduct_name(String product_name) {
this.product_name = product_name;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public String getProduct_image() {
return product_image;
}
public void setProduct_image(String product_image) {
this.product_image = product_image;
}
public float getGross() {
return gross;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public LocalDateTime getDate_ordered() {
return date_ordered;
}
public void setDate_ordered(LocalDateTime date_ordered) {
this.date_ordered = date_ordered;
}
public void setGross(float gross) {
this.gross = gross;
}
public float getVat() {
return vat;
}
public void setVat(float vat) {
this.vat = vat;
}
public float getShippingFee() {
return shippingFee;
}
public void setShippingFee(float shippingFee) {
this.shippingFee = shippingFee;
}
public float getOverallTotal() {
return overallTotal;
}
public void setOverallTotal(float overallTotal) {
this.overallTotal = overallTotal;
}
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;
}
} |
package com.minismap.data;
import java.util.StringTokenizer;
/**
* Created by nbp184 on 2016/03/21.
*/
public class Enemy {
public static Enemy load(String line) {
StringTokenizer tokens = new StringTokenizer(line, Seperators.INSIDE_MAP);
return new Enemy(tokens.nextToken(), tokens.nextToken(), Integer.parseInt(tokens.nextToken()), Integer.parseInt(tokens.nextToken()));
}
public String name;
public String abbreviation;
public GridPoint location;
public Enemy(String name, String abbreviation, int x, int y) {
this.name = name;
this.abbreviation = abbreviation;
location = new GridPoint(x, y);
}
public String save() {
return name +Seperators.INSIDE_MAP +abbreviation +Seperators.INSIDE_MAP +location.x + Seperators.INSIDE_MAP +location.y;
}
}
|
package com.cigc.limit.service;
import com.cigc.limit.utils.DateUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.collect.Tuple;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.security.acl.LastOwnerException;
import java.util.*;
@Component
public class TaoPai {
@Autowired
private TransportClient client;
@Autowired
private JdbcTemplate jdbcTemplate;
//双模点
private static List<String> CJDID_List = new ArrayList<String>();
private static Long defTime = 60000L;
// private static int startTime = 1;
// private static int endTime = 0;
public void searchAllData() {
String sql = "select distinct(zp.CJDID) FROM HC_ZS_STATIC_CJD_RFID rfid INNER JOIN HC_ZS_STATIC_CJD_ZP zp on rfid.CJDID=zp.CJDID";
CJDID_List = jdbcTemplate.queryForList(sql, String.class);
System.out.println("-------------------------------------------");
String index = "cqct_20180508_*";
String type = "AfterVehicle";
//建立查询条件
BoolQueryBuilder rootQuery = QueryBuilders.boolQuery();
//过滤融合成功数据
ExistsQueryBuilder sbuilder = QueryBuilders.existsQuery("tollgateCode");
//过滤单模点
TermsQueryBuilder termsQuery = QueryBuilders.termsQuery("cjdid", CJDID_List);
//按车牌号和车牌颜色进行group by聚合,
AggregationBuilder plateTerms =
AggregationBuilders.terms("groupCode").field("plateCode").size(Integer.MAX_VALUE)
.subAggregation(AggregationBuilders.terms("groupColor").field("plateColor").size(Integer.MAX_VALUE)
.subAggregation(AggregationBuilders.terms("groupCJDID").field("cjdid").size(Integer.MAX_VALUE)
.subAggregation(AggregationBuilders.terms("groupTime").field("passTime").size(Integer.MAX_VALUE)))
);
//查出一天数据
// RangeQueryBuilder startQuery = QueryBuilders.rangeQuery("passTime").from(DateUtils.getMillis(-startTime, true));
// RangeQueryBuilder endQuery = QueryBuilders.rangeQuery("passTime").to(DateUtils.getMillis(0, true));
Date date=new Date();
int hours=date.getHours();
int miute=date.getMinutes();
RangeQueryBuilder startQuery = QueryBuilders.rangeQuery("passTime").from(DateUtils.getTimeStmap(-(hours*60+miute+1440*3+1440)));
RangeQueryBuilder endQuery = QueryBuilders.rangeQuery("passTime").to(DateUtils.getTimeStmap(-(hours*60+miute+1440*3+720)));
rootQuery.mustNot(sbuilder);
rootQuery.must(startQuery);
rootQuery.must(endQuery);
rootQuery.must(termsQuery);
//setFrom,setSize设置分页
SearchResponse response = client.prepareSearch(index)
.setTypes(type)
.setQuery(rootQuery)
.addAggregation(plateTerms)
.setExplain(true).execute().actionGet();
//聚合查询分桶统计,
Tuple<String, String> tuple;
String code = "";
String color = "";
String cjdId = "";
Long pTime;
TreeMap<Long, String> valueMap;
TreeMap<Long, String> timeMap;
//RFID数据,key为车牌ID+车牌颜色,value:(时间+地点ID)集合
Map<String, TreeMap<Long, String>> rfidMap = new HashMap<>();
Terms groupCode = response.getAggregations().get("groupCode");
//车牌桶
for (Terms.Bucket codeBucket : groupCode.getBuckets()) {
valueMap = new TreeMap<>();
Terms groupColor = codeBucket.getAggregations().get("groupColor");
code = codeBucket.getKeyAsString();
//颜色桶
for (Terms.Bucket colorBucket : groupColor.getBuckets()) {
Terms groupCjdId = colorBucket.getAggregations().get("groupCJDID");
color = colorBucket.getKeyAsString();
//cjdid桶
for (Terms.Bucket cjdidBucket : groupCjdId.getBuckets()) {
Terms groupTime = cjdidBucket.getAggregations().get("groupTime");
cjdId = cjdidBucket.getKeyAsString();
//时间桶
for (Terms.Bucket timeBucket : groupTime.getBuckets()) {
pTime = (Long) timeBucket.getKey();
valueMap.put(pTime, cjdId);
}
}
rfidMap.put(code + "-" + color, valueMap);
}
}
Map<String, TreeMap<Long, String>> finallyRfidMap = new HashMap<>();
//筛选大于5次的
Long old;
for (Map.Entry<String, TreeMap<Long, String>> entry : rfidMap.entrySet()) {
if (entry.getValue().size() > 5) {
finallyRfidMap.put(entry.getKey(), entry.getValue());
}
}
//筛选完成
rfidMap.clear();
System.out.println("++++++++++++++++++++" + finallyRfidMap.size());
//查抓拍
BoolQueryBuilder rootQuery2 = QueryBuilders.boolQuery();
//过滤单模点
TermsQueryBuilder termsQuery2 = QueryBuilders.termsQuery("cjdid", CJDID_List);
//过滤
ExistsQueryBuilder sbuilder2 = QueryBuilders.existsQuery("snapsotId");
//按车牌号和车牌颜色进行group by聚合,
AggregationBuilder plateTerms2 =
AggregationBuilders.terms("groupCJDID").field("cjdid").size(Integer.MAX_VALUE)
.subAggregation(AggregationBuilders.terms("groupColor").field("plateColor").size(Integer.MAX_VALUE)
.subAggregation(AggregationBuilders.terms("groupTime").field("passTime").size(Integer.MAX_VALUE)
.subAggregation(AggregationBuilders.terms("groupCode").field("plateCode").size(Integer.MAX_VALUE)))
);
rootQuery2.must(sbuilder2);
rootQuery2.must(startQuery);
rootQuery2.must(endQuery);
rootQuery2.must(termsQuery2);
SearchResponse response2 = client.prepareSearch("cqct_20180508_*").setTypes("ExceptionAfterVehicle")
.setQuery(rootQuery2)
.addAggregation(plateTerms2)
.setExplain(true).execute().actionGet();
String code2 = "";
String color2 = "";
String cjdId2 = "";
Long pTime2;
//抓拍数据输出格式,key:地点+车牌颜色,value:Map(时间:车牌号)
TreeMap<String, TreeMap<Long, String>> snapsotMap = new TreeMap<>();
String outKey;
TreeMap<Long, String> valueTree;
Terms groupCjdId2 = response2.getAggregations().get("groupCJDID");
//颜色桶
for (Terms.Bucket colorBucket : groupCjdId2.getBuckets()) {
Terms groupColor2 = colorBucket.getAggregations().get("groupColor");
cjdId2 = colorBucket.getKeyAsString();
//cjdid桶
for (Terms.Bucket cjdidBucket : groupColor2.getBuckets()) {
Terms groupTime2 = cjdidBucket.getAggregations().get("groupTime");
color2 = cjdidBucket.getKeyAsString();
outKey = cjdId2 + "-" + color2;
valueTree = new TreeMap<>();
//时间桶
for (Terms.Bucket timeBucket : groupTime2.getBuckets()) {
Terms groupCode2 = timeBucket.getAggregations().get("groupCode");
pTime2 = (Long) timeBucket.getKey();
//车牌桶
for (Terms.Bucket codeBucket : groupCode2.getBuckets()) {
code2 = codeBucket.getKeyAsString();
valueTree.put(pTime2, code2);
}
}
snapsotMap.put(outKey, valueTree);
}
}
System.out.println(snapsotMap.size());
/*for (Map.Entry<Tuple<String, String>, List<Long>> entry:snapsotMap.entrySet()){
System.out.println(entry.getKey() + ":" + entry.getValue());
}
*/
//输出类型,key为rfid检测到的车牌号,value为可能的套牌车号,可能性由高到低
Map<String, TreeMap<Integer, String>> output = new HashMap<>();
//中间变量,key:RFID车牌号,value:通过点的抓拍数据车牌号
Map<String, Map<String, Integer>> midleMap = new HashMap<>();
Map<String, Integer> midleValueMap;
Integer mideleInt;
//数据验证
//时间集合 TreeMap<Long, Tuple<String, String>> snapsotMap
List<Long> timeList = new ArrayList<>();
Long rfidTime;
Long lastDefTime;
//RFID数据,key为车牌ID+车牌颜色,value:(时间+地点ID)集合
for (Map.Entry<String, TreeMap<Long, String>> entry : finallyRfidMap.entrySet()) {
//连续位置
for (Map.Entry<Long, String> entry0 : entry.getValue().entrySet()) {
//抓拍数据输出格式,key:地点+车牌颜色,value:Map(时间:车牌号)
for (Map.Entry<String, TreeMap<Long, String>> entry1 : snapsotMap.entrySet()) {
//相同点与相同车牌颜色
if (entry1.getKey().equals(entry0.getValue() + "-" + entry.getKey().substring(entry.getKey().indexOf("-") + 1))) {
//时间最接近
rfidTime = entry0.getKey();
lastDefTime = Long.valueOf(Integer.MAX_VALUE);
//
for (Map.Entry<Long, String> entry2 : entry1.getValue().entrySet()) {
if (Math.abs(entry2.getKey() - rfidTime) < lastDefTime) {
lastDefTime = Math.abs(entry2.getKey() - rfidTime);
} else {
//时间最近点
//时间范围条件要满足
if(lastDefTime<defTime){
if (midleMap.containsKey(entry.getKey())) {
midleValueMap = midleMap.get(entry.getKey());
} else {
midleValueMap = new HashMap<>();
}
if (midleValueMap.containsKey(entry2.getValue())) {
mideleInt=midleValueMap.get(entry2.getValue());
mideleInt+=1;
}else {
mideleInt=1;
}
midleValueMap.put(entry2.getValue(),mideleInt);
midleMap.put(entry.getKey(), midleValueMap);
/* System.out.println(entry.getKey() + "==============================" );
//打印map
Iterator itor = midleValueMap.keySet().iterator();
while(itor.hasNext())
{
String key = (String)itor.next();
String value = String.valueOf(midleValueMap.get(key));
if(Integer.parseInt(value)>5){
System.out.println(key+"=============="+value);
}
}
System.out.println("======================================");
*/
break;
}
}
}
}
}
}
}
//过滤其中大于5条的
//RFID车牌,车牌颜色,抓拍车牌,抓拍车牌颜色,次数
Map<Tuple<String,String>,Tuple<Tuple<String,String>,Integer>> outPutMap=new HashMap<>();
// List<String> outCodeList=new ArrayList<>();
for(Map.Entry<String, Map<String, Integer>> entry:midleMap.entrySet()){
if( (entry.getValue().get(getMapMax(entry.getValue()))>5 || entry.getValue().get(getMapMax(entry.getValue()))==5)) {
outPutMap.put(new Tuple<>(entry.getKey().substring(0,entry.getKey().indexOf("-")),entry.getKey().substring(entry.getKey().indexOf("-")+1)),
new Tuple<>(new Tuple<>(getMapMax(entry.getValue()),entry.getKey().substring(entry.getKey().indexOf("-")+1)),
entry.getValue().get(getMapMax(entry.getValue()))));
// outCodeList.add(entry.getKey().substring(0,entry.getKey().indexOf("-")));
}
}
// System.out.println(CJDID_List.size()+"-------------"+outCodeList.size());//421
/*
//数据清洗
//次数相同的太多一般是某一辆车停在某个采集点附近不动造成的,RFID数据CJD很多相同,得把这种数据过滤掉
BoolQueryBuilder filterRoot = QueryBuilders.boolQuery();
//时间点
//双模
// TermsQueryBuilder termsQuery3 = QueryBuilders.termsQuery("cjdid", CJDID_List);
//车牌
TermsQueryBuilder termsQueryCode = QueryBuilders.termsQuery("plateCode", outCodeList);
//分组查询
AggregationBuilder plateTerms3 =
AggregationBuilders.terms("groupCode").field("plateCode").size(Integer.MAX_VALUE)
.subAggregation(AggregationBuilders.terms("groupCJDID").field("cjdid").size(Integer.MAX_VALUE));
filterRoot.must(startQuery);
filterRoot.must(endQuery);
// filterRoot.must(termsQuery3);
filterRoot.must(termsQueryCode);
SearchResponse filterResponse = client.prepareSearch(index)
.setTypes(type)
.setQuery(filterRoot)
.addAggregation(plateTerms3)
.setExplain(true).execute().actionGet();
String code3="";
String cjdid3="";
//用于过滤的数据,key:RFID的车牌号,value:cjdid与出现次数
Map<String,Map<String,Integer>> filterMap=new HashMap<>();
Map<String,Integer> mildleFilterMap=new HashMap<>();
Integer mildleFilteLong;
Terms groupCode3 = filterResponse.getAggregations().get("groupCode");
for (Terms.Bucket codeBucket : groupCode3.getBuckets()) {
Terms groupCjdid3 = codeBucket.getAggregations().get("groupCJDID");
code3 = codeBucket.getKeyAsString();
System.out.println("--------------"+code3);
if(filterMap.containsKey(code3)){
mildleFilterMap=filterMap.get(code3);
}else {
mildleFilterMap=new HashMap<>();
}
for (Terms.Bucket cjdidBucket : groupCjdid3.getBuckets()) {
cjdid3 = cjdidBucket.getKeyAsString();
if (mildleFilterMap.containsKey(cjdid3)){
mildleFilteLong=mildleFilterMap.get(cjdid3);
}else {
mildleFilteLong=1;
}
mildleFilterMap.put(cjdid3,mildleFilteLong);
}
filterMap.put(code3,mildleFilterMap);
}
System.out.println(filterMap.size());//421
//过滤掉前二重复cjdid大于2,或前1cjd大于3
List<String> codeRFidList=new ArrayList<>();
for (Map.Entry<String,Map<String,Integer>> entry:filterMap.entrySet()){
//降序MAp
TreeMap<Integer, String> orderMap = new TreeMap<Integer, String>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2 - o1;
}
});
for (Map.Entry<String,Integer> entry1:entry.getValue().entrySet()){
orderMap.put(entry1.getValue(),entry1.getKey());
}
if(orderMap.size()>2){
orderMap.remove(orderMap.lastKey());
}
*//* codeRFidList.add(entry.getKey());
System.out.println(entry.getKey());*//*
//过滤
if (*//*orderMap.lastKey()<2 && orderMap.firstKey()<3 && *//*orderMap.lastKey()!=orderMap.firstKey()){
//这种车牌(RFID)是满足的
codeRFidList.add(entry.getKey());
System.out.println(entry.getKey());
}
}
//过滤数据啦
Map<String,String> finallyMap=new HashMap<>();
for(Map.Entry<String, String> entry:outPutMap.entrySet()){
if(codeRFidList.contains(entry.getKey().substring(0,entry.getKey().indexOf("-")))){
finallyMap.put(entry.getKey(),entry.getValue());
}
}
System.out.println(finallyMap.size());*/
//写文档
//RFID车牌,车牌颜色,抓拍车牌,抓拍车牌颜色,次数
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("套牌车");
HSSFRow row = sheet.createRow(0);
HSSFCell cell = row.createCell(0);
cell.setCellValue("RFID车牌");
cell = row.createCell(1);
cell.setCellValue("车牌颜色编号");
cell = row.createCell(2);
cell.setCellValue("抓拍车牌");
cell = row.createCell(3);
cell.setCellValue("抓拍车牌颜色");
cell = row.createCell(4);
cell.setCellValue("次数");
int count = 0;
for (Map.Entry<Tuple<String,String>,Tuple<Tuple<String,String>,Integer>> entry : outPutMap.entrySet()) {
HSSFRow row1 = sheet.createRow(count + 1);
row1.createCell(0).setCellValue(entry.getKey().v1());
row1.createCell(1).setCellValue(entry.getKey().v2());
row1.createCell(2).setCellValue(entry.getValue().v1().v1());
row1.createCell(3).setCellValue(entry.getValue().v1().v2());
row1.createCell(4).setCellValue(entry.getValue().v2());
count++;
}
try {
FileOutputStream fos = new FileOutputStream("C:\\Users\\Administrator\\Desktop\\out.xls");
workbook.write(fos);
System.out.println("写入成功");
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//求一个map最大值
private String getMapMax( Map<String, Integer> map){
int value=0;
String maxKey = null;
List list=new ArrayList();
Iterator ite=map.entrySet().iterator();
while(ite.hasNext()){
Map.Entry entry =(Map.Entry)ite.next();
value = Integer.parseInt(entry.getValue().toString());
list.add(entry.getValue());
Collections.sort(list);
if(value == Integer.parseInt(list.get(list.size()-1).toString())){
maxKey = entry.getKey().toString();
}
}
return maxKey;
}
//取出一个集合中重复次数最多的字符串
private String getMaxString(List<String> list) {
Map<String, Long> top1 = new HashMap<>();
Long aLong;
for (String str : list) {
if (top1.containsValue(str)) {
aLong = top1.get(str);
aLong += 1;
} else {
aLong = 1L;
}
top1.put(str, aLong);
}
SortedMap<Long, String> top = new TreeMap<Long, String>();
for (Map.Entry<String, Long> entry : top1.entrySet()) {
top.put(entry.getValue(), entry.getKey());
}
return top.get(top.lastKey());
}
//查找list中的数字与目标数最接近的数
private Long getTime(List<Long> list, Long nearNum) {
Long diffNum = Math.abs(list.get(0) - nearNum);
// 最终结果
Long result = list.get(0);
for (Long integer : list) {
Long diffNumTemp = Math.abs(integer - nearNum);
if (diffNumTemp < diffNum) {
diffNum = diffNumTemp;
result = integer;
}
}
return result;
}
}
|
package br.com.poli.PuzzleN;
public class PuzzleInsano extends Puzzle {
private int tamanho;
public PuzzleInsano(Tabuleiro t, int k) {
super(t);
this.tamanho = (k*k)-1 ;
Dificuldade d = Dificuldade.NSANE;
d.setValor(tamanho);
setDificuldade(Dificuldade.NSANE);
}
public int getTamanho() {
return tamanho;
}
public void setTamanho(int tamanho) {
this.tamanho = tamanho;
}
public void resolveTabuleiro() throws TempoExcedido {
throw new TempoExcedido("N alto demais! Muito processamento necessário para estas interações");
//TODO ultima parte
}
public void geraTabuleiro(){
getGridPuzzle().geraTabuleiro(getDificuldade());
}
}
|
package com.web.common;
/**
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class ComCodeDTO {
String code="";
String name="";
/**
*
*/
public ComCodeDTO() {
super();
// TODO Auto-generated constructor stub
}
/**
* @return Returns the code.
*/
public String getCode() {
return code;
}
/**
* @param code The code to set.
*/
public void setCode(String code) {
this.code = code;
}
/**
* @return Returns the codeName.
*/
public String getName() {
return name;
}
/**
* @param codeName The codeName to set.
*/
public void setName(String codeName) {
this.name = codeName;
}
}
|
/**
* LoginService.java 25-feb-2014
*
* Copyright 2014 EVERIS S.L.U.
*/
package com.proyecto.server.service.impl;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.proyecto.dom.User;
import com.proyecto.dto.DetalleUsuarioDTO;
import com.proyecto.dto.enums.Rol;
import com.proyecto.server.mapper.MapperToDTO;
import com.proyecto.server.service.ILoginService;
import com.proyecto.server.service.base.IUsuarioAplicacionServiceBase;
@Service
public class LoginService implements ILoginService {
@Autowired
IUsuarioAplicacionServiceBase iUsuarioAplicacionServiceBase;
/**
* {@inheritDoc}
*/
@Override
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public DetalleUsuarioDTO check(final String login, final String password) {
final DetalleUsuarioDTO detalleUsuarioAplicacion = new DetalleUsuarioDTO();
final User usuarioAplicacion = iUsuarioAplicacionServiceBase.findByCredenciales(login, password);
if (usuarioAplicacion == null) {
detalleUsuarioAplicacion.setAccesoPermitido(false);
} else {
final List<Long> idsUsuarioAplicacion = new ArrayList<Long>();
idsUsuarioAplicacion.add(usuarioAplicacion.getUserId().longValue());
// if (usuarioAplicacion.getTipoUsuarioAplicacion().equals(IdsMaestros.TIPO_USUARIO.USER.getId())) {
detalleUsuarioAplicacion.setAccesoPermitido(true);
detalleUsuarioAplicacion.setUsuarioAplicacion(MapperToDTO.adapt(usuarioAplicacion));
detalleUsuarioAplicacion.setRol(Rol.USER);
detalleUsuarioAplicacion.setMenus(usuarioAplicacion.getPerfil().getMenus());
// }
}
return detalleUsuarioAplicacion;
}
}
|
// Copyright (c) 2012 P. Taylor Goetz (ptgoetz@gmail.com)
package com.instanceone.hdfs.shell.command;
import com.instanceone.stemshell.Environment;
import com.instanceone.stemshell.command.AbstractCommand;
import jline.console.ConsoleReader;
import jline.console.completer.Completer;
import jline.console.completer.StringsCompleter;
import org.apache.commons.cli.CommandLine;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.security.UserGroupInformation;
import java.io.IOException;
import java.net.URI;
public class HdfsUGI extends HdfsCommand {
public HdfsUGI(String name) {
super(name);
// Completer completer = new StringsCompleter("hdfs://localhost:8020/", "hdfs://hdfshost:8020/");
// this.completer = completer;
}
public void execute(Environment env, CommandLine cmd, ConsoleReader reader) {
try {
UserGroupInformation.main(cmd.getArgs());
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public Completer getCompleter() {
return this.completer;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.