text stringlengths 10 2.72M |
|---|
package com.atguigu.java4;
import org.junit.Test;
/*
finally :
1.finally中的代码一定会执行。
2.就算在try和catch中有return,那么finally中的代码也一定会执行。
*/
public class FinallyTest {
@Test
public void test2(){
System.out.println(getNumber());//20
System.out.println("----------------------------------");
System.out.println(getNumber2());
}
public int getNumber2(){
try{
return 10;
}catch(Exception e){
System.out.println("发生异常了");
}finally{
System.out.println("我是finally");
}
return 20;
}
/*
* 就算在try中catch中有return,那么finally中的代码也一定会执行。
*/
public int getNumber(){
try{
return 10;
}catch(Exception e){
System.out.println("发生异常了");
}finally{
return 20;
}
}
/*
* 1.就算catch中再次发生异常finally还是会执行。
*/
@Test
public void test(){
try{
System.out.println("aaaa");
System.out.println(1 / 0);
}catch(ArithmeticException e){
System.out.println("发生了异常");
System.out.println(1 / 0);
}finally{
System.out.println("我一定要执行");
}
System.out.println("程序结束");
}
}
|
package com.equipo12.retobc.model.balance;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder(toBuilder = true)
@AllArgsConstructor
@NoArgsConstructor
public class BalancesRS {
private float available;
private float availableOverdraftBalance;
private float overdraftValue;
private float availableOverdraftQuota;
private float cash;
private float unavailable_clearing;
private float receivable;
private float blocked;
private float unavailableStartDay_clearingStartDay;
private float cashStartDay;
private float pockets;
private float remittanceQuota;
private float agreedRemittanceQuota;
private float remittanceQuotaUsage;
private float normalInterest;
private float suspensionInterest;
}
|
package nl.esciencecenter.newsreader.hbase;
import com.google.common.collect.Iterators;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.joda.time.DateTime;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.*;
public class DirectoryDumperTest {
private DirectoryDumper dumper;
private HTable table;
private ResultScanner rs;
@Before
public void setUp() {
dumper = new DirectoryDumper();
table = mock(HTable.class);
dumper.setTable(table);
}
public void setUpScan() throws IOException {
rs = mock(ResultScanner.class);
List<Cell> cells = new ArrayList<>();
byte[] row = "5b1t-br51-jd3n-54fk.naf".getBytes();
byte[] family = "naf".getBytes();
byte[] column = "annotated".getBytes();
byte type = KeyValue.Type.Maximum.getCode();
long ts = new DateTime("2015-04-22T14:53:45.000Z").getMillis();
byte[] value = "<some xml>".getBytes();
Cell cell = CellUtil.createCell(row, family, column, ts, type, value);
cells.add(cell);
Result result = Result.create(cells);
Result[] results = {result};
Iterator<Result> iterator = Iterators.forArray(results);
when(rs.iterator()).thenReturn(iterator);
when(table.getScanner(any(Scan.class))).thenReturn(rs);
}
@After
public void tearDown() throws Exception {
}
@Test
public void testDefaultTableName() {
assertThat(dumper.getTableName(), is("documents"));
}
@Test
public void testDefaulFamilyName() {
assertThat(dumper.getFamilyName(), is("naf"));
}
@Test
public void testDefaultColumnName() {
assertThat(dumper.getColumnName(), is("annotated"));
}
@Test
public void testRun() throws Exception {
// redirect stdout to variable
ByteArrayOutputStream outContent = new ByteArrayOutputStream();
System.setOut(new PrintStream(outContent));
setUpScan();
dumper.run();
String expected = "5b1t-br51-jd3n-54fk.naf : 10\n";
assertThat(outContent.toString(), is(expected));
verify(rs).close();
verify(table).close();
// undo stdout redirect
System.setOut(new PrintStream(new FileOutputStream(FileDescriptor.out)));
}
} |
/*
* 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 hotels;
import javax.swing.table.DefaultTableModel;
/**
*
* @author Nyagritin
*/
public class VilaRosaStock extends javax.swing.JFrame {
/**
* Creates new form VilaRosaStock
*/
public VilaRosaStock() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jScrollPane2 = new javax.swing.JScrollPane();
jTable2 = new javax.swing.JTable();
jScrollPane3 = new javax.swing.JScrollPane();
jTable3 = new javax.swing.JTable();
jScrollPane4 = new javax.swing.JScrollPane();
jTable4 = new javax.swing.JTable();
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jTextField1 = new javax.swing.JTextField();
jTextField4 = new javax.swing.JTextField();
jTextField6 = new javax.swing.JTextField();
jScrollPane5 = new javax.swing.JScrollPane();
jProducts = new javax.swing.JTable();
IMessage = new javax.swing.JLabel();
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jScrollPane1.setViewportView(jTable1);
jTable2.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jScrollPane2.setViewportView(jTable2);
jTable3.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jScrollPane3.setViewportView(jTable3);
jTable4.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jScrollPane4.setViewportView(jTable4);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setFont(new java.awt.Font("Algerian", 1, 18)); // NOI18N
jLabel1.setText("VilaRosa Stock");
jLabel2.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
jLabel2.setText("InventoryID");
jLabel5.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
jLabel5.setText("Inventory Type");
jLabel7.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
jLabel7.setText("Inventory Status");
jButton1.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
jButton1.setText("Add");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
jButton2.setText("Update");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jButton3.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
jButton3.setText("Clear");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
jTextField1.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
jTextField1.setText("jTextField1");
jTextField4.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
jTextField4.setText("jTextField4");
jTextField4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField4ActionPerformed(evt);
}
});
jTextField6.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
jTextField6.setText("jTextField6");
jTextField6.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField6ActionPerformed(evt);
}
});
jProducts.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null}
},
new String [] {
"InventoryID", "Inventory Status", "InventoryType"
}
) {
Class[] types = new Class [] {
java.lang.Integer.class, java.lang.Integer.class, java.lang.String.class
};
boolean[] canEdit = new boolean [] {
false, false, false
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jScrollPane5.setViewportView(jProducts);
if (jProducts.getColumnModel().getColumnCount() > 0) {
jProducts.getColumnModel().getColumn(0).setResizable(false);
jProducts.getColumnModel().getColumn(1).setResizable(false);
jProducts.getColumnModel().getColumn(2).setResizable(false);
}
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(IMessage, javax.swing.GroupLayout.PREFERRED_SIZE, 452, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(291, 291, 291)
.addComponent(jLabel1))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(106, 106, 106)
.addComponent(jScrollPane5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(64, 64, 64)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(15, 15, 15)
.addComponent(jButton1)
.addGap(92, 92, 92)
.addComponent(jButton2)
.addGap(88, 88, 88)
.addComponent(jButton3))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2)
.addComponent(jLabel7))
.addGap(48, 48, 48)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jTextField6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(127, 127, 127)
.addComponent(jLabel5)
.addGap(86, 86, 86)
.addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))))))
.addContainerGap(245, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(38, 38, 38)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(jLabel5)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(34, 34, 34)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel7)
.addComponent(jTextField6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(90, 90, 90)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1)
.addComponent(jButton2)
.addComponent(jButton3))
.addGap(26, 26, 26)
.addComponent(IMessage)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane5, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(320, 320, 320))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(65, 65, 65)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 485, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(316, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jTextField4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField4ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jTextField4ActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
IMessage.setText("");
DefaultTableModel model = (DefaultTableModel) jProducts.getModel();
if(!jTextField1.getText().trim().equals("")){
model.addRow(new Object[]{jTextField1.getText(),jTextField4.getText(),jTextField6.getText()});
}else{
IMessage.setText("Product ID cannot be empty");
}
}//GEN-LAST:event_jButton1ActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
// TODO add your handling code here:
IMessage.setText("");
DefaultTableModel model = (DefaultTableModel) jProducts.getModel();
if(jProducts.getSelectedRow()==-1){
if(jProducts.getRowCount()==0){
IMessage.setText("The table is empty");
}else{
IMessage.setText("Please select product to update");
}
}else{
model.setValueAt(jTextField1.getText(),jProducts.getSelectedRow(),0);
model.setValueAt(jTextField4.getText(),jProducts.getSelectedRow(),3);
model.setValueAt(jTextField6.getText(),jProducts.getSelectedRow(),5);
}
}//GEN-LAST:event_jButton2ActionPerformed
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
// TODO add your handling code here:
IMessage.setText("");
DefaultTableModel model = (DefaultTableModel) jProducts.getModel();
if(jProducts.getSelectedRow()==-1){
if(jProducts.getRowCount()==0){
IMessage.setText("The table is empty");
}else{
IMessage.setText("Please select a product");
}
}else{
model.removeRow(jProducts.getSelectedRow());
}
}//GEN-LAST:event_jButton3ActionPerformed
private void jTextField6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField6ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jTextField6ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(VilaRosaStock.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(VilaRosaStock.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(VilaRosaStock.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(VilaRosaStock.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new VilaRosaStock().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel IMessage;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel7;
private javax.swing.JPanel jPanel1;
private javax.swing.JTable jProducts;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JScrollPane jScrollPane4;
private javax.swing.JScrollPane jScrollPane5;
private javax.swing.JTable jTable1;
private javax.swing.JTable jTable2;
private javax.swing.JTable jTable3;
private javax.swing.JTable jTable4;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField4;
private javax.swing.JTextField jTextField6;
// End of variables declaration//GEN-END:variables
}
|
package sign.com.biz.base.service;
import tk.mybatis.mapper.entity.Example;
import java.util.List;
/**
* create by luolong on 2018/5/12
*/
public interface BaseService<T> {
//通过id查询对象
T selectById(Object id);
//增加
int save(T t);
//删除
int delete(T t);
//根据主键修改对象的值
int update(T t);
//根据条件查对象
List<T> selectByExample(Example example);
}
|
import java.util.ArrayList;
import java.util.List;
public class BubbleSort<T extends Comparable> implements Sort<T> {
private List<T> list;
public BubbleSort(List<T> list) {
this.list = new ArrayList<>(list);
}
@Override
public List<T> getList() {
return list;
}
@Override
public void apply() {
for (int j = 0; j < list.size() ; j++)
for (int i = 0; i < list.size()-1 ; i++)
if (list.get(i+1).compareTo(list.get(i)) < 0) Utils.permute(list, i, i+1);
}
} |
package com.example.htw.currencyconverter;
import android.app.Application;
import com.example.htw.currencyconverter.scopes.modules.PlatformModule;
import com.example.htw.currencyconverter.scopes.components.AppComponent;
import com.example.htw.currencyconverter.scopes.components.DaggerAppComponent;
public class CurrencyApp extends Application {
public static AppComponent appComponent;
@Override
public void onCreate() {
super.onCreate();
appComponent = DaggerAppComponent.builder()
.platformModule(new PlatformModule(this))
.build();
}
}
|
/* Author: Arkadiusz Galas
Date: 1 JUN 2016
ID: 26777
Name: Mr. Ant & His Problem */
/** MrAnt class is a solution of Mr. Ant & His Problem problem on
* http://www.spoj.com/problems/ANTP/
*/
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.StringTokenizer;
public class MrAnt {
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer token = new StringTokenizer(br.readLine());
int n = Integer.parseInt(token.nextToken());
int [] xvalues = new int [n];
int [] yvalues = new int [n];
long [] res = new long [n];
for (int i=0; i<n; i++) {
StringTokenizer token2 = new StringTokenizer(br.readLine());
xvalues[i] = Integer.parseInt(token2.nextToken());
yvalues[i] = Integer.parseInt(token2.nextToken());
res[i] = (((long)yvalues[i]*((long)yvalues[i]-1)*((long)yvalues[i]-2)
-((long)xvalues[i]-1)*((long)xvalues[i]-2)*((long)xvalues[i]-3))/6) % 1000000007;
}
for (int j=0; j<n; j++) {
System.out.println(res[j]);
}
}
} |
package ChatClient;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;
public class ChatClient implements Runnable {
private Socket socket;
private boolean isAlive = true;
private OutputStream outputStream = null;
private InputStream inputStream = null;
public ChatClient(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
inputStream = socket.getInputStream();
while (true) {
byte[] recv = new byte[1024];
int len = inputStream.read(recv);
if (len != -1) {
String recvMsg = new String(recv, 0, len);
ProcessRecvMsg(recvMsg);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(inputStream != null) {
inputStream.close();
}
if(socket != null) {
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static void ProcessRecvMsg(String recvMsg) {
String[] args = recvMsg.split("&");
if (args.length == 1) {
System.out.println(recvMsg);
} else if (args.length == 4) {
System.out.println("you receive message from " + args[3] + ", content:" + args[2]);
} else {
System.out.printf("unexpected recvMsg, msg:%s\n", recvMsg);
}
}
}
|
package com.example.service;
import java.util.List;
import com.example.dao.ImageDao;
import com.example.dao.ImageDaoImpl;
import com.example.model.image;
public class ImageServiceImpl implements ImageService {
private ImageDao img;
{
img=new ImageDaoImpl();
}
public void createRecord(String imageId, String imageUrl, boolean isAvailable)
{
// TODO Auto-generated method stub
img.createRecord(imageId, imageUrl, isAvailable);
}
public List<image> DisplayAll() {
// TODO Auto-generated method stub
return img.DisplayAll();
}
public image getImageByImageId(String imageId) {
// TODO Auto-generated method stub
return null;
}
public void update(String imageId, String imageUr, boolean isAvailable) {
// TODO Auto-generated method stub
}
public void delete(String imageId) {
// TODO Auto-generated method stub
}
}
|
/*
* 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.exerciseSpringBoot.crudBootstrap.entities;
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.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* @author ASUS
*/
@Entity
@Table(name = "employees")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Employee.findAll", query = "SELECT e FROM Employee e")
, @NamedQuery(name = "Employee.findById", query = "SELECT e.id, e.idjob, e.name, e.group FROM Employee e WHERE e.id = :id")
, @NamedQuery(name = "Employee.findByName", query = "SELECT e FROM Employee e WHERE e.name = :name")
, @NamedQuery(name = "Employee.findByGroup", query = "SELECT e FROM Employee e WHERE e.group = :group")})
public class Employee implements Serializable {
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 45)
@Column(name = "name")
private String name;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 2)
@Column(name = "group")
private String group;
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 11)
@Column(name = "id")
private String id;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "idemployee", fetch = FetchType.LAZY)
private List<EmpCondition> empConditionList;
@OneToOne(cascade = CascadeType.ALL, mappedBy = "employee", fetch = FetchType.LAZY)
private Account account;
@JoinColumn(name = "idjob", referencedColumnName = "id")
@ManyToOne(optional = false, fetch = FetchType.LAZY)
private Job idjob;
public Employee() {
}
public Employee(String id) {
this.id = id;
}
public Employee(String id, String name, String group) {
this.id = id;
this.name = name;
this.group = group;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@XmlTransient
public List<EmpCondition> getEmpConditionList() {
return empConditionList;
}
public void setEmpConditionList(List<EmpCondition> empConditionList) {
this.empConditionList = empConditionList;
}
public Account getAccount() {
return account;
}
public void setAccount(Account account) {
this.account = account;
}
public Job getIdjob() {
return idjob;
}
public void setIdjob(Job idjob) {
this.idjob = idjob;
}
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.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 Employee)) {
return false;
}
Employee other = (Employee) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
@Override
public String toString() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
}
|
package com.designurway.idlidosa.ui.home_page.fragments;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.navigation.NavDirections;
import com.designurway.idlidosa.HomeNavGraphDirections;
import com.designurway.idlidosa.R;
import java.lang.IllegalArgumentException;
import java.lang.Object;
import java.lang.Override;
import java.lang.String;
import java.lang.SuppressWarnings;
import java.util.HashMap;
public class DisplayProductFragmentDirections {
private DisplayProductFragmentDirections() {
}
@NonNull
public static ActionDisplayProductFragmentToProductDetailfragment actionDisplayProductFragmentToProductDetailfragment(
@NonNull String productId, @NonNull String present) {
return new ActionDisplayProductFragmentToProductDetailfragment(productId, present);
}
@NonNull
public static NavDirections actionGlobalNotificationListFragment() {
return HomeNavGraphDirections.actionGlobalNotificationListFragment();
}
public static class ActionDisplayProductFragmentToProductDetailfragment implements NavDirections {
private final HashMap arguments = new HashMap();
private ActionDisplayProductFragmentToProductDetailfragment(@NonNull String productId,
@NonNull String present) {
if (productId == null) {
throw new IllegalArgumentException("Argument \"productId\" is marked as non-null but was passed a null value.");
}
this.arguments.put("productId", productId);
if (present == null) {
throw new IllegalArgumentException("Argument \"present\" is marked as non-null but was passed a null value.");
}
this.arguments.put("present", present);
}
@NonNull
public ActionDisplayProductFragmentToProductDetailfragment setProductId(
@NonNull String productId) {
if (productId == null) {
throw new IllegalArgumentException("Argument \"productId\" is marked as non-null but was passed a null value.");
}
this.arguments.put("productId", productId);
return this;
}
@NonNull
public ActionDisplayProductFragmentToProductDetailfragment setPresent(@NonNull String present) {
if (present == null) {
throw new IllegalArgumentException("Argument \"present\" is marked as non-null but was passed a null value.");
}
this.arguments.put("present", present);
return this;
}
@Override
@SuppressWarnings("unchecked")
@NonNull
public Bundle getArguments() {
Bundle __result = new Bundle();
if (arguments.containsKey("productId")) {
String productId = (String) arguments.get("productId");
__result.putString("productId", productId);
}
if (arguments.containsKey("present")) {
String present = (String) arguments.get("present");
__result.putString("present", present);
}
return __result;
}
@Override
public int getActionId() {
return R.id.action_displayProductFragment_to_productDetailfragment;
}
@SuppressWarnings("unchecked")
@NonNull
public String getProductId() {
return (String) arguments.get("productId");
}
@SuppressWarnings("unchecked")
@NonNull
public String getPresent() {
return (String) arguments.get("present");
}
@Override
public boolean equals(Object object) {
if (this == object) {
return true;
}
if (object == null || getClass() != object.getClass()) {
return false;
}
ActionDisplayProductFragmentToProductDetailfragment that = (ActionDisplayProductFragmentToProductDetailfragment) object;
if (arguments.containsKey("productId") != that.arguments.containsKey("productId")) {
return false;
}
if (getProductId() != null ? !getProductId().equals(that.getProductId()) : that.getProductId() != null) {
return false;
}
if (arguments.containsKey("present") != that.arguments.containsKey("present")) {
return false;
}
if (getPresent() != null ? !getPresent().equals(that.getPresent()) : that.getPresent() != null) {
return false;
}
if (getActionId() != that.getActionId()) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = 1;
result = 31 * result + (getProductId() != null ? getProductId().hashCode() : 0);
result = 31 * result + (getPresent() != null ? getPresent().hashCode() : 0);
result = 31 * result + getActionId();
return result;
}
@Override
public String toString() {
return "ActionDisplayProductFragmentToProductDetailfragment(actionId=" + getActionId() + "){"
+ "productId=" + getProductId()
+ ", present=" + getPresent()
+ "}";
}
}
}
|
package com.human.ex;
public class quiz0228_03 {
public static void main(String[] args) {
java.util.Scanner sc = new java.util.Scanner(System.in);
System.out.print("정수 입력 : ");
int n = Integer.parseInt(sc.nextLine());
switch (n % 3) {
case 0:
System.out.println("거짓");
break;
default:
System.out.println("참");
break;
}
sc.close();
}
}
// 빈칸에는 default: |
package com.bloodl1nez.analytics.vk.api.likes;
import com.bloodl1nez.analytics.vk.api.RequestParameters;
import com.bloodl1nez.analytics.vk.api.VkAPIConfig;
import com.bloodl1nez.analytics.vk.api.VkRequestManager;
import org.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
@Component
public class LikesFetcherImpl implements LikesFetcher {
private static final String LIST_LIKES_URL = "https://api.vk.com/method/likes.getList";
private static final String IS_LIKED_URL = "https://api.vk.com/method/likes.isLiked";
private final VkRequestManager requestManager;
private final VkAPIConfig apiConfig;
@Autowired
public LikesFetcherImpl(VkRequestManager requestManager, VkAPIConfig apiConfig) {
this.requestManager = requestManager;
this.apiConfig = apiConfig;
}
@Override
public List<Long> getUserIds(long postId, long ownerId, LikeType type, String token) {
RequestParameters parameters =
RequestParameters.createBuilder()
.addParam("access_token", token)
.addParam("v", apiConfig.getAPIVersion())
.addParam("type", type.getValue())
.addParam("owner_id", ownerId)
.addParam("item_id", postId)
.build();
return requestManager
.get(IS_LIKED_URL, parameters)
.map(response -> response.getJSONObject("response"))
.map(response -> response.getJSONArray("items"))
.map(this::getIdsFromItems)
.orElse(Collections.emptyList());
}
@Override
public boolean didUserLike(long userId, long postId, long ownerId, LikeType type, String token) {
RequestParameters parameters = RequestParameters.createBuilder()
.addParam("access_token", token)
.addParam("v", apiConfig.getAPIVersion())
.addParam("owner_id", ownerId)
.addParam("user_id", userId)
.addParam("item_id", postId)
.addParam("type", type.getValue())
.build();
return requestManager
.get(IS_LIKED_URL, parameters)
.map(response -> response.getJSONObject("response"))
.map(json -> json.getInt("liked"))
.map(liked -> liked > 0)
.orElse(false);
}
private List<Long> getIdsFromItems(JSONArray items) {
return IntStream.range(0, items.length())
.boxed()
.map(items::getLong)
.collect(Collectors.toList());
}
}
|
public class ConstructStringfromBinaryTree {
/**
* Input: Binary tree: [1,2,3,4]
1
/ \
2 3
/
4
Output: "1(2(4))(3)"
Explanation: Originallay it needs to be "1(2(4)())(3()())",
but you need to omit all the unnecessary empty parenthesis pairs.
And it will be "1(2(4))(3)".
*/
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
public String tree2str(TreeNode t) {
if (t == null)
return "";
if (t.left == null && t.right == null) {
return "" + t.val;
}
String left = tree2str(t.left);
if (t.right == null) {
return t.val + "(" + left + ")";
}
String right = tree2str(t.right);
String toreturn = t.val + "(" + left + ")" + "(" + right + ")";
return toreturn;
}
/**
* Find pattern and recursively return here, nothing serious.
* Notice to check if left or right is null, check the node directly rather than the result, will save runtime.
*/
}
|
package tests;
import java.io.*;
import java.util.*;
/**
* Created by Gauthier on 13/03/2017.
*/
public class EcrireData{
public static void main(String[] args) {
FileWriter flot;
PrintWriter flotFiltre;
File chemin;
String nomChemin = args[0];
Random r = new Random();
int nbLigneRandom = r.nextInt(50)+50;
boolean exist;
String finDeLigne = System.getProperty("line.separator");
try{
chemin=new File(nomChemin);
exist=chemin.exists();
if(exist){
throw new IOException("Le fichier exite déja");
}
if(!exist){
flot = new FileWriter(args[0]);
flotFiltre = new PrintWriter(new BufferedWriter(flot));
int val = 65 + r.nextInt(25);
for (int i = 0; i <= nbLigneRandom; i++) {
int val2=r.nextInt(200)-100;
flotFiltre.println((char)val+" "+ val2);
val ++;
if(val>'Z'){
val='A';
}
}
flotFiltre.close();}
}catch(IOException e){
e.printStackTrace();
}
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package projetobanco;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
/**
*
* @author Codification
*/
public class SGBDDAO implements IDAO{
private Connection con;
public SGBDDAO() {
this.con = new ConnectionFactory().getConnection();
}
//Apenas para testes
@Override
public ArrayList<Cliente> pesquisaCliente(String texto) throws Exception {
ArrayList<Cliente> c = new ArrayList<>();
if (texto == null || texto.equals("")) {
PreparedStatement stmt = con.prepareStatement("SELECT * FROM cliente");
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
Cliente cliente = new Cliente();
cliente.setCodigo(rs.getInt("codigo"));
cliente.setNome(rs.getString("nome"));
cliente.setSobrenome(rs.getString("sobreNome"));
cliente.setRG(rs.getString("rg"));
cliente.setCPF(rs.getString("cpf"));
cliente.setEndereco(rs.getString("endereco"));
cliente.setSalario(rs.getDouble("salario"));
c.add(cliente);
}
} else {
PreparedStatement stmt = con.prepareStatement("SELECT * FROM cliente WHERE nome LIKE ? OR sobreNome LIKE ? OR cpf LIKE ? OR rg LIKE ?");
texto = "%" + texto + "%";
stmt.setString(1, texto);
stmt.setString(2, texto);
stmt.setString(3, texto);
stmt.setString(4, texto);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
Cliente cliente = new Cliente();
cliente.setCodigo(rs.getInt("codigo"));
cliente.setNome(rs.getString("nome"));
cliente.setSobrenome(rs.getString("sobreNome"));
cliente.setRG(rs.getString("rg"));
cliente.setCPF(rs.getString("cpf"));
cliente.setEndereco(rs.getString("endereco"));
cliente.setSalario(rs.getDouble("salario"));
c.add(cliente);
}
}
return c;
}
@Override
public Conta carregaConta(int codigoCliente) throws Exception {
Conta conta = null;
PreparedStatement stmt = con.prepareStatement("SELECT * FROM contaCorrente WHERE cliente = ?");
stmt.setInt(1, codigoCliente);
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
conta = new ContaCorrente();
conta.setNumero(rs.getInt("numero"));
conta.setDono(rs.getInt("cliente"));
conta.setDepositoInicial(rs.getDouble("depositoInicial"));
conta.setSaldo(rs.getDouble("saldo"));
((ContaCorrente) conta).setLimite(rs.getDouble("limite"));
}
PreparedStatement stmt2 = con.prepareStatement("SELECT * FROM contaInvestimento WHERE cliente = ?");
stmt2.setInt(1, codigoCliente);
ResultSet rs2 = stmt2.executeQuery();
if (rs2.next()) {
conta = new ContaInvestimento();
conta.setNumero(rs2.getInt("numero"));
conta.setDono(rs2.getInt("cliente"));
conta.setDepositoInicial(rs2.getDouble("depositoInicial"));
conta.setSaldo(rs2.getDouble("saldo"));
((ContaInvestimento) conta).setMontanteMinimo(rs2.getDouble("montanteMinimo"));
((ContaInvestimento) conta).setDepositoMinimo(rs2.getDouble("depositoMinimo"));
}
return conta;
}
@Override
public void deletaContaCorrente(int codigoConta) throws Exception{
PreparedStatement stmt = con.prepareStatement("DELETE FROM contaCorrente WHERE numero = ?");
stmt.setInt(1, codigoConta);
stmt.executeUpdate();
}
@Override
public void deletaContaInvestimento(int codigoConta) throws Exception{
PreparedStatement stmt = con.prepareStatement("DELETE FROM contaInvestimento WHERE numero = ?");
stmt.setInt(1, codigoConta);
stmt.executeUpdate();
}
@Override
public void atualizaConta(Conta conta) throws Exception{
PreparedStatement stmt;
if(conta instanceof ContaInvestimento){
stmt = con.prepareStatement("UPDATE contaInvestimento SET saldo = ? WHERE cliente = ?");
}else{
stmt = con.prepareStatement("UPDATE contaCorrente SET saldo = ? WHERE cliente = ?");
}
stmt.setDouble(1, conta.getSaldo());
stmt.setInt(2, conta.getDono().getCodigo());
stmt.executeUpdate();
}
@Override
public void atualizaCliente(Cliente cliente) throws Exception{
PreparedStatement stmt = con.prepareStatement("UPDATE cliente SET nome = ?,sobreNome = ?,rg = ?,cpf = ?,endereco = ?,salario = ? WHERE codigo = ?");
stmt.setString(1, cliente.getNome());
stmt.setString(2, cliente.getSobrenome());
stmt.setString(3, cliente.getRG());
stmt.setString(4, cliente.getCPF());
stmt.setString(5, cliente.getEndereco());
stmt.setDouble(6, cliente.getSalario());
stmt.setDouble(7, cliente.getCodigo());
stmt.executeUpdate();
}
@Override
public void deletaCliente(Cliente cliente) throws Exception{
PreparedStatement stmt = con.prepareStatement("DELETE FROM contaCorrente WHERE cliente = ?");
stmt.setInt(1, cliente.getCodigo());
stmt.executeUpdate();
stmt = con.prepareStatement("DELETE FROM contaInvestimento WHERE cliente = ?");
stmt.setInt(1, cliente.getCodigo());
stmt.executeUpdate();
stmt = con.prepareStatement("DELETE FROM cliente WHERE codigo = ?");
stmt.setInt(1, cliente.getCodigo());
stmt.executeUpdate();
}
@Override
public void criaContaCorrente(Conta conta) throws Exception {
PreparedStatement stmt;
stmt = con.prepareStatement("INSERT INTO contaCorrente VALUES(0,?,?,?,?)");
stmt.setInt(1, conta.getDono().getCodigo());
stmt.setDouble(2, conta.getSaldo());
stmt.setDouble(3, conta.getDepositoInicial());
stmt.setDouble(4, ((ContaCorrente) conta).getLimite());
stmt.executeUpdate();
}
@Override
public void criaContaInvestimento(Conta conta) throws Exception {
PreparedStatement stmt;
stmt = con.prepareStatement("INSERT INTO contaInvestimento VALUES(0,?,?,?,?,?)");
stmt.setInt(1, conta.getDono().getCodigo());
stmt.setDouble(2, conta.getSaldo());
stmt.setDouble(3, conta.getDepositoInicial());
stmt.setDouble(4, ((ContaInvestimento) conta).getMontanteMinimo());
stmt.setDouble(5, ((ContaInvestimento) conta).getDepositoMinimo());
stmt.executeUpdate();
}
@Override
public void criaCliente(Cliente cliente) throws Exception {
PreparedStatement stmt = con.prepareStatement("INSERT INTO cliente VALUES(0,?,?,?,?,?,?)");
stmt.setString(1, cliente.getNome());
stmt.setString(2, cliente.getSobrenome());
stmt.setString(3, cliente.getRG());
stmt.setString(4, cliente.getCPF());
stmt.setString(5, cliente.getEndereco());
stmt.setDouble(6, cliente.getSalario());
stmt.executeUpdate();
}
@Override
public Cliente carregaCliente(int codigoCliente) throws SQLException {
PreparedStatement stmt = con.prepareStatement("SELECT * FROM cliente WHERE codigo = ?");
stmt.setInt(1, codigoCliente);
ResultSet rs = stmt.executeQuery();
Cliente cliente = new Cliente();
while (rs.next()) {
cliente.setCodigo(rs.getInt("codigo"));
cliente.setNome(rs.getString("nome"));
cliente.setSobrenome(rs.getString("sobreNome"));
cliente.setRG(rs.getString("rg"));
cliente.setCPF(rs.getString("cpf"));
cliente.setEndereco(rs.getString("endereco"));
cliente.setSalario(rs.getDouble("salario"));
return cliente;
}
return null;
}
}
|
package algorithms.sorting.compare;
import algorithms.sorting.SelectionSort;
import algorithms.sorting.ShellSort;
import algorithms.sorting.heap.HeapSortFactory;
import algorithms.sorting.insertion.InsertionSort;
import algorithms.sorting.merge.CopyOnceMergeSort;
import algorithms.sorting.merge.InsertionMergeSort;
import algorithms.sorting.merge.MergeSort;
import algorithms.sorting.quick.QuickSortFactory;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
/**
* Created by Chen Li on 2018/4/1.
*/
public class GeneralSortCompareTest extends AbstractSortCompareTest {
@Autowired
private SortCompareContext randomSortCompareContext;
@Test
public void insertionVsSelectionTest() {
SortCompareContext context = randomSortCompareContext.load(new InsertionSort(), new SelectionSort(),
SortSizeConfigs.slow2SizeAndTimesList
);
compareTest(context);
}
@Test
public void shellVsInsertionTest() {
SortCompareContext context = randomSortCompareContext.load(new ShellSort(), new InsertionSort(),
SortSizeConfigs.slow2SizeAndTimesList
);
compareTest(context);
}
@Test
public void shellVsMergeTest() throws Exception {
SortCompareContext context = randomSortCompareContext.load(new MergeSort(), new ShellSort(),
SortSizeConfigs.slow1SizeAndTimesList
);
compareTest(context);
}
@Test
public void mergeVsCopyOnceTest() throws Exception {
SortCompareContext context = randomSortCompareContext.load(new CopyOnceMergeSort(), new MergeSort(),
SortSizeConfigs.middleSizeAndTimesList
);
compareTest(context);
}
@Test
public void mergeVsInsertionMergeTest() throws Exception {
SortCompareContext context = randomSortCompareContext.load(new InsertionMergeSort(), new MergeSort(),
SortSizeConfigs.slow1SizeAndTimesList
);
compareTest(context);
}
@Test
public void mergeVsHeapSortTest() throws Exception {
HeapSortFactory factory = new HeapSortFactory();
SortCompareContext context = randomSortCompareContext.load(new CopyOnceMergeSort(), factory.bestHeapSort(),
SortSizeConfigs.slow1SizeAndTimesList
);
compareTest(context);
}
@Test
public void mergeVsQuickTest() throws Exception {
QuickSortFactory factory = new QuickSortFactory();
SortCompareContext context = randomSortCompareContext.load(new CopyOnceMergeSort(), factory.median3QuickSort(),
SortSizeConfigs.largeSizeConfig
);
compareTest(context);
}
@Test
public void fastTest() throws Exception {
QuickSortFactory factory = new QuickSortFactory();
SortCompareContext context = randomSortCompareContext.load(new CopyOnceMergeSort(), factory.bestQuickSort(),
SortSizeConfigs.middleSizeAndTimesList
);
compareTest(context);
}
}
|
/*
* Copyright 2002-2023 the original author or authors.
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jms.listener;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;
import jakarta.jms.Connection;
import jakarta.jms.ConnectionFactory;
import jakarta.jms.Destination;
import jakarta.jms.JMSException;
import org.junit.jupiter.api.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.backoff.BackOff;
import org.springframework.util.backoff.BackOffExecution;
import org.springframework.util.backoff.FixedBackOff;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
/**
* Tests for {@link DefaultMessageListenerContainer}.
*
* @author Stephane Nicoll
* @author Juergen Hoeller
* @author Sam Brannen
*/
class DefaultMessageListenerContainerTests {
@Test
void applyBackOff() {
BackOff backOff = mock();
BackOffExecution execution = mock();
given(execution.nextBackOff()).willReturn(BackOffExecution.STOP);
given(backOff.start()).willReturn(execution);
DefaultMessageListenerContainer container = createContainer(createFailingContainerFactory());
container.setBackOff(backOff);
container.start();
assertThat(container.isRunning()).isTrue();
container.refreshConnectionUntilSuccessful();
assertThat(container.isRunning()).isFalse();
verify(backOff).start();
verify(execution).nextBackOff();
container.destroy();
}
@Test
void applyBackOffRetry() {
BackOff backOff = mock();
BackOffExecution execution = mock();
given(execution.nextBackOff()).willReturn(50L, BackOffExecution.STOP);
given(backOff.start()).willReturn(execution);
DefaultMessageListenerContainer container = createContainer(createFailingContainerFactory());
container.setBackOff(backOff);
container.start();
container.refreshConnectionUntilSuccessful();
assertThat(container.isRunning()).isFalse();
verify(backOff).start();
verify(execution, times(2)).nextBackOff();
container.destroy();
}
@Test
void recoverResetBackOff() {
BackOff backOff = mock();
BackOffExecution execution = mock();
given(execution.nextBackOff()).willReturn(50L, 50L, 50L); // 3 attempts max
given(backOff.start()).willReturn(execution);
DefaultMessageListenerContainer container = createContainer(createRecoverableContainerFactory(1));
container.setBackOff(backOff);
container.start();
container.refreshConnectionUntilSuccessful();
assertThat(container.isRunning()).isTrue();
verify(backOff).start();
verify(execution, times(1)).nextBackOff(); // only on attempt as the second one lead to a recovery
container.destroy();
}
@Test
void stopAndRestart() {
DefaultMessageListenerContainer container = createRunningContainer();
container.stop();
container.start();
container.destroy();
}
@Test
void stopWithCallbackAndRestart() throws InterruptedException {
DefaultMessageListenerContainer container = createRunningContainer();
TestRunnable stopCallback = new TestRunnable();
container.stop(stopCallback);
stopCallback.waitForCompletion();
container.start();
container.destroy();
}
@Test
void stopCallbackIsInvokedEvenIfContainerIsNotRunning() throws InterruptedException {
DefaultMessageListenerContainer container = createRunningContainer();
container.stop();
// container is stopped but should nevertheless invoke the runnable argument
TestRunnable stopCallback = new TestRunnable();
container.stop(stopCallback);
stopCallback.waitForCompletion();
container.destroy();
}
@Test
void setCacheLevelNameToUnsupportedValues() {
DefaultMessageListenerContainer container = new DefaultMessageListenerContainer();
assertThatIllegalArgumentException().isThrownBy(() -> container.setCacheLevelName(null));
assertThatIllegalArgumentException().isThrownBy(() -> container.setCacheLevelName(" "));
assertThatIllegalArgumentException().isThrownBy(() -> container.setCacheLevelName("bogus"));
}
/**
* This test effectively verifies that the internal 'constants' map is properly
* configured for all cache constants defined in {@link DefaultMessageListenerContainer}.
*/
@Test
void setCacheLevelNameToAllSupportedValues() {
DefaultMessageListenerContainer container = new DefaultMessageListenerContainer();
Set<Integer> uniqueValues = new HashSet<>();
streamCacheConstants()
.forEach(name -> {
container.setCacheLevelName(name);
int cacheLevel = container.getCacheLevel();
assertThat(cacheLevel).isBetween(0, 4);
uniqueValues.add(cacheLevel);
});
assertThat(uniqueValues).hasSize(5);
}
@Test
void setCacheLevel() {
DefaultMessageListenerContainer container = new DefaultMessageListenerContainer();
assertThatIllegalArgumentException().isThrownBy(() -> container.setCacheLevel(999));
container.setCacheLevel(DefaultMessageListenerContainer.CACHE_NONE);
assertThat(container.getCacheLevel()).isEqualTo(DefaultMessageListenerContainer.CACHE_NONE);
container.setCacheLevel(DefaultMessageListenerContainer.CACHE_CONNECTION);
assertThat(container.getCacheLevel()).isEqualTo(DefaultMessageListenerContainer.CACHE_CONNECTION);
container.setCacheLevel(DefaultMessageListenerContainer.CACHE_SESSION);
assertThat(container.getCacheLevel()).isEqualTo(DefaultMessageListenerContainer.CACHE_SESSION);
container.setCacheLevel(DefaultMessageListenerContainer.CACHE_CONSUMER);
assertThat(container.getCacheLevel()).isEqualTo(DefaultMessageListenerContainer.CACHE_CONSUMER);
container.setCacheLevel(DefaultMessageListenerContainer.CACHE_AUTO);
assertThat(container.getCacheLevel()).isEqualTo(DefaultMessageListenerContainer.CACHE_AUTO);
}
private static Stream<String> streamCacheConstants() {
return Arrays.stream(DefaultMessageListenerContainer.class.getFields())
.filter(ReflectionUtils::isPublicStaticFinal)
.filter(field -> field.getName().startsWith("CACHE_"))
.map(Field::getName);
}
private static DefaultMessageListenerContainer createRunningContainer() {
DefaultMessageListenerContainer container = createContainer(createSuccessfulConnectionFactory());
container.setCacheLevel(DefaultMessageListenerContainer.CACHE_CONNECTION);
container.setBackOff(new FixedBackOff(100, 1));
container.afterPropertiesSet();
container.start();
return container;
}
private static ConnectionFactory createSuccessfulConnectionFactory() {
try {
ConnectionFactory connectionFactory = mock();
given(connectionFactory.createConnection()).willReturn(mock());
return connectionFactory;
}
catch (JMSException ex) {
throw new IllegalStateException(ex); // never happen
}
}
private static DefaultMessageListenerContainer createContainer(ConnectionFactory connectionFactory) {
Destination destination = new Destination() {};
DefaultMessageListenerContainer container = new DefaultMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
container.setCacheLevel(DefaultMessageListenerContainer.CACHE_NONE);
container.setDestination(destination);
return container;
}
private static ConnectionFactory createFailingContainerFactory() {
try {
ConnectionFactory connectionFactory = mock();
given(connectionFactory.createConnection()).will(invocation -> {
throw new JMSException("Test exception");
});
return connectionFactory;
}
catch (JMSException ex) {
throw new IllegalStateException(ex); // never happen
}
}
private static ConnectionFactory createRecoverableContainerFactory(final int failingAttempts) {
try {
ConnectionFactory connectionFactory = mock();
given(connectionFactory.createConnection()).will(new Answer<Object>() {
int currentAttempts = 0;
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
currentAttempts++;
if (currentAttempts <= failingAttempts) {
throw new JMSException("Test exception (attempt " + currentAttempts + ")");
}
else {
return mock(Connection.class);
}
}
});
return connectionFactory;
}
catch (JMSException ex) {
throw new IllegalStateException(ex); // never happen
}
}
private static class TestRunnable implements Runnable {
private final CountDownLatch countDownLatch = new CountDownLatch(1);
@Override
public void run() {
this.countDownLatch.countDown();
}
void waitForCompletion() throws InterruptedException {
this.countDownLatch.await(1, TimeUnit.SECONDS);
assertThat(this.countDownLatch.getCount()).as("callback was not invoked").isEqualTo(0);
}
}
}
|
package com.infohold.bdrp.authority.dao;
import java.util.List;
import com.infohold.bdrp.authority.model.AuthResource;
import com.infohold.bdrp.authority.model.AuthRole;
import com.infohold.bdrp.authority.model.AuthUser;
public interface AuthorityDao<T extends AuthUser,K extends AuthRole> {
public List<T> findAuthUser(AuthUser token);
public List<K> findAuthRole(AuthUser token);
public List<AuthResource> findAuthResources(AuthUser token);
}
|
package Main;
import java.util.Scanner;
/**
* Created by Samarth on 5/30/16.
*/
public class SherlockAndSquares {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
for(int a0 = 0; a0 < t; a0++){
int f = in.nextInt();
int s = in.nextInt();
System.out.println(getNumberOfSquares(f, s));
}
}
public static int getNumberOfSquares(int first, int second) {
int count = 0;
int num = 1;
int square = num*num;
while (square < first) {
num++;
square = num*num;
}
while (square <= second) {
count++;
num++;
square = num*num;
}
return count;
}
}
|
package ua.siemens.dbtool.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ua.siemens.dbtool.dao.WorkPackageTypeDAO;
import ua.siemens.dbtool.model.auxilary.WorkPackageType;
import ua.siemens.dbtool.model.entities.Project;
import ua.siemens.dbtool.service.JsonService;
import ua.siemens.dbtool.service.WorkPackageTypeService;
import java.util.Collection;
import java.util.Comparator;
import java.util.stream.Collectors;
/**
* Implementation of {@link WorkPackageTypeService}
*
* @author Perevoznyk Pavlo
* creation date 29 August 2017
* @version 1.0
*/
@Service
public class WorkPackageTypeServiceImpl implements WorkPackageTypeService {
private WorkPackageTypeDAO workPackageTypeDAO;
private JsonService jsonService;
@Autowired
public WorkPackageTypeServiceImpl(WorkPackageTypeDAO workPackageTypeDAO, JsonService jsonService) {
this.workPackageTypeDAO = workPackageTypeDAO;
this.jsonService = jsonService;
}
@Override
@Transactional
public void save(WorkPackageType workPackageType) {
workPackageTypeDAO.save(workPackageType);
}
@Override
@Transactional
public void save(String workPackageType) {
WorkPackageType wpType = jsonService.convertJsonToWpType(workPackageType);
if (workPackageTypeDAO.findAll().contains(wpType)) {
throw new DataIntegrityViolationException("WP type exists already!");
}
save(wpType);
}
@Override
@Transactional
public void update(WorkPackageType workPackageType) {
workPackageTypeDAO.update(workPackageType);
}
@Override
@Transactional
public void delete(Long id) {
workPackageTypeDAO.delete(id);
}
@Override
@Transactional
public WorkPackageType findById(Long id) {
return workPackageTypeDAO.findById(id);
}
@Override
@Transactional
public Collection<WorkPackageType> findAllByProject(Project project) {
Collection<WorkPackageType> wps = workPackageTypeDAO.findAll();
if(project.isInternal()){
return wps.stream().filter(a -> a.getProject() != null)
.filter(a -> a.getProject().getId().equals(project.getId()))
.sorted(Comparator.comparing(WorkPackageType::getName))
.collect(Collectors.toList());
}
return wps.stream()
.sorted(Comparator.comparing(WorkPackageType::getName))
.collect(Collectors.toList());
}
@Override
@Transactional
public Collection<WorkPackageType> findAllInternal() {
return workPackageTypeDAO.findAllInternal();
}
@Override
public String getTree(Collection<Project> internalProjects) {
return jsonService.prepareWpTypesTree(internalProjects, findAllInternal());
}
}
|
package com.sankalpa.bigdata.hdfs.client;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
public class HDFSClient {
private File coreSiteConfPath;
private File hdfsSiteConfPath;
private Path coreSitePath;
private Path hdfsSitePath;
private Configuration conf;
private FileSystem fileSystem;
// The config directory is passed by the user's main program
public HDFSClient(String siteConfDir) throws IOException {
if (validatePath(siteConfDir) == 1) {
System.out.println("Error validating path. Exiting...");
System.exit(1);
}
coreSitePath = new Path(coreSiteConfPath.getPath()); // getPath() returns a String
hdfsSitePath = new Path(hdfsSiteConfPath.getPath());
conf = new Configuration();
// Conf object will read the HDFS configuration parameters from these
// XML files.
conf.addResource(coreSitePath);
conf.addResource(hdfsSitePath);
try {
fileSystem = FileSystem.get(conf);
} catch(IOException e) { // failed or interrupted I/O operations
System.out.println("An exception has occurred during HDFSClient init: I/O exception: " + e.getMessage());
System.exit(1);
}
}
private int validatePath(String siteConfDir) {
File siteConfDirPath = new File(siteConfDir);
if (siteConfDirPath.exists() == false) {
System.out.println("ERROR: The argument " + siteConfDirPath.getPath() + " does not exist.");
return 1;
}
if (siteConfDirPath.isDirectory() == false) {
System.out.println("ERROR: The argument " + siteConfDirPath.getPath() + " must be a directory.");
return 1;
}
if (siteConfDirPath.canRead() == false) {
System.out.println("ERROR: The argument " + siteConfDirPath.getPath() + " is not readable by me.");
return 1;
}
coreSiteConfPath = new File(siteConfDirPath, "core-site.xml");
if (coreSiteConfPath.exists() == false) {
System.out.println("ERROR: The argument " + coreSiteConfPath.getPath() + " does not exist.");
return 1;
}
if (coreSiteConfPath.isFile() == false) {
System.out.println("ERROR: The argument " + coreSiteConfPath.getPath() + " must be a file.");
return 1;
}
if (coreSiteConfPath.canRead() == false) {
System.out.println("ERROR: The argument " + coreSiteConfPath.getPath() + " is not readable by me.");
return 1;
}
hdfsSiteConfPath = new File(siteConfDirPath, "hdfs-site.xml");
if (hdfsSiteConfPath.exists() == false) {
System.out.println("ERROR: The argument " + hdfsSiteConfPath.getPath() + " does not exist.");
return 1;
}
if (hdfsSiteConfPath.isFile() == false) {
System.out.println("ERROR: The argument " + hdfsSiteConfPath.getPath() + " must be a file.");
return 1;
}
if (hdfsSiteConfPath.canRead() == false) {
System.out.println("ERROR: The argument " + hdfsSiteConfPath.getPath() + " is not readable by me.");
return 1;
}
return 0;
}
public void addFile(String source, String dest) throws IOException {
// Get the filename out of the file path
String filename = source.substring(source.lastIndexOf('/') + 1,
source.length());
// Create the destination path including the filename
if (dest.charAt(dest.length() - 1) != '/') {
dest = dest + "/" + filename;
} else {
dest = dest + filename;
}
System.out.println("Adding file to " + dest);
// Check if the file already exists
Path path = new Path(dest);
if (fileSystem.exists(path)) {
System.out.println("File " + dest + " already exists");
return;
}
// Create a new file and write data to it
FSDataOutputStream out = fileSystem.create(path);
InputStream in = new BufferedInputStream(new FileInputStream(
new File(source)));
byte[] b = new byte[1024];
int numBytes = 0;
while ((numBytes = in.read(b)) > 0) {
out.write(b, 0, numBytes);
}
// Close all the file descriptors
in.close();
out.close();
fileSystem.close();
}
public void readFile(String file) throws IOException {
Path path = new Path(file);
if (!fileSystem.exists(path)) {
System.out.println("File " + file + " does not exist");
return;
}
FSDataInputStream in = fileSystem.open(path);
String filename = file.substring(file.lastIndexOf('/') + 1,
file.length());
OutputStream out = new BufferedOutputStream(new FileOutputStream(
new File(filename)));
byte[] b = new byte[1024];
int numBytes = 0;
while ((numBytes = in.read(b)) > 0) {
out.write(b, 0, numBytes);
}
in.close();
out.close();
fileSystem.close();
}
public void deleteFile(String file) throws IOException {
Path path = new Path(file);
if (!fileSystem.exists(path)) {
System.out.println("File " + file + " does not exist");
return;
}
fileSystem.delete(new Path(file), true);
fileSystem.close();
}
public void mkdir(String dir) throws IOException {
Path path = new Path(dir);
if (fileSystem.exists(path)) {
System.out.println("Dir " + dir + " already exists");
return;
}
fileSystem.mkdirs(path);
fileSystem.close();
}
private static void usage() {
System.out.println("Usage: HDFSClient add/read/delete/mkdir" +
" [<local_path> <hdfs_path>]");
}
public static void main(String[] args) throws IOException {
if (args.length < 1) {
usage();
System.exit(1);
}
if (args[0].equals("--help") || args[0].equals("-h")) {
usage();
System.exit(0);
}
System.out.println("HDFSClient: Starting...");
HDFSClient client = new HDFSClient("/Users/rohithvsm/workspace/big_data/hadoop/hadoop-dist/target/hadoop-2.6.0/etc/hadoop");
if (args[0].equals("add")) {
if (args.length < 3) {
System.out.println("Usage: HDFSClient add <local_path> " +
"<hdfs_path>");
System.exit(1);
}
client.addFile(args[1], args[2]);
} else if (args[0].equals("read")) {
if (args.length < 2) {
System.out.println("Usage: HDFSClient read <hdfs_path>");
System.exit(1);
}
client.readFile(args[1]);
} else if (args[0].equals("delete")) {
if (args.length < 2) {
System.out.println("Usage: HDFSClient delete <hdfs_path>");
System.exit(1);
}
client.deleteFile(args[1]);
} else if (args[0].equals("mkdir")) {
if (args.length < 2) {
System.out.println("Usage: HDFSClient mkdir <hdfs_path>");
System.exit(1);
}
client.mkdir(args[1]);
} else {
usage();
System.exit(1);
}
System.out.println("HDFSClient: Done!");
}
}
|
package Study5;
public class S1AbsImpl implements S1Abs {
@Override
public void methodAbs1() {
System.out.println("1");
}
@Override
public void methodAbs2() {
System.out.println("2");
}
@Override
public void methodAbs3() {
System.out.println("3");
}
}
|
package com.github.mobile.ui.repo;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import com.github.kevinsawicki.wishlist.SingleTypeAdapter;
import com.github.mobile.R;
import com.github.mobile.ui.PagedItemFragment;
import org.eclipse.egit.github.core.Repository;
import org.eclipse.egit.github.core.User;
import java.util.List;
import static com.github.mobile.Intents.EXTRA_USER;
import static com.github.mobile.RequestCodes.REPOSITORY_VIEW;
import static com.github.mobile.ResultCodes.RESOURCE_CHANGED;
/**
* Fragment to display a list of repositories for a {@link User}
*/
public abstract class UserRepositoryListFragment extends PagedItemFragment<Repository> {
protected User user;
@Override
public void onAttach(Context context) {
super.onAttach(context);
user = getSerializableExtra(EXTRA_USER);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setEmptyText(R.string.no_repositories);
}
@Override
protected int getLoadingMessage() {
return R.string.loading_repositories;
}
@Override
protected int getErrorMessage(Exception exception) {
return R.string.error_repos_load;
}
@Override
protected SingleTypeAdapter<Repository> createAdapter(List<Repository> items) {
return new UserRepositoryListAdapter(getActivity().getLayoutInflater(),
items.toArray(new Repository[items.size()]), user);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REPOSITORY_VIEW && resultCode == RESOURCE_CHANGED) {
forceRefresh();
return;
}
super.onActivityResult(requestCode, resultCode, data);
}
@Override
public void onListItemClick(ListView list, View v, int position, long id) {
Repository repo = (Repository) list.getItemAtPosition(position);
startActivityForResult(RepositoryViewActivity.createIntent(repo),
REPOSITORY_VIEW);
}
}
|
package project2;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Scanner;
public class JdbcDemo {
public static void main(String args[])
{
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con= DriverManager.getConnection("jdbc:mysql://localhost:3306/Java","root","Sapient123");
PreparedStatement pstmt =con.prepareStatement("insert into EMP values(?,?)");
Scanner sc=new Scanner(System.in);
String name= sc.nextLine();
int age =sc.nextInt();
//databasename
pstmt.setString(1,name);
pstmt.setInt(2,age);
pstmt.execute();
/*ResultSet rs=stmt.executeQuery("select * from EMP");
while(rs.next())
{
System.out.println("name :"+rs.getString(1));
System.out.println("age is"+rs.getInt(2));
}*/
//rs.close();
//stmt.close();
//con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
|
package com.espian.showcaseview.targets;
import android.graphics.Point;
public interface Target {
public Point getPoint();
}
|
package ru.job4j.control;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* Класс BalancerSemaphoreTest иллюстрирует работу класса java.util.concurrent.Semaphore.
*
* @author Gureyev Ilya (mailto:ill-jah@yandex.ru)
* @version 1
* @since 2017-09-01
*/
public class BalancerSemaphoreTest {
/**
* Иллюстрирует работу класса Semaphore.
*/
@Test
public void showSemaphore() {
int threads = 500;
int requests = 1000;
int semaforeCount = 5;
BalancerSemaphore balancer = new BalancerSemaphore(semaforeCount);
UpperSemaphore[] uppers = new UpperSemaphore[threads];
DownerSemaphore[] downers = new DownerSemaphore[threads];
for (int a = 0; a < threads; a++) {
uppers[a] = new UpperSemaphore(balancer, requests);
downers[a] = new DownerSemaphore(balancer, requests);
}
for (int a = 0; a < threads; a++) {
uppers[a].start();
downers[a].start();
}
try {
for (int a = 0; a < threads; a++) {
uppers[a].join();
downers[a].join();
}
} catch (InterruptedException ex) {
ex.printStackTrace();
}
assertEquals(0, balancer.get());
assertEquals(threads * requests, balancer.getReqsDown());
assertEquals(threads * requests, balancer.getReqsUp());
}
} |
package 多线程.同步;
/**
* Created by 陆英杰
* 2018/9/7 10:31
*/
public class 同步代码块 {
public static void main(String[] args) {
Runnable runnable=new Thread1();//new 一个可以被线程运行的类型,因为这个类实现了Runnable接口
Thread thread1=new Thread(runnable,"线程1");//让thread1线程运行runnable类中的run方法
Thread thread2=new Thread(runnable,"线程2");//让thread2线程运行runnable类中的run方法
thread1.start();
thread2.start();
}
}
/**
* DESC: 如果不加同步的话,那么a的值可能会被重复的打印两次
*/
class Thread1 implements Runnable{
private static int a=20;//共享数据
@Override
public void run() {
while(a>0){
synchronized (this){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+" : "+a--);
}
}
}
} |
package com.nps.hellow.radar;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.view.View;
import com.nps.hellow.R;
/**
* Created by Daniel on 13/01/2015.
* adapté de http://davy-leggieri.developpez.com/tutoriels/android/creation-boussole/
*/
public class RadarView extends View {
private float targetOrientation = 0;
private Paint circlePaint;
private Paint northPaint;
private Path trianglePath;
//Délai entre chaque image
private final int DELAY = 10;
//Durée de l'animation
private final int DURATION = 1000;
private float startOrientation;
private float endOrientation;
//Heure de début de l'animation (ms) pour la fluidité
private long startTime;
public RadarView(Context context) {
super(context);
initView();
}
public RadarView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public RadarView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public float getArrowOrientation() {
return targetOrientation;
}
public void setArrowOrientation(float rotation) {
if (rotation != this.targetOrientation) {
removeCallbacks(animationTask);
this.startOrientation = this.targetOrientation;
this.endOrientation = rotation;
//Détermination du sens de rotation de l'aiguille
if (((startOrientation + 180) % 360) > endOrientation) {
if ((startOrientation - endOrientation) > 180) {
endOrientation += 360;
}
} else {
if ((endOrientation - startOrientation) > 180) {
startOrientation += 360;
}
}
startTime = SystemClock.uptimeMillis();
postDelayed(animationTask, DELAY);
}
}
private Runnable animationTask = new Runnable() {
public void run() {
long curTime = SystemClock.uptimeMillis();
long totalTime = curTime - startTime;
if (totalTime > DURATION) {
targetOrientation = endOrientation % 360;
removeCallbacks(animationTask);
} else {
// fluidité de l'aiguille
float perCent = ((float) totalTime) / DURATION;
perCent = (float) Math.sin(perCent * 1.5);
perCent = Math.min(perCent, 1);
targetOrientation = (float) (startOrientation + perCent * (endOrientation - startOrientation));
postDelayed(this, DELAY);
}
invalidate();
}
};
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int measuredWidth = measure(widthMeasureSpec);
int measuredHeight = measure(heightMeasureSpec);
// Notre vue sera un carré, on garde donc le minimum
int d = Math.min(measuredWidth, measuredHeight);
setMeasuredDimension(d, d);
}
private int measure(int measureSpec) {
int result = 0;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
if (specMode == MeasureSpec.UNSPECIFIED) {
result = 150;
} else {
result = specSize;
}
return result;
}
private void initView() {
Resources r = this.getResources();
// Paint pour l'arrière plan de la boussole
circlePaint = new Paint(Paint.ANTI_ALIAS_FLAG); // Lisser les formes
circlePaint.setColor(r.getColor(R.color.compassCircle));
// Paint de l'aiguille
northPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
northPaint.setColor(r.getColor(R.color.northPointer)); // Couleur par défaut inutile
// Path pour dessiner les aiguilles
trianglePath = new Path();
}
public void setColor(int color) {
northPaint.setColor(color);
}
@Override
protected void onDraw(Canvas canvas) {
//On détermine le point au centre de notre vue
int centerX = getMeasuredWidth() / 2;
int centerY = getMeasuredHeight() / 2;
// On détermine le diamètre du cercle (arrière plan de la boussole)
int radius = Math.min(centerX, centerY);
// On dessine un cercle avec le " pinceau " circlePaint
canvas.drawCircle(centerX, centerY, radius, circlePaint);
// On sauvegarde la position initiale du canevas
canvas.save();
// On tourne le canevas pour que le nord pointe vers le haut
canvas.rotate(-targetOrientation, centerX, centerY);
// on créer une forme triangulaire qui part du centre du cercle et
// pointe vers le haut
trianglePath.reset();//RAZ du path (une seule instance)
trianglePath.moveTo(centerX, 10);
trianglePath.lineTo(centerX - 100, centerY);
trianglePath.lineTo(centerX + 100, centerY);
// On désigne l'aiguille
canvas.drawPath(trianglePath, northPaint);
canvas.restore();
}
}
|
package org.foolip.mushup;
import org.musicbrainz.model.*;
import org.neo4j.api.core.Node;
import org.neo4j.api.core.Relationship;
import org.neo4j.api.core.Direction;
import org.neo4j.util.index.IndexService;
import java.util.*;
public class MushArtist extends MushEntity implements Artist {
private static final String KEY_TYPE = "type";
private static final String KEY_NAME = "name";
private static final String KEY_SORT_NAME = "sortName";
private static final String KEY_DISAMBIGUATION = "disambiguation";
MushArtist(Node underlyingNode, IndexService indexService) {
super(underlyingNode, indexService);
}
public String getType() {
return (String)underlyingNode.getProperty(KEY_TYPE);
}
public void setType(String type) {
underlyingNode.setProperty(KEY_TYPE, type);
}
public String getName() {
return (String)underlyingNode.getProperty(KEY_NAME);
}
public void setName(String name) {
underlyingNode.setProperty(KEY_NAME, name);
}
public String getSortName() {
return (String)underlyingNode.getProperty(KEY_SORT_NAME);
}
public void setSortName(String sortName) {
underlyingNode.setProperty(KEY_SORT_NAME, sortName);
}
public String getDisambiguation() {
return (String)underlyingNode.getProperty(KEY_DISAMBIGUATION);
}
public void setDisambiguation(String disamb) {
underlyingNode.setProperty(KEY_DISAMBIGUATION, disamb);
}
public Iterable<Release> getReleases() {
// FIXME: why does this suck so badly?
LinkedList<Release> releases = new LinkedList<Release>();
for (Relationship rel : underlyingNode.
getRelationships(RelTypes.RELEASE, Direction.OUTGOING)) {
releases.add(new MushRelease(rel.getEndNode(), this.indexService));
}
return releases;
}
public void addRelease(Release rel) {
underlyingNode.createRelationshipTo(((MushRelease)rel).getUnderlyingNode(), RelTypes.RELEASE);
}
}
|
package model;
import image.Image;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import image.Pixel;
/**
* This class represents a simple model of an image processing application.
*/
public class SimpleMultiLayerImageProcessingModel implements MultiLayerImageProcessingModel {
protected List<Layer> layers;
protected int currentLayerIndex;
protected int width;
protected int height;
/**
* Creates a image processing model with an empty list of layers, a default layer index, width,
* and height of -1.
*/
public SimpleMultiLayerImageProcessingModel() {
this.layers = new ArrayList<>();
this.currentLayerIndex = -1;
this.width = -1;
this.height = -1;
}
/**
* Copy constructor for the model.
* @param model The model to be copied.
*/
public SimpleMultiLayerImageProcessingModel(SimpleMultiLayerImageProcessingModel model) {
this.layers = model.getLayers();
this.currentLayerIndex = model.currentLayerIndex;
this.width = model.width;
this.height = model.height;
}
@Override
public void imageFilter(Filter filter) throws IllegalArgumentException, IllegalStateException {
if (filter == null) {
throw new IllegalArgumentException("Given filter was null.");
}
if (currentLayerIndex == -1) {
throw new IllegalStateException("There is no image to apply the filter on.");
}
Layer layer = layers.get(currentLayerIndex);
double[][] matrix = filter.getMatrix();
Image postImage = layer.getImage().imageFilter(matrix);
layer.loadImage(postImage);
}
@Override
public void colorTransformation(ColorTransformation ct) throws IllegalArgumentException,
IllegalStateException {
if (ct == null) {
throw new IllegalArgumentException("Color transformation was null.");
}
if (currentLayerIndex == -1) {
throw new IllegalStateException("There is no image to apply the color transformation on.");
}
Layer layer = layers.get(currentLayerIndex);
double[][] matrix = ct.getMatrix();
Image postImage = layer.getImage().colorTransformation(matrix);
layer.loadImage(postImage);
}
@Override
public void makeCheckerBoard(int length) throws IllegalArgumentException {
if (length <= 0) {
throw new IllegalArgumentException("The length of the checkerboard cannot be 0 or negative.");
}
List<List<Pixel>> pixels = new ArrayList<>();
boolean whiteTile = true;
for (int i = 0; i < length; i++) {
pixels.add(new ArrayList<>());
for (int j = 0; j < length; j++) {
if (whiteTile) {
pixels.get(i).add(new Pixel(0, 0, 0));
whiteTile = false;
}
else {
pixels.get(i).add(new Pixel(255, 255, 255));
whiteTile = true;
}
}
}
Image im = new Image(pixels, length, length);
importImage(im);
}
@Override
public void importImage(Image im) throws IllegalArgumentException {
if (im == null) {
throw new IllegalArgumentException("You must give a name.");
}
if (currentLayerIndex == -1) {
throw new IllegalStateException("There is no layer to load this image.");
}
if (width == -1 && height == -1) {
this.width = im.getWidth();
this.height = im.getHeight();
}
if (im.getWidth() != width || im.getHeight() != height) {
throw new IllegalArgumentException("Cannot load in an image that is of different dimension "
+ "from the rest of the layers.");
}
layers.get(currentLayerIndex).loadImage(im);
}
//Tries to export the topmost visible layer. If the topmost visible layer does not have an
//image loaded into it, all the layer are invisible, or there are no layers then we throw
//exceptions.
@Override
public Image exportImage() throws IllegalStateException {
if (layers.size() == 0) {
throw new IllegalStateException("There are no layers.");
}
for (int i = layers.size() - 1; i >= 0; i--) {
if (layers.get(i).getVisibility()) {
try {
Image im = layers.get(i).getImage();
return im;
} catch (IllegalStateException e) {
// do nothing and don't export this layer since no image is loaded
}
}
}
throw new IllegalStateException("All the layers are invisible.");
}
@Override
public void createLayer(String name) {
if (name == null) {
throw new IllegalArgumentException("You must give a name.");
}
for (Layer l : layers) {
if (l.getName().equals(name)) {
throw new IllegalArgumentException("Cannot add a new layer with a name that is"
+ " already used.");
}
}
layers.add(new Layer(name));
currentLayerIndex = layers.size() - 1;
}
//Deletes the current layer, if the layer to be deleted is the layer that the user is currently
//on then the current layer is set to the topmost layer
@Override
public void deleteLayer(String name) throws IllegalArgumentException {
if (name == null) {
throw new IllegalArgumentException("You must give a name.");
}
for (int i = 0; i < layers.size(); i++) {
if (layers.get(i).getName().equals(name)) {
layers.remove(layers.get(i));
if (i < currentLayerIndex) {
currentLayerIndex -= 1;
}
else if (i == currentLayerIndex) {
currentLayerIndex = layers.size() - 1;
// this resets the necessary width and height of the layers since there are no layers left
if (layers.size() == 0) {
this.width = -1;
this.height = -1;
}
}
return;
}
}
throw new IllegalArgumentException("Could not find the layer with the given name.");
}
@Override
public void setCurrentLayer(String name) throws IllegalArgumentException {
if (name == null) {
throw new IllegalArgumentException("You must give a name.");
}
for (int i = 0; i < layers.size(); i++) {
if (layers.get(i).getName().equals(name)) {
currentLayerIndex = i;
return;
}
}
throw new IllegalArgumentException("Could not find the layer with the given name.");
}
@Override
public void setVisible(String name) throws IllegalArgumentException {
if (name == null) {
throw new IllegalArgumentException("You must give a name.");
}
for (int i = 0; i < layers.size(); i++) {
if (layers.get(i).getName().equals(name)) {
layers.get(i).setVisible();
return;
}
}
throw new IllegalArgumentException("Could not find the layer with the given name.");
}
@Override
public void setInvisible(String name) throws IllegalArgumentException {
if (name == null) {
throw new IllegalArgumentException("You must give a name.");
}
for (int i = 0; i < layers.size(); i++) {
if (layers.get(i).getName().equals(name)) {
layers.get(i).setInvisible();
return;
}
}
throw new IllegalArgumentException("Could not find the layer with the given name.");
}
@Override
public List<Image> exportLayers() {
List<Image> images = new ArrayList<>();
for (Layer l : layers) {
try {
Image im = l.getImage();
images.add(im);
} catch (IllegalStateException e) {
// do nothing
}
}
return images;
}
@Override
public List<Layer> getLayers() {
List<Layer> layers = new ArrayList<>();
for (Layer l : this.layers) {
try {
Image im = l.getImage();
layers.add(new Layer(Optional.of(im), l.getVisibility(), l.getName()));
} catch (IllegalStateException e) {
layers.add(new Layer(Optional.empty(), l.getVisibility(), l.getName()));
}
}
return layers;
}
@Override
public void reset(SimpleMultiLayerImageProcessingModel newModel) {
this.layers = newModel.layers;
this.currentLayerIndex = newModel.currentLayerIndex;
this.width = newModel.width;
this.height = newModel.height;
}
}
|
package com.accolite.au.services.impl;
import com.accolite.au.dto.CustomEntityNotFoundExceptionDTO;
import com.accolite.au.dto.TrainingDTO;
import com.accolite.au.embeddables.TrainingEmbeddableId;
import com.accolite.au.mappers.TrainingMapper;
import com.accolite.au.models.Training;
import com.accolite.au.models.Session;
import com.accolite.au.models.Student;
import com.accolite.au.repositories.TrainingRepository;
import com.accolite.au.repositories.SessionRepository;
import com.accolite.au.repositories.StudentRepository;
import com.accolite.au.services.TrainingService;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.springframework.stereotype.Service;
import javax.persistence.EntityManager;
import java.util.List;
@Service
public class TrainingServiceImpl implements TrainingService {
private final TrainingRepository trainingRepository;
private final SessionRepository sessionRepository;
private final EntityManager entityManager;
private final StudentRepository studentRepository;
private final TrainingMapper trainingMapper;
public TrainingServiceImpl(TrainingRepository trainingRepository, SessionRepository sessionRepository,
EntityManager entityManager, StudentRepository studentRepository, TrainingMapper trainingMapper) {
this.trainingRepository = trainingRepository;
this.sessionRepository = sessionRepository;
this.entityManager = entityManager;
this.studentRepository = studentRepository;
this.trainingMapper = trainingMapper;
}
@Override
public TrainingDTO markAndUpdateTrainingData(TrainingDTO trainingDTO, char type) {
if(sessionRepository.existsById(trainingDTO.getAttendanceId().getSessionId()) &&
studentRepository.existsById(trainingDTO.getAttendanceId().getStudentId())){
TrainingEmbeddableId trainingEmbeddableId = new TrainingEmbeddableId(trainingDTO.getAttendanceId().getSessionId(), trainingDTO.getAttendanceId().getStudentId());
Training training;
if(trainingRepository.existsById(trainingEmbeddableId)){
training = trainingRepository.getOne(trainingEmbeddableId);
if(type == 'M' || type == 'm'){
training.setMarks(trainingDTO.getMarks());
}
else{
training.setStatus(trainingDTO.getStatus());
}
}
else {
// if record doesn't already exists
training = trainingMapper.toTraining(trainingDTO);
Student student = entityManager.getReference(Student.class, trainingDTO.getAttendanceId().getStudentId());
Session session = entityManager.getReference(Session.class, trainingDTO.getAttendanceId().getSessionId());
training.setSession(session);
training.setStudent(student);
}
return trainingMapper.toTrainingDTO(trainingRepository.saveAndFlush(training));
}
else if(!sessionRepository.existsById(trainingDTO.getAttendanceId().getSessionId())){
throw new CustomEntityNotFoundExceptionDTO("Session with id : " + trainingDTO.getAttendanceId().getSessionId() + " not Found");
}
throw new CustomEntityNotFoundExceptionDTO("Student with id : " + trainingDTO.getAttendanceId().getStudentId() + " not Found");
}
@Override
public TrainingDTO getTrainingData(int sessionId, int studentId){
if(sessionRepository.existsById(sessionId) && studentRepository.existsById(studentId)){
return trainingMapper.toTrainingDTO(trainingRepository.getOne(new TrainingEmbeddableId(sessionId, studentId)));
}
else if(!sessionRepository.existsById(sessionId)){
throw new CustomEntityNotFoundExceptionDTO("Session with id : " + sessionId + " not Found");
}
throw new CustomEntityNotFoundExceptionDTO("Student with id : " + studentId + " not Found");
}
@Override
public ObjectNode getAllTrainingData(char type, int batchId){
// GENERATING CUSTOM ATTENDANCE RESPONSE
// Object Mapper
ObjectMapper mapper = new ObjectMapper();
// create a ObjectNode root Node
ObjectNode rootNode = mapper.createObjectNode();
List<String[]> sessionsReport ;
// if(type == 'A' || type == 'a'){
// sessionsReport = trainingRepository.findAllSessionsAttendeesCount(); // [[total_present_count, 1, 'session1'], [total_present_count, 2, 'session2']]
// }
// else{
// sessionsReport = trainingRepository.findAllSessionsMarks(); // [[avg_marks, 1, 'session1'], [avg_marks, 2, 'session2']]
// }
//sessionsReport = sessionRepository.findAllSessions();
sessionsReport = sessionRepository.findAllSessionsByBatchId(batchId);
ArrayNode sessionNode = mapper.createArrayNode();
for(String[] row: sessionsReport){
ObjectNode tempSessionEntity = mapper.createObjectNode();
tempSessionEntity.put("sessionId", row[1]);
tempSessionEntity.put("sessionName", row[0]);
sessionNode.add(tempSessionEntity);
}
rootNode.set("sessions", sessionNode);
ArrayNode attendanceDataNode = mapper.createArrayNode();
for (Student student : studentRepository.findAllByBatch_BatchIdOrderByFirstNameAsc(batchId)) {
List<String[]> tempSessions = trainingRepository.findAllSessionsForStudent(student.getStudentId()); // [['session1', 'A', 12], ['session2', 'P', 45]]
ObjectNode tempEntity = mapper.createObjectNode();
// Creating Student JSONObject
ObjectNode tempStudentEntity = mapper.createObjectNode();
tempStudentEntity.put("studentName", student.getFirstName() + " " + student.getLastName());
tempStudentEntity.put("studentEmail", student.getEmailId());
tempStudentEntity.put("studentFirstName", student.getFirstName());
tempStudentEntity.put("studentLastName", student.getLastName());
tempStudentEntity.put("studentId", student.getStudentId());
tempEntity.put("student", tempStudentEntity.toString());
tempEntity.set("student", tempStudentEntity);
for (String[] row : tempSessions) {
ObjectNode tempSessionEntity = mapper.createObjectNode();
tempSessionEntity.put("sessionName", row[1]);
if(type == 'M' || type == 'm') {
tempSessionEntity.put("marks", row[3]);
}
else{
tempSessionEntity.put("attendance", row[2]);
}
tempEntity.set(row[0], tempSessionEntity);
}
attendanceDataNode.add(tempEntity);
}
if(type == 'M' || type == 'm') {
rootNode.set("marksData", attendanceDataNode);
}
else{
rootNode.set("attendanceData", attendanceDataNode);
}
return rootNode;
}
}
|
package org.bellatrix.services;
import java.math.BigDecimal;
import org.bellatrix.data.AccountView;
import org.bellatrix.data.MemberView;
import org.bellatrix.data.ResponseStatus;
public class BalanceInquiryResponse {
private String formattedBalance;
private BigDecimal balance;
private BigDecimal reservedAmount;
private String formattedReservedAmount;
private ResponseStatus status;
private MemberView member;
private AccountView account;
public String getFormattedBalance() {
return formattedBalance;
}
public void setFormattedBalance(String formattedBalance) {
this.formattedBalance = formattedBalance;
}
public BigDecimal getBalance() {
return balance;
}
public void setBalance(BigDecimal balance) {
this.balance = balance;
}
public ResponseStatus getStatus() {
return status;
}
public void setStatus(ResponseStatus status) {
this.status = status;
}
public BigDecimal getReservedAmount() {
return reservedAmount;
}
public void setReservedAmount(BigDecimal reservedAmount) {
this.reservedAmount = reservedAmount;
}
public String getFormattedReservedAmount() {
return formattedReservedAmount;
}
public void setFormattedReservedAmount(String formattedReservedAmount) {
this.formattedReservedAmount = formattedReservedAmount;
}
public MemberView getMember() {
return member;
}
public void setMember(MemberView member) {
this.member = member;
}
public AccountView getAccount() {
return account;
}
public void setAccount(AccountView account) {
this.account = account;
}
}
|
package com.starfall.created.factory.simplefactory;
/**
* @project JavaProject
* @package com.starfall.created.factory.simplefactory
* @className ConcreteProductA
* @author StarFall
* @date 2019/4/1 23:09
* @description 2.1、具体产品角色A
*/
public class ConcreteProductA implements Product {
@Override
public void productMethod() {
System.out.println("具体的产品角色:" + this.getClass().getName());
}
}
|
package com.basicRest;
import com.Files.Payload;
import io.restassured.path.json.JsonPath;
public class ComplexParse {
public static void main(String[] args) {
// TODO Auto-generated method stub
JsonPath Jsp=new JsonPath(Payload.coursePrice());
//Print the number of course in the Json
int count=Jsp.getInt("courses.size()");
//Courses is an array it will give
System.out.println(count);
//Print the purchaseamount.
int Totalamount=Jsp.getInt("dashboard.purchaseAmount");
//Traverse from Parent to child with.operator
System.out.println(Totalamount);
//print the title of the firstcourse
String title=Jsp.get("courses[0].title");
System.out.println(title);
//print all title and respective Prices.
for(int i=0;i<count;i++)
{
String titleofcourse=Jsp.get("courses["+i+"].title");
System.out.println(Jsp.get("courses["+i+"].price"));
//+i+->Writing a variable in between String
//System.out.println->Always expects String arguments and when we don't know what the line
//Returns in that case just add ".tostring();
System.out.println(titleofcourse);}
//Print number of copies sold by RPA
System.out.println("Print number of copies sold by RPA");
for( int i=0;i<count;i++)
{
String courseTitles=Jsp.get("courses["+i+"].title");
if(courseTitles.equalsIgnoreCase("RPA"))
{
int RPAcopies=Jsp.get("courses["+i+"].copies");
System.out.println(RPAcopies);
break;
}
}}}
|
package VendingMachine1;
/**
* Created by FLK on 4/8/18.
*/
public class SoldOutExcepton extends RuntimeException {
private String message;
public SoldOutExcepton(String string)
{
this.message = string;
}
@Override
public String getMessage(){ return message; }
}
|
package New.practice;
import java.util.Scanner;
public class LoopTest {
public void firstLoop() {
int i = 0, j = 0;
while (true) {
i++;
System.out.println("i=" + i);
while (true) {
j++;
System.out.println("j=" + j);
if (j > 2)
break;
}
j = 0;
if (i > 3)
break;
}System.out.println();
}
public void secondLoop(int num) {
int i, j;
for (i = 1; i <= num; i += 2) {
for (j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
}
for (i = 0; i <= num; i += 2) {
for (j = num; i < j - 1; j--) {
System.out.print("*");
}
System.out.println();
}System.out.println();
}
public void thirdLoop() {
int i, j;
for (i = 2; i <= 9; i++) {
for (j = 1; j <= 9; j++) {
System.out.printf("%dX%d=%d\t", i, j, i * j);
}
System.out.println();
}System.out.println();
}
public void fourthLoop(int i) {
int a;
for (a = 1; a <= 9; a++) {
System.out.printf("%dX%d=%d\n", i, a, i * a);
}System.out.println();
}
public static void main(String[] args) {
LoopTest lt = new LoopTest();
Scanner sc = new Scanner(System.in);
int x;
while (true) {
System.out.println("수행할 연산");
System.out.println("1.while반복문 \n2.입력숫자만큼 별찍기 \n3.전체구구단 \n4.입력한숫자구구단\n5.종료\n");
int num = sc.nextInt();
if (num == 5) // while 무한루프 탈출
{
System.out.println("종료함");
break;
}
switch (num) {
case 1:
lt.firstLoop();
break;
case 2:
System.out.println("최대 별 갯수");
x = sc.nextInt();
lt.secondLoop(x);
break;
case 3:
lt.thirdLoop();
break;
case 4:
System.out.println("계산할 숫자 입력");
x = sc.nextInt();
lt.fourthLoop(x);
break;
default:
System.out.println("정확한 번호 입력");
break;
}
}
}
}
|
package com.connectthedots.util;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
/**
* utilities for dealing with bytes and streams.
*
*/
public class Bytes {
public static String readFully(Reader reader) throws IOException {
if (reader == null) return null;
char[] arr = new char[8*1024]; // 8K at a time
StringBuffer buf = new StringBuffer();
int numRead;
while ((numRead = reader.read(arr, 0, arr.length)) > 0) {
buf.append(arr, 0, numRead);
}
return buf.toString();
}
public static byte[] readFully(InputStream is) throws IOException {
if (is == null) return null;
ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
byte[] buf = new byte[1024];
int read = 0;
while ((read = is.read(buf)) > 0) {
baos.write(buf, 0, read);
}
return baos.toByteArray();
}
} |
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class Edytor extends JFrame implements ActionListener, KeyListener{
JMenu[] menu = {new JMenu("Plik"), new JMenu("Pomoc"), new JMenu("Edycja")};
JMenuItem[] items = { new JMenuItem("Otwórz"),
new JMenuItem("Zapisz"), new JMenuItem("Wyjdź"), new JMenuItem("Opis"), new JMenuItem("Autor"),
new JMenuItem("Kopiuj"), new JMenuItem("Wklej"), new JMenuItem("Wytnij")
};
JPanel panel=new JPanel();
JButton wczytaj = new JButton("Otwórz");
JButton zapisz = new JButton("Zapisz");
JButton autor = new JButton("Autor");
String rodzaj[] = {"Times New Roman", "Arial", "Calibri", "Verdana"};
String rozmiar[] = {"12", "14", "16", "18"};
String kolory[] = {"Czarny", "Czerwony", "Niebieski", "Żółty"};
JComboBox<String> czcionka = new JComboBox<>(rodzaj);
JComboBox<String> wielkosc = new JComboBox<>(rozmiar);
JComboBox<String> kolor = new JComboBox<>(kolory);
JTextArea pole_tekstowe = new JTextArea(20,20);
JScrollPane pole_tekstowe1 = new JScrollPane(pole_tekstowe);
private static final long serialVersionUID = 1L;
Edytor(){
super("Edytor tekstowy");
setSize(600,600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
for (int i = 0; i < items.length; i++)
items[i].addActionListener(this);
menu[0].add(items[0]);
menu[0].add(items[1]);
menu[0].add(items[2]);
menu[1].add(items[3]);
menu[1].add(items[4]);
menu[2].add(items[5]);
menu[2].add(items[6]);
menu[2].add(items[7]);
JMenuBar menubar = new JMenuBar();
for (int i = 0; i < menu.length; i++)
menubar.add(menu[i]);
setJMenuBar(menubar);
panel.setLayout(null);
pole_tekstowe.setLineWrap(true);
panel.setFocusable(true);
panel.add(wczytaj);
wczytaj.addActionListener(this);
panel.add(zapisz);
zapisz.addActionListener(this);
panel.add(autor);
autor.addActionListener(this);
panel.add(pole_tekstowe1);
panel.add(czcionka);
czcionka.addActionListener(this);
czcionka.setSelectedIndex(0);
panel.add(wielkosc);
wielkosc.addActionListener(this);
wielkosc.setSelectedIndex(0);
panel.add(kolor);
kolor.addActionListener(this);
kolor.setSelectedIndex(0);
panel.addKeyListener(this);
pole_tekstowe1.setBounds(10, 40, 565, 450);
autor.setBounds(10, 10, 70, 20);
zapisz.setBounds(90, 10, 80, 20);
wczytaj.setBounds(180, 10, 80, 20);
czcionka.setBounds(270, 10, 140, 20);
wielkosc.setBounds(420, 10, 50, 20);
kolor.setBounds(480, 10, 100, 20);
setContentPane(panel);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
Object zrodlo=e.getSource();
int t = czcionka.getSelectedIndex();
int t1 = wielkosc.getSelectedIndex();
int t2 = kolor.getSelectedIndex();
if(zrodlo==zapisz){
zapisz();
}
if(zrodlo==wczytaj){
wczytaj();
}
if(zrodlo==autor){
JOptionPane.showMessageDialog(this, "Jakub Jaskóła");
}
if(zrodlo==items[0]){
wczytaj();
}
if(zrodlo==items[1]){
zapisz();
}
if(zrodlo==items[2]){
System.exit(0);
}
if(zrodlo==items[3]){
JOptionPane.showMessageDialog(this, " OPIS PROGRAMU \n Skróty klawiszowe: \n ALT+S - Zapis do pliku\n ALT+O - Otwieranie pliku\n(Skróty działają po odpaleniu programu, ale kiedy klikniemy już w pole tekstowe focus ustawia się na polu tekstowym,\n focus wraca po nacisnieciu jakiegos buttona)");
}
if(zrodlo==items[4]){
JOptionPane.showMessageDialog(this, "Jakub Jaskóła");
}
if(zrodlo==items[5]){
pole_tekstowe.copy();
}
if(zrodlo==items[6]){
pole_tekstowe.paste();
}
if(zrodlo==items[7]){
pole_tekstowe.cut();
}
if(t==0){
Font timesNewRomanFont = new Font("Times New Roman", Font.PLAIN, 14);
pole_tekstowe.setFont(timesNewRomanFont);
}
if(t==1) {
Font arialFont = new Font("Arial", Font.PLAIN, 14);
pole_tekstowe.setFont(arialFont);
}
if(t==2) {
Font calibriFont = new Font("Calibri", Font.PLAIN, 14);
pole_tekstowe.setFont(calibriFont);
}
if(t==3) {
Font verdanaFont = new Font("Verdana", Font.PLAIN, 14);
pole_tekstowe.setFont(verdanaFont);
}
if(t1==0){
Font f = pole_tekstowe.getFont();
pole_tekstowe.setFont(f.deriveFont(12.0f));
}
if(t1==1){
Font f = pole_tekstowe.getFont();
pole_tekstowe.setFont(f.deriveFont(14.0f));
}
if(t1==2){
Font f = pole_tekstowe.getFont();
pole_tekstowe.setFont(f.deriveFont(16.0f));
}
if(t1==3){
Font f = pole_tekstowe.getFont();
pole_tekstowe.setFont(f.deriveFont(18.0f));
}
if(t2==0){
Font f = pole_tekstowe.getFont();
pole_tekstowe.setFont(f);
pole_tekstowe.setForeground(Color.BLACK);
}
if(t2==1){
Font f = pole_tekstowe.getFont();
pole_tekstowe.setFont(f);
pole_tekstowe.setForeground(Color.RED);
}
if(t2==2){
Font f = pole_tekstowe.getFont();
pole_tekstowe.setFont(f);
pole_tekstowe.setForeground(Color.BLUE);
}
if(t2==3){
Font f = pole_tekstowe.getFont();
pole_tekstowe.setFont(f);
pole_tekstowe.setForeground(Color.YELLOW);
}
panel.requestFocus();
}
public void wczytaj(){
JFileChooser fc = new JFileChooser();
fc.showOpenDialog(null);
String tekst = "";
File plik = fc.getSelectedFile();
String linia;
try {
BufferedReader br = new BufferedReader(new FileReader(plik));
do {
linia = br.readLine();
if (linia != null)
tekst += linia + "\n";
} while (linia != null);
br.close();
pole_tekstowe.setText(tekst);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void zapisz(){
String linia;
JFileChooser fc = new JFileChooser();
fc.showSaveDialog(null);
linia = pole_tekstowe.getText();
File plik = fc.getSelectedFile();
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(plik+".txt"));
bw.write(linia);
bw.flush();
bw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void keyPressed(KeyEvent kevt) {
if(kevt.getKeyChar()=='s') {
if(kevt.isAltDown()){
zapisz();
}
}
if(kevt.getKeyChar()=='o') {
if(kevt.isAltDown()){
wczytaj();
}
}
}
@Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void keyTyped(KeyEvent kevt) {
}
public static void main(String[] args) {
new Edytor();
}
}
|
package hu.lamsoft.hms.customer.persistence.customer.dao;
import java.util.Date;
import java.util.List;
import org.springframework.stereotype.Repository;
import hu.lamsoft.hms.common.persistence.dao.BaseDao;
import hu.lamsoft.hms.customer.persistence.customer.entity.CustomerMeal;
@Repository
public interface CustomerMealDao extends BaseDao<CustomerMeal> {
List<CustomerMeal> findByCustomerEmailAndTimeOfMealBetween(String customerEmail, Date timeOfMealFrom, Date timeOfMealTo);
}
|
package com.alibaba.druid.bvt.pool;
import java.sql.Connection;
import java.util.Properties;
import junit.framework.TestCase;
import org.junit.Assert;
import com.alibaba.druid.mock.MockConnection;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
public class DruidDataSourceTest_initSql_factory extends TestCase {
private DruidDataSource dataSource;
protected void setUp() throws Exception {
Properties properties = new Properties();
properties.put(DruidDataSourceFactory.PROP_URL, "jdbc:mock:xxx");
properties.put(DruidDataSourceFactory.PROP_INITCONNECTIONSQLS, ";;select 123");
dataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
}
protected void tearDown() throws Exception {
dataSource.close();
}
public void testDefault() throws Exception {
Connection conn = dataSource.getConnection();
MockConnection mockConn = conn.unwrap(MockConnection.class);
Assert.assertEquals("select 123", mockConn.getLastSql());
conn.close();
}
}
|
package com.javarush.task.task10.task1015;
import java.util.ArrayList;
/*
Массив списков строк
*/
public class Solution {
public static void main(String[] args) {
ArrayList<String>[] arrayOfStringList = createList();
printList(arrayOfStringList);
}
public static ArrayList<String>[] createList() {
ArrayList<String>[] array = new ArrayList[3];
ArrayList<String> a1 = new ArrayList<>();
ArrayList<String> a2 = new ArrayList<>();
ArrayList<String> a3 = new ArrayList<>();
a1.add("a");
a1.add("b");
a1.add("c");
a2.add("d");
a2.add("e");
a2.add("f");
a3.add("g");
a3.add("h");
a3.add("q");
array[0] = a1;
array[1] = a2;
array[2] = a3;
return array;
}
public static void printList(ArrayList<String>[] arrayOfStringList) {
for (ArrayList<String> list : arrayOfStringList) {
for (String string : list) {
System.out.println(string);
}
}
}
} |
package com.paydock.androidsdk.View;
import com.paydock.androidsdk.IGetToken;
import com.paydock.javasdk.Models.ExternalCheckoutRequestZipMoney;
import com.paydock.javasdk.Services.Environment;
public interface IZipMoneyInputForm {
void getCheckoutToken(Environment environment, String publicKey, String gatewayID,
IGetToken delegateInterface) throws Exception;
ZipMoneyInputForm setPayDock(Environment environment, String publicKey, String gatewayID,
IGetToken delegateInterface);
ZipMoneyInputForm setMeta(ExternalCheckoutRequestZipMoney.Meta zipMeta);
Boolean validate();
void build();
void hide();
}
|
package nom.hhx.cache.factory;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CacheBuilder
{
private Properties properties;
private final Logger logger = LoggerFactory.getLogger( CacheBuilder.class );
public static class Settings
{
public static final String JVM_PERCENT_SETNAME = "cachesize";
public static final String AUTO_KEY_SETNAME = "autokey";
}
public CacheBuilder()
{
this.properties = new Properties();
this.properties.setProperty( Settings.JVM_PERCENT_SETNAME, "500" );
this.properties.setProperty( Settings.AUTO_KEY_SETNAME, "true" );
}
public CacheBuilder setProperty( String name, String value )
{
if( name == Settings.JVM_PERCENT_SETNAME )
{
try
{
int val = Integer.valueOf( value );
}
catch( Exception e )
{
logger.warn( "Wrong settings value for " + Settings.JVM_PERCENT_SETNAME + ". Default value 500 will be use." );
}
}
this.properties.setProperty( name, value );
return this;
}
protected Properties getProperties()
{
return this.properties;
}
}
|
package com.example.sean.onedroid;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
//a list to store the categories where each component is under, e.g widgets, layouts, containers etc.
private List<String> categories;
//a map to map each component to a specific category
private Map<String, List<String>> items;
/**
* Called when the app is launched. Its the entry point to our application,
*
* @param savedInstanceState
*/
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//expandable list view to hold our information on the launcher activity.
ExpandableListView expandableListView = (ExpandableListView) findViewById(R.id.expandableListView);
fillData();
//Have the adapter populate the data for us
ExpandableListAdapter expandableListAdapter = new MyExpListAdapter(this, categories, items);
expandableListView.setAdapter(expandableListAdapter);
expandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
@Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
String widgetName = new MyExpListAdapter().returnChild(groupPosition, childPosition);
ExampleWidget.widget = widgetName;
launchActivity();
return false;
}
});
}
private void launchActivity() {
//launch the tabbed activity
Intent i = new Intent(this, TabbedActivity.class);
startActivity(i);
}
private void fillData() {
//initialize the categories and the hashmap
categories = new ArrayList<>();
items = new HashMap<>();
//populate the categories
categories.add("Widgtes");
categories.add("Text Fields");
categories.add("Layouts");
categories.add("Containers");
categories.add("Images and Media");
categories.add("Date and Time");
categories.add("Transitions");
categories.add("Advanced");
categories.add("Custom-Google");
categories.add("Custom-Design");
categories.add("Custom-AppCompat");
//create new lists under each category
List<String> widgets = new ArrayList<>();
List<String> textFields = new ArrayList<>();
List<String> layouts = new ArrayList<>();
List<String> containers = new ArrayList<>();
List<String> imagesAndMedia = new ArrayList<>();
List<String> dateAndTime = new ArrayList<>();
List<String> transitions = new ArrayList<>();
List<String> advanced = new ArrayList<>();
List<String> customGoogle = new ArrayList<>();
List<String> customDesign = new ArrayList<>();
List<String> customAppCompat = new ArrayList<>();
//populate each list (referred to as child)
widgets.add("TextView");
widgets.add("Button");
widgets.add("ToggleButton");
widgets.add("CheckBox");
widgets.add("RadioButton");
widgets.add("CheckedTextView");
widgets.add("Spinner");
widgets.add("ProgressBar");
widgets.add("SeekBar");
widgets.add("QuickContactBadge");
widgets.add("RatingBar");
widgets.add("Switch");
widgets.add("Space");
textFields.add("Plain Text");
textFields.add("Password");
textFields.add("Email");
textFields.add("Phone");
textFields.add("Postal Address");
textFields.add("Multiline Text");
textFields.add("Time");
textFields.add("Date");
textFields.add("Number");
textFields.add("AutoCompleteTextView");
textFields.add("MultilineAutoCompleteTextView");
layouts.add("ConstraintLayout");
layouts.add("GridLayout");
layouts.add("FrameLayout");
layouts.add("LinearLayout");
layouts.add("RelativeLayout");
layouts.add("TableLayout");
layouts.add("TableRow");
layouts.add("<fragment>");
containers.add("RadioGroup");
containers.add("ListView");
containers.add("GridView");
containers.add("ExpandableListView");
containers.add("ScrollView");
containers.add("HorizontalScrollView");
containers.add("TabHost");
containers.add("WebView");
containers.add("SearchView");
imagesAndMedia.add("ImageButton");
imagesAndMedia.add("ImageView");
imagesAndMedia.add("VideoView");
dateAndTime.add("TimePicker");
dateAndTime.add("DatePicker");
dateAndTime.add("CalendarView");
dateAndTime.add("Chronometer");
dateAndTime.add("TextClock");
transitions.add("ImageSwitcher");
transitions.add("AdapterViewFlipper");
transitions.add("StackView");
transitions.add("TextSwitcher");
transitions.add("ViewAnimator");
transitions.add("ViewFlipper");
transitions.add("ViewSwitcher");
advanced.add("<include>");
advanced.add("<requestFocus>");
advanced.add("<view>");
advanced.add("ViewStub");
advanced.add("TextureView");
advanced.add("NumberPicker");
customGoogle.add("AdView");
customGoogle.add("MapFragment");
customGoogle.add("MapView");
customDesign.add("CoordinatorLayout");
customDesign.add("AppBarLayout");
customDesign.add("TabLayout");
customDesign.add("TabItem");
customDesign.add("NestedScrollView");
customDesign.add("FloatingActionButton");
customDesign.add("TextInputLayout");
customAppCompat.add("CardView");
customAppCompat.add("Grid_Layout");
customAppCompat.add("RecyclerView");
customAppCompat.add("ToolBar");
//map each list to a specific category
items.put(categories.get(0), widgets);
items.put(categories.get(1), textFields);
items.put(categories.get(2), layouts);
items.put(categories.get(3), containers);
items.put(categories.get(4), imagesAndMedia);
items.put(categories.get(5), dateAndTime);
items.put(categories.get(6), transitions);
items.put(categories.get(7), advanced);
items.put(categories.get(8), customGoogle);
items.put(categories.get(9), customDesign);
items.put(categories.get(10), customAppCompat);
}
}
|
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
/**
* cd Desktop/ENDI-2020/ARTIF-INTEL/PA4-KNN-AUC/knn-pa4/java
*
* javac -d bin src/*.java
*
*
* java -cp bin kNNPA4 ../datasets/sms/train.csv ../datasets/sms/dev.csv 10 cosine spam > ../datasets/sms/sms_predictions/dev_knn_k10_spam_cosine.csv
*
* java -cp bin kNNPA4 ../datasets/sms/train.csv ../datasets/sms/dev.csv 10 euclidean spam > ../datasets/sms/sms_predictions/dev_knn_k10_spam_euclidean.csv
*
* java -cp bin kNNPA4 ../datasets/sms/train.csv ../datasets/sms/dev.csv 10 manhattan spam > ../datasets/sms/sms_predictions/dev_knn_k10_spam_manhattan.csv
*
* Modified version of the k-Nearest Neighbors Classification Algorithm.
* Instead of predicting the class label of an observation, this program outputs the Confidence Score
* that an observation is from the provided Positive Class.
* i.e. Instead of outputting the majority label of an observation, it outputs the percentage
* of an observation's <k> Nearest Neighbors that belong to the given positive class.
*
* @author Eva Rubio.
* (Built off the codebase provided by: Professor Hank Feild)
*/
public class kNNPA4 {
public class Observation {
public ArrayList<Double> features;
public String label;
public Observation(ArrayList<Double> features, String label) {
this.features = features;
this.label = label;
}
public String toString() {
StringBuffer output = new StringBuffer();
String lastCol;
for(int i = 0; i < features.size(); i++){
output.append(features.get(i));
if (i < features.size() - 1) {
output.append(",");
}
if (i == features.size()) {
lastCol = String.format("%.5f", features.get(i));
output.append(lastCol);
}
}
if(label != null)
output.append(",").append(label);
return output.toString();
}
}
public class Dataset {
public ArrayList<String> columnNames;
public ArrayList<Observation> observations;
public Dataset(ArrayList<String> columnNames, ArrayList<Observation> observations) {
this.columnNames = columnNames;
this.observations = observations;
}
public String columnNamesAsCSV() {
StringBuffer output = new StringBuffer();
for (int i = 0; i < columnNames.size(); i++) {
output.append(columnNames.get(i));
if (i < columnNames.size() - 1)
output.append(",");
}
return output.toString();
}
}
/**
* Searching for NaN.
*
* (1) mathematically undefined numerical operations: - ZERO / ZERO = NaN -
* INFINITY - INFINITY = NaN - INFINITY * ZERO = NaN
*
* (2) Numerical operations which don’t have results in real numbers: - SQUARE
* ROOT OF -1 = NaN - LOG OF -1 = NaN
*
* (3) All numeric operations with NaN as an operand produce NaN as a result: - 2
* + NaN = NaN - 2 - NaN = NaN - 2 * NaN = NaN - 2 / NaN = NaN
*
* // 1. static method if (Double.isNaN(doubleValue)) { ... } // 2. object's
* method if (doubleObject.isNaN()) { ... }
*
*
* - if 0/0 -- invalid operation - if .sqrt(-1) -- unrepresentable values
*
* “A constant holding a Not-a-Number (NaN) value of type double. It is
* equivalent to the value returned by
* Double. longBitsToDouble(0x7ff8000000000000L)
* https://www.baeldung.com/java-not-a-number
*
* Calculates the Euclidean distance between 2 observations.
*/
public class EuclideanDistance implements Distance {
public double distance(ArrayList<Double> featuresA, ArrayList<Double> featuresB) {
double sum = 0;
for (int i = 0; i < featuresA.size(); i++)
sum += Math.pow(featuresA.get(i) - featuresB.get(i), 2);
return Math.sqrt(sum);
}
}
/**
* Most of these are just theory... It took me a looong time to remember what trigonomtry was...
*
* https://www.machinelearningplus.com/nlp/cosine-similarity/
* https://www.khanacademy.org/math/precalculus/x9e81a4f98389efdf:vectors/x9e81a4f98389efdf:component-form/a/vector-magnitude-and-direction-review
* https://www.machinelearningplus.com/nlp/cosine-similarity/
* https://www.lasclasesdegonzalo.com/trigonometricosparaangulosconcretos
* https://www.geogebra.org/m/tezrgs9Z
*
* Calculates the Euclidean distance between 2 observations.
*
* For 2 Observation feature vectors A and B.
*
* - Similarity funct: - Range [-1, 1]. - Highier = Closer. This is what we want!!
*
* - DISTANCE fuct (): - Range [0, 1]. - Lower = Closer.
*
* For us to compute de DIST(), we first need to calculate the COSINE-SIMILARITY()
*/
public class CosineSimilarity implements Distance {
/**
* Calculates the cosine similarity between 2 observations.
* Numerator:
* For each feature, multiply the value of that feature in obsA with the value of that feature in obsB.
* We add those products together to get our numerator.
*
* Denominator:
* Squares each feature value in obsA, adds them together
* and, takes the square root .
* Does the same for obsB.
* Multiplies the 2 square roots together.
*
* @param featuresA
* @param featuresB
* @return The similarity between the 2 observations.
*/
public double cosineSimilarity(ArrayList<Double> featuresA, ArrayList<Double> featuresB) {
double product = 0.0;
double denom = 0.0;
double sqrA = 0.0;
double sqrB = 0.0;
double sol = 0.0;
for (int i = 0; i < featuresA.size(); i++) {
product += featuresA.get(i) * featuresB.get(i);
sqrA += Math.pow(featuresA.get(i), 2);
sqrB += Math.pow(featuresB.get(i), 2);
}
//if (sqrA == 0 && sqrB == 0) { return 2.0; }
denom = Math.sqrt(sqrA) * Math.sqrt(sqrB);
sol = product / denom;
return sol;
}
// Calculates the distance between 2 observations using their cosine similarity.
public double distance(ArrayList<Double> featuresA, ArrayList<Double> featuresB) {
double thecos = cosineSimilarity(featuresA, featuresB);
double numer = -1 * thecos + 1;
return numer / 2;
}
}
public class ManhattanDistance implements Distance {
public double distance(ArrayList<Double> featuresA, ArrayList<Double> featuresB){
double sum = 0;
for(int i = 0; i < featuresA.size(); i++)
sum += Math.abs(featuresA.get(i)-featuresB.get(i));
return sum;
}
}
/**
* Generate a list of observations from the data file.
*
* @param filename The name of the file to parse. Should have a header and be in
* comma separated value (CSV) format.
* @param hasLabel If true, the last column will be used as the label for each
* observation and all other columns will be features. If false,
* *all* columns will be used as features.
* @return The observations and header (column names).
* @throws IOException
*/
public Dataset parseDataFile(String filename, boolean hasLabel) throws IOException {
ArrayList<String> columnNames = new ArrayList<String>();
ArrayList<Observation> observations = new ArrayList<Observation>();
BufferedReader reader = new BufferedReader(new FileReader(filename));
for(String col : reader.readLine().split(",")){
columnNames.add(col);
}
while(reader.ready()){
String[] columns = reader.readLine().split(",");
ArrayList<Double> features = new ArrayList<Double>();
String label = null;
if(hasLabel){
for(int i = 0; i < columns.length-1; i++){
features.add(Double.parseDouble(columns[i]));
}
label = columns[columns.length-1];
} else {
for(int i = 0; i < columns.length; i++){
features.add(Double.parseDouble(columns[i]));
}
}
observations.add(new Observation(features, label));
}
reader.close();
return new Dataset(columnNames, observations);
}
/**
* Predict the label of newObservation based on the majority label among
* the k nearest observations in trainingSet.
*
* @param newObservation The observation to classify.
* @param trainingSet The set of observations to derive the label from.
* @param k The number of nearest neighbors to consider when determining the label.
* @param dist The distance function to use.
* @return The predicted label of newObservation.
*/
public Double classify(Observation newObs,
ArrayList<Observation> trainingSet, int k, Distance dist, String positiveClass) {
// the list of the distance from newObs to each of its k-neighbors.
ArrayList<Double> distancesList = new ArrayList<Double>();
ArrayList<String> labelsList = new ArrayList<String>();
HashMap<String, Integer> labelsDistSum = new HashMap<String, Integer>();
int maxDistIndex; // the position of the farther obs in the list of distances.
double maxDist; // is the largest distance that one of our neighbors has. I.e. The obs which is the farthest from newObs.
int totalCounts = 0;
int posCounts = 0;
// double sol = 0;
// we calculate the distance from newObs to EVERY single obs in the given dataset,
// and store k of them in 'distancesList'.
for (Observation observation : trainingSet) {
// for this 'observation'
Double distance = dist.distance(observation.features, newObs.features);
// if the list doesnt contain k neighbors in it:
if (distancesList.size() < k) {
// add the distance to this neighbor 'observation', to the list
distancesList.add(distance);
// and also add its corresponding label
labelsList.add(observation.label);
} else { // if we already have the list with k neighbors:
// Find the largest value in distancesList and it's corresponding index.
maxDistIndex = 0;
maxDist = distancesList.get(0); // we set it to the fisrt dist val as it is so far, the largest one seen.
// we start looping at 1 because we have already seen 0.
for (int i = 1; i < distancesList.size(); i++) {
if (distancesList.get(i) > maxDist) {
maxDist = distancesList.get(i);
maxDistIndex = i;
}
}
// Replace the largest distance with this one if this one is
// smaller.
// if the distance we just computed (between observation and newObs)
// is smaller than the largest distance that our list contains so far, replace it.
// Remember! We want the closest neighbors!
if (distance < maxDist) {
// .set(index, newVal) --> Replace the current value at 'index', with: 'newVal'.
// replace our current largest value (located at maxDistIndex) with this smaller distance value.
distancesList.set(maxDistIndex, distance);
// we find the item located at the same index, and we replace the label that was there, with this one.
labelsList.set(maxDistIndex, observation.label);
}
}
}
// -------------------------------------------------------------------------------------------------------------------------
//Now that we have located our k nearest neighbors and their corresponig labels:
//add all the distance values of the observations with posClass.
// add all the distance values of the observations with negativeClass.
//add them together to get the total distance.
// Add labels to the hash map.
for (String label : labelsList) {
// if the label has already been added as a key to the map:
if (labelsDistSum.containsKey(label)) {
// replace the old count for this label with oldCount+1.
labelsDistSum.put(label, labelsDistSum.get(label) + 1);
} else {
// if the label has neever been seen before, add it to the map and set the count
// to be 1.
labelsDistSum.put(label, 1);
}
}
for (String label : labelsDistSum.keySet()) {
totalCounts += labelsDistSum.get(label);
if (labelsDistSum.containsKey(positiveClass)) {
posCounts = labelsDistSum.get(positiveClass);
} else {
//If the class is not present, the confidence socre is null.
return 0.0;
}
}
Double totalAsDouble = Double.valueOf(totalCounts);
Double posCountsAsDouble = Double.valueOf(posCounts);
return posCountsAsDouble / totalAsDouble;
}
/**
* https://pdfs.semanticscholar.org/0318/f6c2c8928d3259cd8d65283901536cea9e33.pdf?_ga=2.140176563.1629213328.1588025057-1310319897.1581406461
*
* Predict the Confidence Score of newObservation belonging to the positive
* class based on the percentage of its k nearest observations in trainingSet.
* It outputs a Confidence Score that this observation is from the given
* positiveClass. The score computed, inticates the confidence that an
* observation belongs to the positive class.
*
* - if score is: - closer to 1 It means that, newObs is more likely to be from
* the positiveClass. - closer to 0 Means it is more likely for newObs to be
* from the negativeClass.
*
* ---- the confidence score (in terms of this distance measure) is the relative
* distance.
*
* For example, if sample S1 has a distance 80 to Class 1 and distance 120 to
* Class 2,
*
* - then it has (100-(80/200))%=60% confidence to be in Class 1 - and 40%
* confidence to be in Class 2.
*
* find its k nearest neighbors.
* find what their labels are.
* get the percentage of those neighbors that have the label=positiveClass.
*
* @param newObservation The observation to get the Confidence Score from.
* @param trainingSet The set of observations to derive the score from.
* @param k The number of nearest neighbors to consider when
* determining the score.
* @param dist The distance function to use.
* @param positiveClass The positive class to use.
* @return The percentage of newObservation's k newarest neighbors are labeled
* with the positiveClass.
public double confidenceScore(Observation newObservation, ArrayList<Observation> trainingSet, int k,
Distance dist, String positiveClass) {
return 0;
}
*/
public static void main(String[] args) throws IOException {
kNNPA4 knn = new kNNPA4();
String trainingFilename, testingFilename, distanceFunction, positiveClass;
int k;
Dataset trainData, testData;
Distance distance;
if(args.length < 5){
System.err.println(
"Usage: kNNPA4 <training file> <test file> <k> <distance "+
"function> <positive class>\n\n"+
"<distance function> must be one of:\n"+
" * euclidean\n"+
" * manhattan\n"+
" * cosine\n\n"+
"<positive class> must : \n"+
" * be a string\n"+
" * match exaclty 1 of the classes in the dataset.");
System.exit(1);
}
trainingFilename = args[0];
testingFilename = args[1];
k = Integer.parseInt(args[2]);
distanceFunction = args[3];
positiveClass = args[4];
distance = knn.new EuclideanDistance();
if(distanceFunction.equals("manhattan")){
distance = knn.new ManhattanDistance();
} else if (distanceFunction.equals("cosine")) {
distance = knn.new CosineSimilarity();
}
// - parse input files
trainData = knn.parseDataFile(trainingFilename, true);
testData = knn.parseDataFile(testingFilename, true);
// - run kNN
// - report the classifications
// * test file + one new column: predicted_label
//System.out.println(testData.columnNamesAsCSV() + ",predicted_label");
System.out.println(testData.columnNamesAsCSV() + ",predicted_positive");
for(Observation obs : testData.observations)
System.out.println(obs +","+ String.format("%.5f",
knn.classify(obs, trainData.observations, k, distance, positiveClass)));
}
}
/**
* Generate confidence scores which estimate the likelihood that a hypothesis(prediction) is
* correct.
* One approach:
– Find features correlated with correctness
– Construct feature vector from good features
– Build correct/incorrect classifier for feature vector.
Given a confidence feature vector we want to classify the vector
as correct or incorrect.
*
* The objective of the k-NN measures is: To assign higher confidence to
* those examples that are ‘close’ (i.e. with high similarity) to examples of
* its predicted class, and are ‘far’ (i.e. low similarity) from examples of a
* different class. The
*/ |
package com.frist_demo;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
public class MainPage {
private WebDriver driver;
private WebElement userMenu;
public MainPage(WebDriver dr){
this.driver=dr;
this.userMenu = driver.findElement(By.cssSelector("div#userMenu"));
}
public String getloginUserMenu(){
return userMenu.getText();
}
}
|
import java.util.*;
class dist
{
private int feet,inch;
void read(int f,int i)
{
feet=f;
inch=i;
if(inch>=12)
{
feet+=inch/12;
inch=inch%12;
}
}
void print()
{
System.out.println(feet+"'"+inch+"\"");
}
}
class distance
{
public static void main(String args[])
{
Scanner x=new Scanner(System.in);
System.out.print("Enter Dimonsen of object in feet:-");
int f=x.nextInt();
System.out.print("Enter Dimenson of object in inch:-");
int i=x.nextInt();
dist c=new dist();
c.print();
c.read(f,i);
c.print();
}
} |
package net.lantrack.framework.core.entity;
import java.io.Serializable;
/**
* 专门用来存放key-value的,一般给下拉,单选,复选框用
*
* @date 2019年3月7日
*/
public class MapEntity implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* key
*/
private String k;
/**
* value
*/
private String v;
public String getK() {
return k;
}
public void setK(String k) {
this.k = k;
}
public String getV() {
return v;
}
public void setV(String v) {
this.v = v;
}
}
|
package com.awakenguys.kmitl.ladkrabangcountry;
import com.awakenguys.kmitl.ladkrabangcountry.model.Announce;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import java.util.List;
@RepositoryRestResource(collectionResourceRel = "announces", path = "announces")
public interface AnnounceRepo extends MongoRepository<Announce, String> {
List<Announce> findById (@Param("id") String id);
}
|
package com.jxtb.test.controller;
import com.jxtb.test.entity.Test;
import com.jxtb.test.service.ISessionService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* User: Administrator
* Date: 17-3-24
* Time: 下午5:09
* To change this template use File | Settings | File Templates.
*/
@SuppressWarnings("ALL")
@Controller
@RequestMapping("session")
public class SessionController {
// 业务层
@Resource(name = "sessionService")
private ISessionService sessionService;
@RequestMapping("find")
public String find(HttpServletRequest request, HttpServletResponse response) throws ServletException {
List<Test> testList= sessionService.findAllTest();
Test test=sessionService.findTestById("5");
System.out.println("testList="+testList);
System.out.println("test="+test);
return "login";
}
@RequestMapping("add")
public String add(HttpServletRequest request, HttpServletResponse response) throws ServletException {
Test test=new Test();
test.setId("5");
test.setUserName("abc123");
test.setUserPsw("admin");
int result= sessionService.addAllTest(test);
System.out.println("result="+result);
return "login";
}
@RequestMapping("delete")
public String delete(HttpServletRequest request, HttpServletResponse response) throws ServletException {
Test test=sessionService.findTestById("5");
int result= sessionService.deleteAllTest(test);
System.out.println("result="+result);
return "login";
}
@RequestMapping("update")
public String update(HttpServletRequest request, HttpServletResponse response) throws ServletException {
Test test=sessionService.findTestById("5");
test.setUserName("mimimi");
test.setUserPsw("mimimi");
int result= sessionService.updateAllTest(test);
System.out.println("result="+result);
return "login";
}
}
|
package org.flowable.cloud.runtime.core.behavior.classdelegate;
import java.util.List;
import org.flowable.bpmn.model.MapExceptionEntry;
import org.flowable.cloud.runtime.core.utils.NameUtil;
import org.flowable.common.engine.api.delegate.Expression;
import org.flowable.engine.impl.bpmn.helper.ClassDelegate;
import org.flowable.engine.impl.bpmn.helper.DefaultClassDelegateFactory;
import org.flowable.engine.impl.bpmn.parser.FieldDeclaration;
import org.springframework.context.ApplicationContext;
/**
* @author chen.xing<br>
* @version 1.0<br>
* @Desc good study day day up
* @data 2019<br>
*/
public class CloudClassDelegateFactory extends DefaultClassDelegateFactory {
private ApplicationContext applicationContext;
private CloudClassDelegateServiceTaskStages taskStage;
public CloudClassDelegateFactory(ApplicationContext applicationContext, CloudClassDelegateServiceTaskStages taskStage) {
this.applicationContext = applicationContext;
this.taskStage = taskStage;
}
@Override
public ClassDelegate create(String id, String className, List<FieldDeclaration> fieldDeclarations, boolean triggerable, Expression skipExpression, List<MapExceptionEntry> mapExceptions) {
if (this.applicationContext.containsBean(NameUtil.getJavaDelegateBeanName(className))) {
return new CloudClassDelegateServiceTaskBehavior(taskStage, id, className, fieldDeclarations, triggerable, skipExpression, mapExceptions);
}
else {
return super.create(id, className, fieldDeclarations, triggerable, skipExpression, mapExceptions);
}
}
@Override
public ClassDelegate create(String className, List<FieldDeclaration> fieldDeclarations) {
if (this.applicationContext.containsBean(NameUtil.getJavaDelegateBeanName(className))) {
return new CloudClassDelegateServiceTaskBehavior(taskStage, className, fieldDeclarations);
}
else {
return super.create(className, fieldDeclarations);
}
}
}
|
package com.cpg.BankPro.dao;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import com.cpg.BankPro.dto.Customerpojo;
class CustomerDetailsImplTest {
Customerpojo pojo=new Customerpojo();
CustomerDetailsImpl dao=new CustomerDetailsImpl();
@Test
void testRegistration() {
pojo.setFirstName("pal");
pojo.setLastName("Buroju");
pojo.setEmailId("pal@");
pojo.setPassword("pallavi");
pojo.setPancardNo("20");
pojo.setAadharNo("987654321234");
pojo.setAddress("hyd");
pojo.setMobileNo("7382303065");
assertEquals(pojo,dao.registration(pojo));
}
@Test
void testLogin() {
//pojo.setAccountNo(74);
//pojo.setPassword("pallavi");
pojo=dao.login(1001, "123");
assertEquals(pojo,pojo);
}
}
|
package pages;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.support.ui.Select;
public class ManageSIUReferralUpdateScorePage extends BasePage {
private By SIUSummaryTextLocator = By.id("CLM_SC_BO_0008_SIUSummary_10a");
private By fraudSummaryTableRowsLocator = By.xpath("//*[@id='CLM_SC_BO_0016_FraudSummary']/tbody/tr[@id]");
private String fraudSummaryTableRowsLocatorString = "//*[@id='CLM_SC_BO_0016_FraudSummary']/tbody/tr[@id][<val>]";
private By SIUSelectedTableRowsLocator = By.xpath("//*[@id='CLM_SC_BO_0151_SIUSelected']/tbody/tr[@id]");
private String SIUSelectedTableRowsLocatorString = "//*[@id='CLM_SC_BO_0151_SIUSelected']/tbody/tr[@id][<val>]";
private By overrideReasonDdlLocator = By.id("CLM_SC_BO_0016_RemovalReason");
private By removeReasonBtnLocator = By.id("CLM_SC_BO_0151_RemoveButton");
private By activeSIURowsLocator = By.xpath("//*[@id='CLM_SC_BO_0151_SIUSelected']/tbody/tr[contains(td[@id='ReasonStatus'], 'Active')]");
private By activeSIUFirstRowLocator = By.xpath("//*[@id='CLM_SC_BO_0151_SIUSelected']/tbody/tr[contains(td[@id='ReasonStatus'], 'Active')][1]");
public String getSIUSummaryText() {
writeStepToTestNGReport("Capture SIU summary");
// Auto-generated method stub
String rtnSIUSummary = "";
try {
rtnSIUSummary = driver.get().findElement(SIUSummaryTextLocator).getText();
} catch (NoSuchElementException nsee) {
nsee.printStackTrace();
}
return rtnSIUSummary;
}
public int getFraudSummaryTableRowCount() {
writeStepToTestNGReport("Get Fraud Summary table row count");
// Auto-generated method stub
return driver.get().findElements(fraudSummaryTableRowsLocator).size();
}
public int getSIUSelectedTableRowCount() {
writeStepToTestNGReport("Get SIU Selected table row count");
// Auto-generated method stub
return driver.get().findElements(SIUSelectedTableRowsLocator).size();
}
public void closeAllSIUScores(String closeReason) {
writeStepToTestNGReport("Close all SIU scores");
// TODO Auto-generated method stub
int fraudSummaryTblRowCount = getFraudSummaryTableRowCount();
for (int i = 1; i <= fraudSummaryTblRowCount; i++) {
driver.get().findElement(By.xpath(fraudSummaryTableRowsLocatorString.replace("<val>", Integer.toString(i)))).click();
progressSync();
//int SIUSelectedTblRowCount = getSIUSelectedTableRowCount();
while (driver.get().findElements(activeSIURowsLocator).size() > 0) {
driver.get().findElement(activeSIUFirstRowLocator).click();
progressSync();
new Select(driver.get().findElement(overrideReasonDdlLocator)).selectByVisibleText(closeReason);
driver.get().findElement(removeReasonBtnLocator).click();
progressSync();
}
}
}
}
|
package com.ainory.kafka.streams.entity;
import com.ainory.kafka.streams.util.JsonUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import java.io.Serializable;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.DoubleSummaryStatistics;
import java.util.HashMap;
import java.util.LongSummaryStatistics;
/**
* @author ainory on 2018. 3. 20..
*/
public class HostMetricVO implements Serializable{
private final String DATE_FORMAT_COMMON = "yyyy-MM-dd HH:mm:ss";
private final DecimalFormat DECIMAL_FORMAT = new DecimalFormat("##0.00");
private String hostname;
private long startTimestamp = 0L;
private long endTimestamp = 0L;
private long summaryTimestamp = 0L;
private String startTimestampStr;
private String endTimestampStr;
private ArrayList<Double> cpu_list = new ArrayList<>();
private ArrayList<Long> memory_list = new ArrayList<>();
private double cpu_avg;
private double cpu_min;
private double cpu_max;
private double memory_avg;
private long memory_min;
private long memory_max;
public double interval;
public String getHostname() {
return hostname;
}
public void setHostname(String hostname) {
this.hostname = hostname;
}
public long getStartTimestamp() {
return startTimestamp;
}
public void setStartTimestamp(long startTimestamp) {
this.startTimestamp = startTimestamp;
this.startTimestampStr = DateFormatUtils.format(startTimestamp, DATE_FORMAT_COMMON);
}
public long getEndTimestamp() {
return endTimestamp;
}
public void setEndTimestamp(long endTimestamp) {
this.endTimestamp = endTimestamp;
this.endTimestampStr = DateFormatUtils.format(endTimestamp, DATE_FORMAT_COMMON);
}
public long getSummaryTimestamp() {
return summaryTimestamp;
}
public void setSummaryTimestamp(long summaryTimestamp) {
this.summaryTimestamp = summaryTimestamp;
}
public double getCpu_avg() {
return cpu_avg;
}
public void setCpu_avg(double cpu_avg) {
this.cpu_avg = cpu_avg;
}
public double getCpu_min() {
return cpu_min;
}
public void setCpu_min(double cpu_min) {
this.cpu_min = cpu_min;
}
public double getCpu_max() {
return cpu_max;
}
public void setCpu_max(double cpu_max) {
this.cpu_max = cpu_max;
}
public double getMemory_avg() {
return memory_avg;
}
public void setMemory_avg(double memory_avg) {
this.memory_avg = memory_avg;
}
public long getMemory_min() {
return memory_min;
}
public void setMemory_min(long memory_min) {
this.memory_min = memory_min;
}
public long getMemory_max() {
return memory_max;
}
public void setMemory_max(long memory_max) {
this.memory_max = memory_max;
}
public ArrayList<Double> getCpu_list() {
return cpu_list;
}
public void setCpu_list(ArrayList<Double> cpu_list) {
this.cpu_list = cpu_list;
}
public ArrayList<Long> getMemory_list() {
return memory_list;
}
public void setMemory_list(ArrayList<Long> memory_list) {
this.memory_list = memory_list;
}
public double getInterval() {
return interval;
}
public void setInterval(double interval) {
this.interval = interval;
}
public void cpu_calc(double val){
DoubleSummaryStatistics statistics = new DoubleSummaryStatistics();
cpu_list.add(val);
for(double cpu_val : cpu_list){
statistics.accept(cpu_val);
}
setCpu_avg(statistics.getAverage());
setCpu_min(statistics.getMin());
setCpu_max(statistics.getMax());
}
public void memory_calc(long val){
LongSummaryStatistics statistics = new LongSummaryStatistics();
memory_list.add(val);
for(long memory_val : memory_list){
statistics.accept(memory_val);
}
setMemory_avg(statistics.getAverage());
setMemory_min(statistics.getMin());
setMemory_max(statistics.getMax());
}
public String toCpuStatisticsCollectdJson(){
return toCollectdJsonString(hostname, "cpu", "percent", "cpu_idle", cpu_avg, cpu_min, cpu_max, interval, System.currentTimeMillis());
}
public String toMemoryStatisticsCollectdJson(){
return toCollectdJsonString(hostname, "memory", "memory", "used", memory_avg, memory_min, memory_max, interval, System.currentTimeMillis());
}
private String toCollectdJsonString(String host, String plugin, String type, String type_instance, Number avg_value, Number min_value, Number max_value, double interval, long time){
ArrayList<CollectdKafkaVO> list = new ArrayList<>();
CollectdKafkaVO collectdKafkaVO = setCollectdKafkaVO(host, plugin, type, type_instance, interval, time);
collectdKafkaVO.setType_instance(type_instance+"_avg");
if(StringUtils.equals(plugin, "memory")){
collectdKafkaVO.setValues(new ArrayList<Long>(){{add(avg_value.longValue());}});
}else{
collectdKafkaVO.setValues(new ArrayList<Double>(){{add(avg_value.doubleValue());}});
}
list.add(collectdKafkaVO);
collectdKafkaVO = setCollectdKafkaVO(host, plugin, type, type_instance, interval, time);
collectdKafkaVO.setType_instance(type_instance+"_min");
if(StringUtils.equals(plugin, "memory")){
collectdKafkaVO.setValues(new ArrayList<Long>(){{add(min_value.longValue());}});
}else{
collectdKafkaVO.setValues(new ArrayList<Double>(){{add(min_value.doubleValue());}});
}
list.add(collectdKafkaVO);
collectdKafkaVO = setCollectdKafkaVO(host, plugin, type, type_instance, interval, time);
collectdKafkaVO.setType_instance(type_instance+"_max");
if(StringUtils.equals(plugin, "memory")){
collectdKafkaVO.setValues(new ArrayList<Long>(){{add(max_value.longValue());}});
}else{
collectdKafkaVO.setValues(new ArrayList<Double>(){{add(max_value.doubleValue());}});
}
list.add(collectdKafkaVO);
return JsonUtil.objectToJsonString(list);
}
private CollectdKafkaVO setCollectdKafkaVO(String host, String plugin, String type, String type_instance, double interval, long time){
CollectdKafkaVO collectdKafkaVO = new CollectdKafkaVO();
collectdKafkaVO.setHost(host);
collectdKafkaVO.setDsnames(new ArrayList<String>(){{add("value");}});
collectdKafkaVO.setDstypes(new ArrayList<String>(){{add("gauge");}});
collectdKafkaVO.setTime(String.valueOf(time));
collectdKafkaVO.setInterval(interval);
collectdKafkaVO.setPlugin(plugin);
collectdKafkaVO.setPlugin_instance("");
collectdKafkaVO.setType(type);
collectdKafkaVO.setMeta(new HashMap<String,Boolean>(){{put("network: received", true);}});
return collectdKafkaVO;
}
@Override
public String toString() {
final StringBuffer sb = new StringBuffer();
sb.append("hostname='").append(hostname).append('\'');
sb.append(", startTimestamp=").append(startTimestamp);
sb.append(", endTimestamp=").append(endTimestamp);
sb.append(", startTimestampStr=").append(startTimestampStr);
sb.append(", endTimestampStr=").append(endTimestampStr);
// sb.append(", cpu_list=").append(cpu_list);
// sb.append(", memory_list=").append(memory_list);
sb.append(", cpu_avg=").append(DECIMAL_FORMAT.format(cpu_avg));
sb.append(", cpu_min=").append(DECIMAL_FORMAT.format(cpu_min));
sb.append(", cpu_max=").append(DECIMAL_FORMAT.format(cpu_max));
sb.append(", memory_avg=").append(DECIMAL_FORMAT.format(memory_avg));
sb.append(", memory_min=").append(memory_min);
sb.append(", memory_max=").append(memory_max);
return sb.toString();
}
public static void main(String[] args) {
HostMetricVO hostMetricVO = new HostMetricVO();
System.out.println(hostMetricVO.toCollectdJsonString("spanal-app", "cpu", "percent", "cpu_idle", 90.00, 89.00, 91.00, 900, System.currentTimeMillis()));
}
}
|
package Problem_1074;
import java.util.Scanner;
public class Main {
static int N, r, c;
public static int pow2(int x) {
return 1<<x;
}
public static int answer(int n, int x, int y) {
if(n == 1) return 2*x+y;
else {
if(x < pow2(n-1)) {
if( y < pow2(n-1)) {
return answer(n-1, x, y);
} else {
return answer(n-1, x, y - pow2(n-1)) + pow2(2*n-2);
}
}
else {
if( y < pow2(n-1)) {
return answer(n-1, x - pow2(n-1), y) + 2*pow2(2*n-2);
} else {
return answer(n-1, x - pow2(n-1), y - pow2(n-1)) + 3*pow2(2*n-2);
}
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
N = sc.nextInt();
r = sc.nextInt();
c = sc.nextInt();
System.out.println(answer(N,r,c));
}
}
|
package com.leviathan143.craftingutils.client.gui.ingredientList;
import java.io.IOException;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.item.ItemStack;
import org.lwjgl.input.Keyboard;
import com.leviathan143.craftingutils.common.container.DummyContainer;
import com.leviathan143.craftingutils.common.jei.CraftingUtilsPlugin;
public class GuiSelectOutput extends GuiContainer
{
private Minecraft mc;
public GuiSelectOutput(Minecraft minecraft)
{
super(new DummyContainer());
mc = minecraft;
}
@Override
public void initGui()
{
xSize = 176;
guiLeft = (this.width - xSize) / 2;
}
@Override
public boolean doesGuiPauseGame()
{
return false;
}
@Override
protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY)
{
mc.fontRendererObj.drawString("Hover over the desired"
, 0, (this.height / 2) - 5, 0xFF0000);
mc.fontRendererObj.drawString("output item, and left click"
, 0, (this.height / 2) + 5, 0xFF0000);
}
@Override
protected void drawGuiContainerBackgroundLayer(float partialTicks,
int mouseX, int mouseY) {}
@Override
protected void mouseClicked(int mouseX, int mouseY, int mouseButton) throws IOException
{
}
}
|
package io.breen.socrates.test.logicly;
import java.util.UUID;
public abstract class Evaluatable extends LogiclyObject {
public final Evaluatable inputs[];
public final Evaluatable outputs[];
public Evaluatable(UUID uuid, int numInputs, int numOutputs) {
super(uuid);
this.inputs = new Evaluatable[numInputs];
this.outputs = new Evaluatable[numOutputs];
}
/**
* @return an array of Boolean values describing the output of this Evaluatable, precisely the
* same size as this object's outputs array
*
* @throws UndeterminedStateException
*/
public abstract boolean[] evaluate() throws UndeterminedStateException;
}
|
public class Library {
private double runTime;
private int songs;
private Album[] albums;
public Library() {
albums = new Album[10];
runTime = 0;
songs = 0;
}
public void update(){
runTime = 0;
songs = 0;
for (Album val : albums){
if (val != null){
runTime += val.getPlayTime();
songs += val.getTracks();
}
}
}
public boolean add(Album a1) {
boolean a = false;
boolean b = true;
for (int i = 0; i < albums.length; i++) {
if (albums[i] == null) {
albums[i] = a1;
this.update();
return true;
}
}
return false;
}
public void remove(int index) {
for (int i = 0; i < albums.length; i++) {
if (i == index) {
albums[i] = null; //Setting album to null basically to remove it
this.update();
}
}
}
public void Double(){
Album[] reset = new Album[albums.length * 2];
for (int i = 0 ; i < albums.length ; i++){
reset[i] = albums[i];
}
albums = reset;
this.update();
}
public int findTitle(String title){
for (int i = 0; i < albums.length; i++) {
if (albums[i] != null && albums[i].getTitle().equals(title)){
return i;
}
else{
return -1;
}
}
return -1;
}
public int findArtist(String artist){
for (int i = 0; i < albums.length; i++) {
if (albums[i] != null && albums[i].getArtist().equals(artist)){
return i;
}
else{
return -1;
}
}
return -1;
}
public Album getAlbum(int index){
if (index >= 0 && index < albums.length){
return albums[index];
}
else{
System.out.println("Index out of bounds");
return null;
}
}
public String toString(){
String toString = "";
for (Album a : albums){
if (a != null){
toString += a.toString() + "\n";
}
}
this.update();
return toString + "total play time: " + runTime + " and number of songs is " + songs;
}
public void sortByTitle(){
Album temp;
int min;
for (int i = 0 ; i < albums.length - 1 ; i++){
min = i;
for (int scan = i + 1; scan < albums.length ; scan++) {
if (albums[scan] != null && albums[i] != null){
if (albums[scan].getTitle().compareTo(albums[min].getTitle()) < 0){
min = scan;
}
}
}
temp = albums[min];
albums[min] = albums[i];
albums[i] = temp;
}
}
public void sortByArtist(){
for (int i = 1; i < albums.length; i++) {
Album key = albums[i];
int position = i;
while (position > 0 && albums[position - 1] != null && key != null && albums[position - 1].getArtist().compareTo(key.getArtist()) > 0 ){
albums[position] = albums[position - 1];
position--;
}
albums[position] = key;
}
}
public int binarySearchArtist(String target){
int low = 0;
int high = albums.length - 1;
int middle = (low + high) / 2;
while (!albums[middle].getArtist().equals(target) && low <= high ){
if (target.compareTo(albums[middle].getArtist()) < 0){
high = middle - 1;
}
else{
low = middle + 1;
}
middle = (low + high) / 2;
}
if (albums[middle].getArtist().equals(target)){
return middle;
}
else{
return -1;
}
}
public int binarySearchTitle(String target){
int low = 0;
int high = albums.length - 1;
int middle = (low + high) / 2;
while (!albums[middle].getTitle().equals(target) && low <= high ){
if (target.compareTo(albums[middle].getTitle()) < 0){
high = middle - 1;
}
else{
low = middle + 1;
}
middle = (low + high) / 2;
}
if (albums[middle].getTitle().equals(target)){
return middle;
}
else{
return -1;
}
}
}
|
/*
* Copyright 2002-2019 the original author or authors.
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.context.junit4.spr9051;
import javax.sql.DataSource;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.testfixture.beans.Employee;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.annotation.DirtiesContext.ClassMode;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.AfterTransaction;
import org.springframework.test.context.transaction.BeforeTransaction;
import org.springframework.transaction.annotation.Transactional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.transaction.TransactionAssert.assertThatTransaction;
import static org.springframework.transaction.support.TransactionSynchronizationManager.isActualTransactionActive;
/**
* This set of tests (i.e., all concrete subclasses) investigates the claims made in
* <a href="https://jira.spring.io/browse/SPR-9051" target="_blank">SPR-9051</a>
* with regard to transactional tests.
*
* @author Sam Brannen
* @since 3.2
* @see org.springframework.test.context.testng.AnnotationConfigTransactionalTestNGSpringContextTests
*/
@RunWith(SpringJUnit4ClassRunner.class)
@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD)
public abstract class AbstractTransactionalAnnotatedConfigClassTests {
protected static final String JANE = "jane";
protected static final String SUE = "sue";
protected static final String YODA = "yoda";
protected DataSource dataSourceFromTxManager;
protected DataSource dataSourceViaInjection;
protected JdbcTemplate jdbcTemplate;
@Autowired
private Employee employee;
@Autowired
public void setTransactionManager(DataSourceTransactionManager transactionManager) {
this.dataSourceFromTxManager = transactionManager.getDataSource();
}
@Autowired
public void setDataSource(DataSource dataSource) {
this.dataSourceViaInjection = dataSource;
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
private int countRowsInTable(String tableName) {
return jdbcTemplate.queryForObject("SELECT COUNT(0) FROM " + tableName, Integer.class);
}
private int createPerson(String name) {
return jdbcTemplate.update("INSERT INTO person VALUES(?)", name);
}
protected int deletePerson(String name) {
return jdbcTemplate.update("DELETE FROM person WHERE name=?", name);
}
protected void assertNumRowsInPersonTable(int expectedNumRows, String testState) {
assertThat(countRowsInTable("person")).as("the number of rows in the person table (" + testState + ").").isEqualTo(expectedNumRows);
}
protected void assertAddPerson(final String name) {
assertThat(createPerson(name)).as("Adding '" + name + "'").isEqualTo(1);
}
@Test
public void autowiringFromConfigClass() {
assertThat(employee).as("The employee should have been autowired.").isNotNull();
assertThat(employee.getName()).isEqualTo("John Smith");
}
@BeforeTransaction
public void beforeTransaction() {
assertNumRowsInPersonTable(0, "before a transactional test method");
assertAddPerson(YODA);
}
@Before
public void setUp() throws Exception {
assertNumRowsInPersonTable((isActualTransactionActive() ? 1 : 0), "before a test method");
}
@Test
@Transactional
public void modifyTestDataWithinTransaction() {
assertThatTransaction().isActive();
assertAddPerson(JANE);
assertAddPerson(SUE);
assertNumRowsInPersonTable(3, "in modifyTestDataWithinTransaction()");
}
@After
public void tearDown() throws Exception {
assertNumRowsInPersonTable((isActualTransactionActive() ? 3 : 0), "after a test method");
}
@AfterTransaction
public void afterTransaction() {
assertThat(deletePerson(YODA)).as("Deleting yoda").isEqualTo(1);
assertNumRowsInPersonTable(0, "after a transactional test method");
}
}
|
// this is a placeholder/stub class
public class Range {
private String literal;
public Range(String literal) {
this.literal = literal;
}
}
|
/**
*
*/
package org.qsos.test;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import org.qsos.utils.ILibQSOS;
import org.qsos.utils.LibQSOS;
import org.qsos.utils.SimpleMenuEntry;
import junit.framework.TestCase;
/**
* @author Arthur Clerfeuille <arthur.clerfeuille@atosorigin.com>
*
*/
public class LibQSOSTest extends TestCase {
private ILibQSOS lib;
public void testGet() throws MalformedURLException{
/*Creation of the lib which allow to manipulate datas*/
lib = new LibQSOS();
/*Instanciation with a sheet*/
lib.load(new URL("http://cvs.savannah.gnu.org/viewcvs/*checkout*/qsos/qsos/sheet/groupware/kolab/kolab.qsos"));
/* Check of datas */
assertEquals("language",lib.getLanguage(),"en");
assertEquals("appname",lib.getAppname(),"kolab");
assertEquals("release",lib.getRelease(),"2");
assertEquals("licenseid",lib.getLicenseId(),"31");
assertEquals("licensedesc",lib.getLicenseDesc(),"GNU General Public License");
assertEquals("url",lib.getUrl(),"http://www.kolab.org");
assertEquals("des",lib.getDesc(),"Kolab is a groupware used in the german administration");
assertEquals("demourl",lib.getDemoUrl(),"http://kolab.org/screenshots.html");
assertEquals("qsosformat",lib.getQsosformat(),"1");
assertEquals("qsosappfamily",lib.getQsosappfamily(),"groupware");
assertEquals("qsosappname",lib.getQsosappname(),"kolab");
assertEquals("qsosspecificformat",lib.getQsosspecificformat(),"1");
System.out.println(lib.getAuthors());
/*Search by name on an element */
assertEquals("Desc0","Very few users identified",lib.getDescByName("popularity",0));
assertEquals("Desc1","Detectable use on Internet",lib.getDescByName("popularity",1));
assertEquals("Desc2","Numerous users, numerous references",lib.getDescByName("popularity",2));
assertEquals("Score","2",lib.getScoreByName("popularity"));
}
public void testSet() throws MalformedURLException{
/*Creation*/
lib = new LibQSOS();
/*Instanciation with a template*/
lib.load(new URL("http://cvs.savannah.gnu.org/viewcvs/*checkout*/qsos/qsos/sheet/groupware/template/groupware.qsos"));
/*Adding datas in the header*/
lib.setLanguage("en");
lib.setAppname("kolab");
lib.setRelease("2.1");
lib.setLicenseId("31");
lib.setLicenseDesc("GNU General Public License");
lib.setUrl("http://www.kolab.org");
lib.setDesc("Kolab is a groupware used in the german administration");
lib.setDemoUrl("http://kolab.org/screenshots.html");
lib.setQsosformat("1");
lib.setQsosappfamily("groupware");
lib.setQsosappname("kolab");
lib.setQsosspecificformat("1");
lib.addAuthor("Gonéri Le Bouder","goneri.lebouder@atosorigin.com");
/* Adding data in the sections but won't work till the update of the template*/
lib.setScoreByName("age","2");
lib.setCommentByName("age","Kolab.org domain was created the 29th of Oct 2002");
/* Getting a tree view of the file */
List<SimpleMenuEntry> list = lib.getSimpleTree();
System.out.println(lib.Debugaffichage(list));
/* Writing the file */
lib.write("test/testKolabCreation.xml");
}
}
|
package ecommercseSite.PageObject;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
public class MyAccountPage {
public WebDriver driver;
@FindBy(xpath = "//*[@href='http://automationpractice.com/index.php?mylogout=']")
public WebElement logoutBtn;
public MyAccountPage(WebDriver remoteDriver) {
this.driver = remoteDriver;
}
public void clickLogoutBtn() {
logoutBtn.click();
}
}
|
package Recursion;
import java.util.Scanner;
public class Nto1 {
static void print(int n){
System.out.println(n);
if(n>1)
print(n-1);
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter the value of n");
int n = in.nextInt();
print(n);
in.close();
}
}
|
package by.realovka.diploma.repository;
import by.realovka.diploma.entity.Like;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface LikeRepository extends JpaRepository<Like, Long> {
List<Like> findByPostId(long id);
}
|
package com.example.ComputerOnline.Buyers;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.example.ComputerOnline.Prevalent.Prevalent;
import com.example.ComputerOnline.R;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
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 java.util.HashMap;
public class ResetPasswordActivity extends AppCompatActivity {
private String check = "";
private TextView pageTitle, titleQuestions;
private EditText phoneNumber,question1, question2;
private Button verifyButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_reset_password );
check = getIntent().getStringExtra( "check" );
pageTitle = findViewById( R.id.page_title );
titleQuestions = findViewById( R.id.title_questions );
phoneNumber = findViewById( R.id.find_phone_number );
question1 = findViewById( R.id.question_1 );
question2 = findViewById( R.id.question_2);
verifyButton = findViewById( R.id.verify_btn );
verifyButton.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick(View view) {
verifyUser();
}
} );
}
@Override
protected void onStart(){
super.onStart();
phoneNumber.setVisibility( View.GONE );
if(check.equals( "settings" ))
{
pageTitle.setText( "Đặt câu hỏi" );
titleQuestions.setText( "Vui lòng đặt câu trả lời" );
verifyButton.setText( "Đặt" );
displayPreviousAnswers();
verifyButton.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick(View view) {
setAnswers();
}
} );
}
else if(check.equals( "login" ))
{
phoneNumber.setVisibility( View.VISIBLE );
verifyButton.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick(View view) {
verifyUser();
}
} );
}
}
private void setAnswers(){
String answer1 = question1.getText().toString().toLowerCase();
String answer2 = question2.getText().toString().toLowerCase();
if(question1.equals("") && question2.equals( "" ))
{
Toast.makeText( ResetPasswordActivity.this, "Vui lòng trả lời cả hai câu", Toast.LENGTH_SHORT ).show();
}
else
{
DatabaseReference ref = FirebaseDatabase.getInstance()
.getReference()
.child( "Users" )
.child( Prevalent.currentOnlineUser.getPhone() );
final HashMap<String, Object> userdataMap = new HashMap<>();
userdataMap.put("answer1", answer1);
userdataMap.put("answer2", answer2);
ref.child("Security Questions").updateChildren( userdataMap ).addOnCompleteListener( new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if(task.isSuccessful())
{
Toast.makeText( ResetPasswordActivity.this, "Ban da co cau hoi bao mat!!", Toast.LENGTH_SHORT ).show();
Intent intent = new Intent(ResetPasswordActivity.this, SettinsActivity.class);
startActivity(intent);
}
}
} );
}
}
private void displayPreviousAnswers(){
DatabaseReference ref = FirebaseDatabase.getInstance()
.getReference()
.child( "Users" )
.child( Prevalent.currentOnlineUser.getPhone() );
ref.child( "Security Questions" ).addValueEventListener( new ValueEventListener() {
@Override
public void onDataChange( DataSnapshot dataSnapshot) {
if(dataSnapshot.child( "Users" ).exists()){
String ans1 = dataSnapshot.child( "Sercurity Questions" ).child( "Answer1" ).getValue() .toString();
String ans2 = dataSnapshot.child( "Sercurity Questions" ).child( "Answer2" ).getValue() .toString();
question1.setText( ans1 );
question2.setText( ans2 );
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
} );
}
private void verifyUser()
{
final String phone = phoneNumber.getText().toString();
final String answer1 = question1.getText().toString().toLowerCase();
final String answer2 = question2.getText().toString().toLowerCase();
final DatabaseReference ref = FirebaseDatabase.getInstance()
.getReference()
.child( "Users" )
.child( Prevalent.currentOnlineUser.getPhone() );
ref.addValueEventListener( new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String mPhone = dataSnapshot.child( "phone" ).getValue().toString();
if(phone.equals( mPhone ) || phone.equals(Prevalent.currentOnlineUser.getPhone() ))
{
if(dataSnapshot.hasChild( "Security Questions" ))
{
String ans1 = dataSnapshot.child("Security Questions").child( "answer1" ).getValue().toString();
String ans2 = dataSnapshot.child("Security Questions").child( "answer2" ).getValue().toString();
if(!ans1.equals( answer1 ))
{
Toast.makeText( ResetPasswordActivity.this, "", Toast.LENGTH_SHORT ).show();
}
else if(!ans2.equals( answer2 ))
{
Toast.makeText( ResetPasswordActivity.this, "", Toast.LENGTH_SHORT ).show();
}
else
{
AlertDialog.Builder builder = new AlertDialog.Builder( ResetPasswordActivity.this );
builder.setTitle( "New Password" );
final EditText newPassword = new EditText( ResetPasswordActivity.this );
newPassword.setHint( "Điền mật khẩu tại đây" );
builder.setView( newPassword );
builder.setPositiveButton( "Change", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if(!newPassword.getText().toString().equals( ""))
{
ref.child( "password" )
.setValue( newPassword.getText().toString() )
.addOnCompleteListener( new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText( ResetPasswordActivity.this, "Đổi mật khẩu thành công", Toast.LENGTH_SHORT ).show();
}
}
} );
}
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int which) {
dialogInterface.cancel();
}
});
builder.show();
}
}
else
{
Toast.makeText(ResetPasswordActivity.this, "Vui long điền câu hỏi bảo mật", Toast.LENGTH_SHORT).show();
}
}
else
{
Toast.makeText(ResetPasswordActivity.this, "Số điện thoại không tồn tại", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
} );
}
}
|
package com.test;
import org.junit.Test;
/**
* @Description: Class类
* @auther: LB 2018/9/19 09:37
* @modify: LB 2018/9/19 09:37
*/
public class ClassTest {
@Test
public void classtest(){
System.out.printf(ClassTest.class+"");
System.out.printf(ClassTest.class.equals(new ClassTest().getClass())+"is");
}
}
|
/*
* Copyright 2002-2021 the original author or authors.
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jmx.support;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.management.MBeanServerConnection;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import org.springframework.aop.TargetSource;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.target.AbstractLazyCreationTargetSource;
import org.springframework.beans.factory.BeanClassLoaderAware;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.CollectionUtils;
/**
* {@link FactoryBean} that creates a JMX 1.2 {@code MBeanServerConnection}
* to a remote {@code MBeanServer} exposed via a {@code JMXServerConnector}.
* Exposes the {@code MBeanServer} for bean references.
*
* @author Rob Harrop
* @author Juergen Hoeller
* @since 1.2
* @see MBeanServerFactoryBean
* @see ConnectorServerFactoryBean
* @see org.springframework.jmx.access.MBeanClientInterceptor#setServer
* @see org.springframework.jmx.access.NotificationListenerRegistrar#setServer
*/
public class MBeanServerConnectionFactoryBean
implements FactoryBean<MBeanServerConnection>, BeanClassLoaderAware, InitializingBean, DisposableBean {
@Nullable
private JMXServiceURL serviceUrl;
private final Map<String, Object> environment = new HashMap<>();
private boolean connectOnStartup = true;
@Nullable
private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader();
@Nullable
private JMXConnector connector;
@Nullable
private MBeanServerConnection connection;
@Nullable
private JMXConnectorLazyInitTargetSource connectorTargetSource;
/**
* Set the service URL of the remote {@code MBeanServer}.
*/
public void setServiceUrl(String url) throws MalformedURLException {
this.serviceUrl = new JMXServiceURL(url);
}
/**
* Set the environment properties used to construct the {@code JMXConnector}
* as {@code java.util.Properties} (String key/value pairs).
*/
public void setEnvironment(Properties environment) {
CollectionUtils.mergePropertiesIntoMap(environment, this.environment);
}
/**
* Set the environment properties used to construct the {@code JMXConnector}
* as a {@code Map} of String keys and arbitrary Object values.
*/
public void setEnvironmentMap(@Nullable Map<String, ?> environment) {
if (environment != null) {
this.environment.putAll(environment);
}
}
/**
* Set whether to connect to the server on startup.
* <p>Default is {@code true}.
* <p>Can be turned off to allow for late start of the JMX server.
* In this case, the JMX connector will be fetched on first access.
*/
public void setConnectOnStartup(boolean connectOnStartup) {
this.connectOnStartup = connectOnStartup;
}
@Override
public void setBeanClassLoader(ClassLoader classLoader) {
this.beanClassLoader = classLoader;
}
/**
* Creates a {@code JMXConnector} for the given settings
* and exposes the associated {@code MBeanServerConnection}.
*/
@Override
public void afterPropertiesSet() throws IOException {
if (this.serviceUrl == null) {
throw new IllegalArgumentException("Property 'serviceUrl' is required");
}
if (this.connectOnStartup) {
connect();
}
else {
createLazyConnection();
}
}
/**
* Connects to the remote {@code MBeanServer} using the configured service URL and
* environment properties.
*/
private void connect() throws IOException {
Assert.state(this.serviceUrl != null, "No JMXServiceURL set");
this.connector = JMXConnectorFactory.connect(this.serviceUrl, this.environment);
this.connection = this.connector.getMBeanServerConnection();
}
/**
* Creates lazy proxies for the {@code JMXConnector} and {@code MBeanServerConnection}.
*/
private void createLazyConnection() {
this.connectorTargetSource = new JMXConnectorLazyInitTargetSource();
TargetSource connectionTargetSource = new MBeanServerConnectionLazyInitTargetSource();
this.connector = (JMXConnector)
new ProxyFactory(JMXConnector.class, this.connectorTargetSource).getProxy(this.beanClassLoader);
this.connection = (MBeanServerConnection)
new ProxyFactory(MBeanServerConnection.class, connectionTargetSource).getProxy(this.beanClassLoader);
}
@Override
@Nullable
public MBeanServerConnection getObject() {
return this.connection;
}
@Override
public Class<? extends MBeanServerConnection> getObjectType() {
return (this.connection != null ? this.connection.getClass() : MBeanServerConnection.class);
}
@Override
public boolean isSingleton() {
return true;
}
/**
* Closes the underlying {@code JMXConnector}.
*/
@Override
public void destroy() throws IOException {
if (this.connector != null &&
(this.connectorTargetSource == null || this.connectorTargetSource.isInitialized())) {
this.connector.close();
}
}
/**
* Lazily creates a {@code JMXConnector} using the configured service URL
* and environment properties.
* @see MBeanServerConnectionFactoryBean#setServiceUrl(String)
* @see MBeanServerConnectionFactoryBean#setEnvironment(java.util.Properties)
*/
private class JMXConnectorLazyInitTargetSource extends AbstractLazyCreationTargetSource {
@Override
protected Object createObject() throws Exception {
Assert.state(serviceUrl != null, "No JMXServiceURL set");
return JMXConnectorFactory.connect(serviceUrl, environment);
}
@Override
public Class<?> getTargetClass() {
return JMXConnector.class;
}
}
/**
* Lazily creates an {@code MBeanServerConnection}.
*/
private class MBeanServerConnectionLazyInitTargetSource extends AbstractLazyCreationTargetSource {
@Override
protected Object createObject() throws Exception {
Assert.state(connector != null, "JMXConnector not initialized");
return connector.getMBeanServerConnection();
}
@Override
public Class<?> getTargetClass() {
return MBeanServerConnection.class;
}
}
}
|
package dk.jrpe.monitor.db.datasource.inmemory;
import dk.jrpe.monitor.db.inmemory.httpaccess.InMemoryDataBase;
import dk.jrpe.monitor.db.datasource.HttpAccessDataSource;
import dk.jrpe.monitor.db.httpaccess.to.HTTPAccessTO;
import java.util.List;
/**
* Data source for the in memory database.
* @author Jörgen Persson
*/
public class InMemoryDataSource implements HttpAccessDataSource {
private final InMemoryDataBase dataBase = InMemoryDataBase.getInstance();
@Override public List<HTTPAccessTO> getHttpSuccess() {
return this.dataBase.getHttpSuccess();
}
@Override public List<HTTPAccessTO> getHttpFailed() {
return this.dataBase.getHttpFailed();
}
@Override public List<HTTPAccessTO> getHttpSuccessPerMinute(String date, String from, String to) {
return this.dataBase.getHttpSuccessPerMinute(date, from, to);
}
@Override public List<HTTPAccessTO> getHttpFailedPerMinute(String date, String from, String to) {
return this.dataBase.getHttpFailedPerMinute(date, from, to);
}
@Override public void saveHttpAccess(HTTPAccessTO to, int hour) {
// Not used
}
@Override public void updateHttpSuccess(HTTPAccessTO to) {
this.dataBase.updateHttpSuccess(to);
}
@Override public void updateHttpSuccessPerMinute(HTTPAccessTO to) {
this.dataBase.updateHttpSuccessPerMinute(to);
}
@Override public void updateHttpFailed(HTTPAccessTO to) {
this.dataBase.updateHttpFailed(to);
}
@Override public void updateHttpFailedPerMinute(HTTPAccessTO to) {
this.dataBase.updateHttpFailedPerMinute(to);
}
@Override public void open() {
// NOT USED
}
@Override public void close() throws Exception {
// NOT USED
}
@Override public void clear() {
this.dataBase.clear();
}
}
|
package com.project.daicuongbachkhoa;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import com.project.daicuongbachkhoa.R;
import com.project.daicuongbachkhoa.account.LoginUser;
import com.project.daicuongbachkhoa.landingpage.LandingPage;
import com.project.daicuongbachkhoa.landingpage.Notification;
import com.project.daicuongbachkhoa.menubar.MenuBar;
import com.project.daicuongbachkhoa.student.physicsonestudent.OptionPhysicsOneStudent;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// xử lý hoạt hoạ
setContentView(R.layout.activity_main);
/* Thread opening = new Thread() {
public void run() {
try {
sleep(1);
} catch (Exception e) {
} finally {
Intent intent = new Intent(MainActivity.this, LoginUser.class);
startActivity(intent);
}
}
};
opening.start();*/
//Intent intent = new Intent(this, LoginUser.class);
Intent intent = new Intent(this, LoginUser.class);
startActivity(intent);
// finish();// để không ngược lại !
}
@Override
protected void onPause() {
super.onPause();
finish();// xong !
}
} |
import java.awt.*;
import java.awt.event.*;
class AEvent extends Frame implements ActionListener{
TextField tf;
AEvent(){
//create components
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click to check Even Handling");
b.setBounds(30,120,250,30);
//register listener
b.addActionListener(this);//passing current instance
//add components and set size, layout and visibility
add(b);
add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
tf.setText("Dasa Sathyan");
}
public static void main(String args[]){
new AEvent();
}
}
|
package task;
import java.io.Serializable;
import java.util.Arrays;
/**
* Created by kleba on 15.03.2018.
*/
public class Line implements Serializable {
private Point pointFirst;
private Point pointSecond;
public Line(Point pointsFirst,Point pointSecond) {
this.pointFirst=pointsFirst;
this.pointSecond=pointSecond;
}
public void setPointFirst(Point pointFirst) {
this.pointFirst = pointFirst;
}
public Point getPointFirst() {
return pointFirst;
}
public void setPointSecond(Point pointSecond) {
this.pointSecond = pointSecond;
}
public Point getPointSecond() {
return pointSecond;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[");
sb.append(pointFirst);
sb.append("\t");
sb.append(pointSecond);
sb.append("]");
sb.append("\n");
return sb.toString();
}
}
|
/*
* Copyright 2015 Benedikt Ritter
*
* 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.github.britter.springbootherokudemo;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.validation.Valid;
import java.util.List;
@Controller
@RequestMapping("/")
public class HomeController {
private RecordRepository repository;
@Autowired
public HomeController(RecordRepository repository) {
this.repository = repository;
}
@RequestMapping(method = RequestMethod.GET)
@ApiOperation(value = "getRecords", nickname = "get Records")
@ApiImplicitParams({
@ApiImplicitParam(name = "model", value = "User's name", required = true, dataType = "string", paramType = "query", defaultValue="Niklas")
})
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Success", response = String.class),
@ApiResponse(code = 401, message = "Unauthorized"),
@ApiResponse(code = 403, message = "Forbidden"),
@ApiResponse(code = 404, message = "Not Found"),
@ApiResponse(code = 500, message = "Failure")})
public String home(ModelMap model) {
List<Record> records = repository.findAll();
model.addAttribute("records", records);
model.addAttribute("insertRecord", new Record());
return "home";
}
@RequestMapping(method = RequestMethod.POST)
public String insertData(ModelMap model,
@ModelAttribute("insertRecord") @Valid Record record,
BindingResult result) {
if (!result.hasErrors()) {
repository.save(record);
}
return home(model);
}
}
|
/*
* 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 colorselector;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Slider;
import javafx.scene.text.Text;
import javafx.scene.layout.VBox;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.stage.Stage;
import javafx.scene.paint.Color;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Font;
/**
*
* @author emwhfm
*/
public class ColorSelector extends Application {
private Text txt;
private Slider slRed;
private Slider slGreen;
private Slider slBlue;
private Slider slOpacity;
@Override
public void start(Stage primaryStage) {
txt = new Text("Show Colors");
txt.setFont(Font.font("Times New Roman",
FontWeight.BOLD, FontPosture.REGULAR, 20));
slRed = new Slider(0.0, 100.0, 0.0);
slRed.setShowTickLabels(true);
slRed.setShowTickMarks(true);
slGreen = new Slider(0.0, 100.0, 0.0);
slGreen.setShowTickLabels(true);
slGreen.setShowTickMarks(true);
slBlue = new Slider(0.0, 100.0, 0.0);
slBlue.setShowTickLabels(true);
slBlue.setShowTickMarks(true);
slOpacity = new Slider(0.0, 100.0, 100.0);
slOpacity.setShowTickLabels(true);
slOpacity.setShowTickMarks(true);
VBox root = new VBox(20);
root.getChildren().addAll(txt, slRed, slGreen, slBlue, slOpacity);
root.setPadding(new Insets(20));
root.setAlignment(Pos.CENTER);
Scene scene = new Scene(root);
slRed.valueProperty().addListener(ov -> changeColor());
slGreen.valueProperty().addListener(ov -> changeColor());
slBlue.valueProperty().addListener(ov -> changeColor());
slOpacity.valueProperty().addListener(ov -> changeColor());
primaryStage.setTitle("Color selector");
primaryStage.setScene(scene);
primaryStage.show();
}
protected void changeColor() {
Color c1 = new Color(slRed.getValue() / 100,
slGreen.getValue() / 100, slBlue.getValue() / 100, slOpacity.getValue() / 100);
txt.setFill(c1);
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
|
package com.test.base;
/**
* Given an array nums, we call (i, j) an important reverse pair if i < j and nums[i] > 2*nums[j].
* i < j 并且 num[i] > 2*num[j],就是成功的一对
*
* You need to return the number of important reverse pairs in the given array.
* 计算给的一个数组,有多少个这样的一对
*
* @author YLine
*
* 2019年5月29日 下午1:04:26
*/
public interface Solution
{
public int reversePairs(int[] nums);
}
|
package com.distributie.utils;
import java.util.List;
import java.util.Locale;
import android.content.Context;
import android.location.Geocoder;
import com.distributie.beans.Address;
import com.google.android.gms.maps.model.LatLng;
public class MapUtils {
public static LatLng geocodeAddress(Address address, Context context) throws Exception {
LatLng coords = null;
double latitude = 0;
double longitude = 0;
StringBuilder strAddress = new StringBuilder();
if (address.getStreetName() != null && !address.getStreetName().trim().equals("")) {
strAddress.append(address.getStreetName());
strAddress.append(",");
}
if (address.getStreetNo() != null && !address.getStreetNo().trim().equals("")) {
strAddress.append(address.getStreetNo());
strAddress.append(",");
}
if (address.getRegion() != null && !address.getRegion().trim().equals("")) {
strAddress.append(address.getRegion());
strAddress.append(",");
}
if (address.getCity() != null && !address.getCity().trim().equals("")) {
strAddress.append(address.getCity());
strAddress.append(",");
}
if (address.getCountry() != null && !address.getCountry().equals("") && !address.getCountry().trim().equals("RO")) {
strAddress.append(address.getCountry());
}
Geocoder geoCoder = new Geocoder(context, Locale.getDefault());
List<android.location.Address> addresses = geoCoder.getFromLocationName(strAddress.toString(), 1);
if (addresses.size() > 0) {
latitude = addresses.get(0).getLatitude();
longitude = addresses.get(0).getLongitude();
}
coords = new LatLng(latitude, longitude);
return coords;
}
public static LatLng geocodeSimpleAddress(String address, Context context) throws Exception {
LatLng coords = null;
double latitude = 0;
double longitude = 0;
StringBuilder strAddress = new StringBuilder(address);
if (strAddress.toString().endsWith(",")) {
strAddress.append("ROMANIA");
} else {
strAddress.append(",");
strAddress.append("ROMANIA");
}
Geocoder geoCoder = new Geocoder(context, Locale.getDefault());
List<android.location.Address> addresses = geoCoder.getFromLocationName(strAddress.toString(), 1);
if (addresses.size() > 0) {
latitude = addresses.get(0).getLatitude();
longitude = addresses.get(0).getLongitude();
}
coords = new LatLng(latitude, longitude);
return coords;
}
public static double distanceXtoY(double lat1, double lon1, double lat2, double lon2, String unit) {
double theta = lon1 - lon2;
double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.cos(deg2rad(theta));
dist = Math.acos(dist);
dist = rad2deg(dist);
dist = dist * 60 * 1.1515;
if (unit == "K") {
dist = dist * 1.609344;
} else if (unit == "N") {
dist = dist * 0.8684;
}
return (dist);
}
private static double deg2rad(double deg) {
return (deg * Math.PI / 180.0);
}
private static double rad2deg(double rad) {
return (rad * 180 / Math.PI);
}
}
|
/*
* Created on 01/10/2008
*
* To change the template for this generated file go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
package com.citibank.ods.modules.product.prodasset.action;
import com.citibank.ods.common.action.BaseODSMovementDetailAction;
import com.citibank.ods.common.functionality.BaseFnc;
import com.citibank.ods.common.functionality.valueobject.BaseFncVO;
import com.citibank.ods.modules.product.prodasset.functionality.ProdAssetMovementDetailFnc;
import com.citibank.ods.modules.product.prodasset.functionality.valueobject.ProdAssetMovementDetailFncVO;
/**
* @author lfabiano
*
* To change the template for this generated type comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
public class ProdAssetMovementDetailAction extends BaseODSMovementDetailAction
{
/*
* Parte do nome do módulo ou ação
*/
private static final String C_SCREEN_NAME = "ProdAsset.ProdAssetMovementDetail";
/* (non-Javadoc)
* @see com.citibank.ods.common.action.BaseODSAction#getFuncionality()
*/
protected BaseFnc getFuncionality()
{
return new ProdAssetMovementDetailFnc();
}
/* (non-Javadoc)
* @see com.citibank.ods.common.action.BaseODSAction#getScreenName()
*/
protected String getScreenName()
{
return C_SCREEN_NAME;
}
/* (non-Javadoc)
* @see com.citibank.ods.common.action.BaseODSAction#extraActions(com.citibank.ods.common.functionality.valueobject.BaseFncVO, java.lang.String)
*/
protected String extraActions( BaseFncVO fncVO_, String invokePath_ )
{
return null;
}
/* (non-Javadoc)
* @see com.citibank.ods.common.action.BaseAction#getFncVOPublishName()
*/
public String getFncVOPublishName()
{
return ProdAssetMovementDetailFncVO.class.getName();
}
}
|
package acueducto.domain;
import java.util.Map;
import java.util.HashMap;
import java.util.Collection;
/**
*
* @author Karla Salas M. | Leonardo Sanchez J.
*/
public interface EstacionRepository {
/**
* Insercion de un objeto Estacion.
* @param est
* @return
*/
public boolean insertEstacion(Estacion est);
/**
* Eliminacion de un objeto Estacion.
* @param est
* @return
*/
public boolean deleteEstacion(Estacion est);
/**
* Busqueda de un objeto Estacion.
* @param id
* @return
*/
public Estacion findEstacion(int id);
/**
* Actualizacion de un objeto Estacion.
* @param est
* @return
*/
public boolean updateEstacion(Estacion est);
/**
* Listado de objetos Estacion.
* @return
*/
public Collection findAllEstacion();
} |
package loredan13.hearth_server;
import com.sun.net.httpserver.HttpServer;
import loredan13.hearth_server.server.*;
import java.io.IOException;
import java.net.InetSocketAddress;
/**
* Created by loredan13 on 24.01.2015.
*/
public class Main {
public static int PORT = 12592;
public static boolean shutdownFlag = false;
public static void main(String[] args) {
//Daemonize application
try {
System.in.close();
System.out.close();
} catch (IOException e) {
e.printStackTrace();
}
//Set application to exit on receiving SIGTERM
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
shutdownFlag = true;
}
});
Config.loadConfig();
Authorization.init();
User.init();
//Start HTTP server
try {
HttpServer server = HttpServer.create(new InetSocketAddress(PORT), 0);
server.createContext(AuthHandler.PATH, new AuthHandler());
server.createContext(MoodHandler.PATH, new MoodHandler());
server.createContext(StateHandler.PATH, new StateHandler());
server.createContext(ConfigHandler.PATH, new ConfigHandler());
server.createContext(LocationHandler.PATH, new LocationHandler());
server.createContext(GameHandler.PATH, new GameHandler());
server.createContext(VacancyGameHandler.PATH, new VacancyGameHandler());
server.start();
} catch (IOException e) {
e.printStackTrace();
}
Log.print("Main", "Server started successfully");
while (!shutdownFlag) ;
Log.print("Main", "Server shutdown");
return;
}
}
|
package com.example.demoapp.Activities;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Dialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import com.example.demoapp.R;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
public class UserHomepage extends AppCompatActivity {
private FirebaseAuth mAuth;
private FirebaseUser currentUser;
private DatabaseReference reference;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_homepage);
mAuth=FirebaseAuth.getInstance();
currentUser=mAuth.getCurrentUser();
reference= FirebaseDatabase.getInstance().getReference();
popouMethod();
}
private void popouMethod() {
//Form Dialog
final Dialog dialog=new Dialog(this);
//set contentview
dialog.setContentView(R.layout.popup_form_layout);
//set outside touch
dialog.setCanceledOnTouchOutside(false);
//set dialog height & width
dialog.getWindow().setLayout(WindowManager.LayoutParams.WRAP_CONTENT,WindowManager.LayoutParams.WRAP_CONTENT);
//set transparent backgroun
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
//set Animation
dialog.getWindow().getAttributes().windowAnimations= android.R.style.Animation_Dialog;
//Initial dialog variable
final EditText date=dialog.findViewById(R.id.tv_date);
final EditText message=dialog.findViewById(R.id.et_message);
Button submitBtn=dialog.findViewById(R.id.submit_btn);
RadioGroup radioGroup=dialog.findViewById(R.id.radioGroup);
final RadioButton male=dialog.findViewById(R.id.male_btn);
final RadioButton female=dialog.findViewById(R.id.female_btn);
//create code
Calendar calendar=Calendar.getInstance();
SimpleDateFormat simpleDateFormat= new SimpleDateFormat("dd-MMM-yyyy hh:mm:ss a");
String datetime=simpleDateFormat.format(calendar.getTime());
date.setText(datetime);
submitBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String mdate=date.getText().toString().trim();
String mmessage=message.getText().toString().trim();
String gender="";
if (male.isChecked()){
gender="Male";
}
if (female.isChecked()){
gender="Female";
}
if (mdate.isEmpty() || mmessage.isEmpty()){
ShowMessage("Please verify all field");
}
else {
submitFormtofirebase(mdate,mmessage,gender,dialog);
}
}
});
//show dialog
dialog.show();
}
private void submitFormtofirebase(String mdate, String mmessage, String gender, final Dialog dialog) {
HashMap<String,Object> map=new HashMap<>();
map.put("userid",currentUser.getUid());
map.put("username",currentUser.getDisplayName());
map.put("useremail",currentUser.getEmail());
map.put("date",mdate);
map.put("gender",gender);
map.put("message",mmessage);
DatabaseReference mRef=FirebaseDatabase.getInstance().getReference().child("UserForm").push();
String id=mRef.getKey();
mRef.setValue(map).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()){
ShowMessage("Form Updated Succesfully..");
dialog.dismiss();
}
else {
ShowMessage("Error"+task.getException().getMessage());
}
}
});
}
private void ShowMessage(String s) {
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG).show();
}
}
|
package dao;
import java.sql.Connection;
public abstract class DaoFactory {
private Connection conn;
public DaoFactory() {
}
public abstract ProductDAO getProductDAO();
public abstract Connection openConnection();
public abstract void closeConnection(Connection conn);
}
|
package com.domineer.triplebro.mistakebook.activities;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.domineer.triplebro.mistakebook.R;
import com.domineer.triplebro.mistakebook.adapters.ErrorListAdapter;
import com.domineer.triplebro.mistakebook.controllers.ErrorListController;
import com.domineer.triplebro.mistakebook.models.ErrorInfo;
import com.domineer.triplebro.mistakebook.views.MyListView;
import java.util.List;
public class CollectActivity extends Activity implements View.OnClickListener {
private ImageView iv_close_error_list;
private ListView lv_error_list;
private RelativeLayout rl_image_large;
private ImageView iv_image_large;
private ImageView iv_close_image_large;
private ErrorListController errorListController;
private SharedPreferences userInfo;
private int user_id;
private ImageView iv_close_collect;
private List<ErrorInfo> errorInfoList;
private ErrorListAdapter errorListAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_collect);
initView();
initData();
setOnClickListener();
}
private void initView() {
iv_close_collect = (ImageView) findViewById(R.id.iv_close_collect);
lv_error_list = (ListView) findViewById(R.id.lv_error_list);
rl_image_large = (RelativeLayout) findViewById(R.id.rl_image_large);
iv_image_large = (ImageView) findViewById(R.id.iv_image_large);
iv_close_image_large = (ImageView) findViewById(R.id.iv_close_image_large);
}
private void initData() {
errorListController = new ErrorListController(this);
userInfo = getSharedPreferences("userInfo", MODE_PRIVATE);
user_id = userInfo.getInt("user_id", -1);
if(user_id == -1){
Toast.makeText(this, "还没登录呢,不能查看错题列表!!!", Toast.LENGTH_SHORT).show();
finish();
}
errorInfoList = errorListController.getCollectErrorListByUserId(user_id);
errorListAdapter = new ErrorListAdapter(this, errorInfoList);
errorListAdapter.setViewInfo(rl_image_large,iv_image_large,iv_close_image_large);
lv_error_list.setAdapter(errorListAdapter);
}
private void setOnClickListener() {
iv_close_collect.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.iv_close_collect:
finish();
break;
}
}
}
|
package com.utils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
public class FileManager {
public static void saveToFile(String file, String content){
try{
PrintWriter writer = new PrintWriter(file, "UTF-8");
writer.println(content);
writer.close();
} catch (IOException e) {
System.err.println(e);
}
}
public static void saveToFile(File file, String content){
saveToFile(file.getAbsolutePath(), content);
}
public static String loadFromFile(String file){
StringBuilder result = new StringBuilder();
String line;
try {
BufferedReader in = new BufferedReader(new FileReader(file));
while((line = in.readLine()) != null){
result.append(line);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
return result.toString();
}
public static String loadFromFile(File file){
return loadFromFile(file.getAbsolutePath());
}
}
|
package eu.bittrade.steem.steemstats.entities;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* @author <a href="http://steemit.com/@dez1337">dez1337</a>
*/
@Entity
@Table(name = "RECORDS")
public class Record {
@Id
@Column(name = "RECORD_ID")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(name = "START_BLOCK_NUMBER")
private long startBlockNumber;
@Column(name = "START_BLOCK_CREATION_DATE")
private Date startBlockCreationDate;
@Column(name = "END_BLOCK_NUMBER")
private long endBlockNumber;
@Column(name = "END_BLOCK_CREATION_DATE")
private Date endBlockCreationDate;
@Column(name = "NUMBER_OF_OPERATIONS")
private long numberOfOperations;
@Column(name = "NUMBER_OF_TRANSACTIONS")
private long numberOfTransactions;
/**
* @return the id
*/
public long getId() {
return id;
}
/**
* @param id
* the id to set
*/
public void setId(long id) {
this.id = id;
}
/**
* @return the startBlockNumber
*/
public long getStartBlockNumber() {
return startBlockNumber;
}
/**
* @param startBlockNumber
* the startBlockNumber to set
*/
public void setStartBlockNumber(long startBlockNumber) {
this.startBlockNumber = startBlockNumber;
}
/**
* @return the startBlockCreationDate
*/
public Date getStartBlockCreationDate() {
return startBlockCreationDate;
}
/**
* @param startBlockCreationDate
* the startBlockCreationDate to set
*/
public void setStartBlockCreationDate(Date startBlockCreationDate) {
this.startBlockCreationDate = startBlockCreationDate;
}
/**
* @return the endBlockNumber
*/
public long getEndBlockNumber() {
return endBlockNumber;
}
/**
* @param endBlockNumber
* the endBlockNumber to set
*/
public void setEndBlockNumber(long endBlockNumber) {
this.endBlockNumber = endBlockNumber;
}
/**
* @return the endBlockCreationDate
*/
public Date getEndBlockCreationDate() {
return endBlockCreationDate;
}
/**
* @param endBlockCreationDate
* the endBlockCreationDate to set
*/
public void setEndBlockCreationDate(Date endBlockCreationDate) {
this.endBlockCreationDate = endBlockCreationDate;
}
/**
* @return the numberOfOperations
*/
public long getNumberOfOperations() {
return numberOfOperations;
}
/**
* @param numberOfOperations
* the numberOfOperations to set
*/
public void setNumberOfOperations(long numberOfOperations) {
this.numberOfOperations = numberOfOperations;
}
/**
* @return the numberOfTransactions
*/
public long getNumberOfTransactions() {
return numberOfTransactions;
}
/**
* @param numberOfTransactions
* the numberOfTransactions to set
*/
public void setNumberOfTransactions(long numberOfTransactions) {
this.numberOfTransactions = numberOfTransactions;
}
}
|
package digitalclock;
import java.awt.*;
import javax.swing.*;
public class DigitalClock extends JFrame{
JLabel clock;
Clock cl;
public DigitalClock() {
clock= new JLabel("Casio");
setTitle("Saranti's Clock");
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(clock);
setSize(1200,160);
setLocation(600, 300);
clock.setFont(new Font("Arial",Font.CENTER_BASELINE,80));
clock.setOpaque(true);
clock.setBackground(Color.BLACK);
clock.setForeground(Color.WHITE);
cl=new Clock(this);
setVisible(true);
}
public static void main(String[] args) {
DigitalClock dc= new DigitalClock();
}
}
|
/*
* Copyright 2002-2022 the original author or authors.
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.http.converter;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.FileCacheImageInputStream;
import javax.imageio.stream.FileCacheImageOutputStream;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.ImageOutputStream;
import javax.imageio.stream.MemoryCacheImageInputStream;
import javax.imageio.stream.MemoryCacheImageOutputStream;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.StreamingHttpOutputMessage;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
/**
* Implementation of {@link HttpMessageConverter} that can read and write
* {@link BufferedImage BufferedImages}.
*
* <p>By default, this converter can read all media types that are supported
* by the {@linkplain ImageIO#getReaderMIMETypes() registered image readers},
* and writes using the media type of the first available
* {@linkplain javax.imageio.ImageIO#getWriterMIMETypes() registered image writer}.
* The latter can be overridden by setting the
* {@link #setDefaultContentType defaultContentType} property.
*
* <p>If the {@link #setCacheDir cacheDir} property is set, this converter
* will cache image data.
*
* <p>The {@link #process(ImageReadParam)} and {@link #process(ImageWriteParam)}
* template methods allow subclasses to override Image I/O parameters.
*
* @author Arjen Poutsma
* @since 3.0
*/
public class BufferedImageHttpMessageConverter implements HttpMessageConverter<BufferedImage> {
private final List<MediaType> readableMediaTypes = new ArrayList<>();
@Nullable
private MediaType defaultContentType;
@Nullable
private File cacheDir;
public BufferedImageHttpMessageConverter() {
String[] readerMediaTypes = ImageIO.getReaderMIMETypes();
for (String mediaType : readerMediaTypes) {
if (StringUtils.hasText(mediaType)) {
this.readableMediaTypes.add(MediaType.parseMediaType(mediaType));
}
}
String[] writerMediaTypes = ImageIO.getWriterMIMETypes();
for (String mediaType : writerMediaTypes) {
if (StringUtils.hasText(mediaType)) {
this.defaultContentType = MediaType.parseMediaType(mediaType);
break;
}
}
}
/**
* Sets the default {@code Content-Type} to be used for writing.
* @throws IllegalArgumentException if the given content type is not supported by the Java Image I/O API
*/
public void setDefaultContentType(@Nullable MediaType defaultContentType) {
if (defaultContentType != null) {
Iterator<ImageWriter> imageWriters = ImageIO.getImageWritersByMIMEType(defaultContentType.toString());
if (!imageWriters.hasNext()) {
throw new IllegalArgumentException(
"Content-Type [" + defaultContentType + "] is not supported by the Java Image I/O API");
}
}
this.defaultContentType = defaultContentType;
}
/**
* Returns the default {@code Content-Type} to be used for writing.
* Called when {@link #write} is invoked without a specified content type parameter.
*/
@Nullable
public MediaType getDefaultContentType() {
return this.defaultContentType;
}
/**
* Sets the cache directory. If this property is set to an existing directory,
* this converter will cache image data.
*/
public void setCacheDir(File cacheDir) {
Assert.notNull(cacheDir, "'cacheDir' must not be null");
Assert.isTrue(cacheDir.isDirectory(), () -> "'cacheDir' is not a directory: " + cacheDir);
this.cacheDir = cacheDir;
}
@Override
public boolean canRead(Class<?> clazz, @Nullable MediaType mediaType) {
return (BufferedImage.class == clazz && isReadable(mediaType));
}
private boolean isReadable(@Nullable MediaType mediaType) {
if (mediaType == null) {
return true;
}
Iterator<ImageReader> imageReaders = ImageIO.getImageReadersByMIMEType(mediaType.toString());
return imageReaders.hasNext();
}
@Override
public boolean canWrite(Class<?> clazz, @Nullable MediaType mediaType) {
return (BufferedImage.class == clazz && isWritable(mediaType));
}
private boolean isWritable(@Nullable MediaType mediaType) {
if (mediaType == null || MediaType.ALL.equalsTypeAndSubtype(mediaType)) {
return true;
}
Iterator<ImageWriter> imageWriters = ImageIO.getImageWritersByMIMEType(mediaType.toString());
return imageWriters.hasNext();
}
@Override
public List<MediaType> getSupportedMediaTypes() {
return Collections.unmodifiableList(this.readableMediaTypes);
}
@Override
public BufferedImage read(@Nullable Class<? extends BufferedImage> clazz, HttpInputMessage inputMessage)
throws IOException, HttpMessageNotReadableException {
ImageInputStream imageInputStream = null;
ImageReader imageReader = null;
// We cannot use try-with-resources here for the ImageInputStream, since we have
// custom handling of the close() method in a finally-block.
try {
imageInputStream = createImageInputStream(inputMessage.getBody());
MediaType contentType = inputMessage.getHeaders().getContentType();
if (contentType == null) {
throw new HttpMessageNotReadableException("No Content-Type header", inputMessage);
}
Iterator<ImageReader> imageReaders = ImageIO.getImageReadersByMIMEType(contentType.toString());
if (imageReaders.hasNext()) {
imageReader = imageReaders.next();
ImageReadParam irp = imageReader.getDefaultReadParam();
process(irp);
imageReader.setInput(imageInputStream, true);
return imageReader.read(0, irp);
}
else {
throw new HttpMessageNotReadableException(
"Could not find javax.imageio.ImageReader for Content-Type [" + contentType + "]",
inputMessage);
}
}
finally {
if (imageReader != null) {
imageReader.dispose();
}
if (imageInputStream != null) {
try {
imageInputStream.close();
}
catch (IOException ex) {
// ignore
}
}
}
}
private ImageInputStream createImageInputStream(InputStream is) throws IOException {
is = StreamUtils.nonClosing(is);
if (this.cacheDir != null) {
return new FileCacheImageInputStream(is, this.cacheDir);
}
else {
return new MemoryCacheImageInputStream(is);
}
}
@Override
public void write(final BufferedImage image, @Nullable final MediaType contentType,
final HttpOutputMessage outputMessage)
throws IOException, HttpMessageNotWritableException {
final MediaType selectedContentType = getContentType(contentType);
outputMessage.getHeaders().setContentType(selectedContentType);
if (outputMessage instanceof StreamingHttpOutputMessage streamingOutputMessage) {
streamingOutputMessage.setBody(outputStream -> writeInternal(image, selectedContentType, outputStream));
}
else {
writeInternal(image, selectedContentType, outputMessage.getBody());
}
}
private MediaType getContentType(@Nullable MediaType contentType) {
if (contentType == null || contentType.isWildcardType() || contentType.isWildcardSubtype()) {
contentType = getDefaultContentType();
}
Assert.notNull(contentType, "Could not select Content-Type. " +
"Please specify one through the 'defaultContentType' property.");
return contentType;
}
private void writeInternal(BufferedImage image, MediaType contentType, OutputStream body)
throws IOException, HttpMessageNotWritableException {
ImageOutputStream imageOutputStream = null;
ImageWriter imageWriter = null;
try {
Iterator<ImageWriter> imageWriters = ImageIO.getImageWritersByMIMEType(contentType.toString());
if (imageWriters.hasNext()) {
imageWriter = imageWriters.next();
ImageWriteParam iwp = imageWriter.getDefaultWriteParam();
process(iwp);
imageOutputStream = createImageOutputStream(body);
imageWriter.setOutput(imageOutputStream);
imageWriter.write(null, new IIOImage(image, null, null), iwp);
}
else {
throw new HttpMessageNotWritableException(
"Could not find javax.imageio.ImageWriter for Content-Type [" + contentType + "]");
}
}
finally {
if (imageWriter != null) {
imageWriter.dispose();
}
if (imageOutputStream != null) {
try {
imageOutputStream.close();
}
catch (IOException ex) {
// ignore
}
}
}
}
private ImageOutputStream createImageOutputStream(OutputStream os) throws IOException {
if (this.cacheDir != null) {
return new FileCacheImageOutputStream(os, this.cacheDir);
}
else {
return new MemoryCacheImageOutputStream(os);
}
}
/**
* Template method that allows for manipulating the {@link ImageReadParam}
* before it is used to read an image.
* <p>The default implementation is empty.
*/
protected void process(ImageReadParam irp) {
}
/**
* Template method that allows for manipulating the {@link ImageWriteParam}
* before it is used to write an image.
* <p>The default implementation is empty.
*/
protected void process(ImageWriteParam iwp) {
}
}
|
package CubeBase2;
import java.util.LinkedList;
import Helper.Answer;
class FactorialHelper {
// attention overflow
public final static int Fsize = 18;
public static int[] F = new int[Fsize];
public static int[][] C = new int[Fsize][Fsize];
static {
F[1] = 1;
for (int i = 2; i < Fsize; i++) {
F[i] = F[i - 1] * i;
C[i][0] = 1;
C[i][i] = 1;
}
for (int i = 0; i < Fsize; i++) {
for (int j = 1; j < i; j++) {
C[i][j] = F[i] / F[j] / F[i - j];
}
}
}
}
class CubeType {
public static final int UNKNOW = 0;
public static final int INSIDE = 1;
public static final int OUTSIDE = 2;
public static final int EDGE = 3;
}
class CubeBaseArr {
public static int generateNum;
public static int dim;
double[] arr;
/**
*
* @param len
*/
CubeBaseArr(int dimension) {
dim = dimension;
arr = new double[dimension];
for (int i = 0; i < arr.length; i++) {
arr[i] = 0.5;
}
generateNum = (int)Math.pow(2, dimension);
}
protected CubeBaseArr(double arr[]) {
this.arr = new double[arr.length];
for (int i = 0; i < arr.length; i++) {
this.arr[i] = arr[i];
}
}
/**
* give a grain to decide if arr inside the hypersphere
*
* @param grain
* @return
*/
public int isInside(double grain) {
double highsum = 0.0;
double lowsum = 0.0;
for (int i = 0; i < arr.length; i++) {
double temp1 = (arr[i] + grain);
highsum += temp1 * temp1;
double temp2 = (arr[i] - grain);
lowsum += temp2 * temp2;
}
if (highsum < 1.0) {
return CubeType.INSIDE;
} else if (lowsum > 1.0) {
return CubeType.OUTSIDE;
} else {
return CubeType.EDGE;
}
}
public LinkedList<CubeBaseArr> generate(double grain) {
LinkedList<CubeBaseArr> cbas = new LinkedList<CubeBaseArr>();
for (int i = 0; i < generateNum; i++) {
CubeBaseArr cur = new CubeBaseArr(arr);
for (int d = 0, shift = dim - 1; d < dim; d++, shift--) {// dimension
if ((i & (1 << shift)) == 0) {
cur.arr[d] -= grain;
} else {
cur.arr[d] += grain;
}
}
cbas.add(cur);
}
return cbas;
}
}
class CubeBaseProxy {
public double sampleCount;
private int dimension;
private double curGrain;
private double lastGrain;
private double curVolume;
private double curWeight;
private LinkedList<CubeBaseArr> cbas;
CubeBaseProxy(int dimension) {
this.dimension = dimension;
lastGrain = 1;
curGrain = 0.5;
cbas = new LinkedList<CubeBaseArr>();
CubeBaseArr cba = new CubeBaseArr(dimension);
cbas.add(cba);
curWeight = 1.0;
sampleCount = 0.0;
}
/**
* for old one
*
* @return
*/
public double pushFoward() {
int size = cbas.size();
lastGrain /= 2;
curGrain /= 2;
long count = 0;
for (int i = 0; i < size; i++) {
CubeBaseArr cur = cbas.removeFirst();
sampleCount++;
int temp = cur.isInside(lastGrain);
if (temp == CubeType.EDGE) {
cbas.addAll(cur.generate(curGrain));
} else if (temp == CubeType.INSIDE) {
count++;
}
}
curVolume += curWeight * count;
curWeight /= Math.pow(2, dimension);
return curVolume;
}
}
/**
*
* @author wangbicheng
* Cube-Base Test
*/
public class CubeBase2Test {
public static void main(String[] args) {
long start = System.currentTimeMillis();
int dimension = 3;
int grainLevel = 12; // the sample number is about (2 ^ dimension) ^ grainLevel
double estimateVolume = Math.pow(2, dimension);
CubeBaseProxy cbp = new CubeBaseProxy(dimension);
for(int i = 0; i < grainLevel - 1; i++) {
cbp.pushFoward();
}
estimateVolume *= cbp.pushFoward();
long end = System.currentTimeMillis();
System.out.println("estimate sample: " + Math.pow(Math.pow(2, dimension), grainLevel));
System.out.println("actually sample:" + cbp.sampleCount);
System.out.println("standard volume:" + Answer.answer(dimension));
System.out.println("estimate volume:" + estimateVolume);
System.out.println("cost time:" + (end - start) / 1000 + "s");
return;
}
}
|
package com.szhrnet.taoqiapp.mvp.api.response;
/**
* <pre>
* author: MakeCodeFly
* desc : PageListModel类
* email:15695947865@139.com
* </pre>
*/
@SuppressWarnings({"WeakerAccess", "unused"})
public class PageListModel<T> { private boolean is_last;
private T list;
public boolean is_last() {
return is_last;
}
public void setIs_last(boolean is_last) {
this.is_last = is_last;
}
public T getList() {
return list;
}
public void setList(T list) {
this.list = list;
}
}
|
/* Created on Apr 14, 2007
*
*/
package com.citibank.ods.entity.pl.valueobject;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.citibank.ods.entity.pl.TplRiskFamilyProdPlayerHistEntity;
import com.citibank.ods.entity.pl.TplRiskFamilyProdPlayerMovEntity;
/**
* @author acacio.domingos
*
*/
public class TplProductHistEntityVO extends BaseTplProductEntityVO
{
/**
* Data e Hora que o usuario aprovou o registro cadastrado
*
* @generated "UML to Java
* (com.ibm.xtools.transform.uml2.java.internal.UML2JavaTransform)"
*/
private Date m_lastAuthDate;
/**
* Codigo do usuario (SOE ID) que aprovou o cadastro do registro
*
* @generated "UML to Java
* (com.ibm.xtools.transform.uml2.java.internal.UML2JavaTransform)"
*/
private String m_lastAuthUserId;
/**
* Status Registro - Identifica se o registro esta ativo, inativo ou aguar
* dando aprovacao"
*
* @generated "UML to Java
* (com.ibm.xtools.transform.uml2.java.internal.UML2JavaTransform)"
*/
private String m_recStatCode;
/**
* Data de Referencia do registro no historico.
*
* @generated "UML to Java
* (com.ibm.xtools.transform.uml2.java.internal.UML2JavaTransform)"
*/
private Date m_prodRefDate;
//Lista de Emissores do Produto
private List<TplRiskFamilyProdPlayerHistEntity> listTplRiskFamilyProdPlayerHistEntity;
public TplProductHistEntityVO(){
listTplRiskFamilyProdPlayerHistEntity = new ArrayList<TplRiskFamilyProdPlayerHistEntity>();
}
/**
* @return Returns the lastAuthDate.
*/
public Date getLastAuthDate()
{
return m_lastAuthDate;
}
/**
* @param lastAuthDate_ The lastAuthDate to set.
*/
public void setLastAuthDate( Date lastAuthDate_ )
{
m_lastAuthDate = lastAuthDate_;
}
/**
* @return Returns the lastAuthUserId.
*/
public String getLastAuthUserId()
{
return m_lastAuthUserId;
}
/**
* @param lastAuthUserId_ The lastAuthUserId to set.
*/
public void setLastAuthUserId( String lastAuthUserId_ )
{
m_lastAuthUserId = lastAuthUserId_;
}
/**
* @return Returns the ProdRefDate.
*/
public Date getProdRefDate()
{
return m_prodRefDate;
}
/**
* @param prodRefDate__ The prodRefDate to set.
*/
public void setProdRefDate( Date prodRefDate_ )
{
m_prodRefDate = prodRefDate_;
}
/**
* @return Returns the recStatCode.
*/
public String getRecStatCode()
{
return m_recStatCode;
}
/**
* @param recStatCode_ The recStatCode to set.
*/
public void setRecStatCode( String recStatCode_ )
{
m_recStatCode = recStatCode_;
}
public List<TplRiskFamilyProdPlayerHistEntity> getListProductPlayerRiskVO() {
return listTplRiskFamilyProdPlayerHistEntity;
}
public void setListProductPlayerRiskVO(List<TplRiskFamilyProdPlayerHistEntity> listTplRiskFamilyProdPlayerHistEntity) {
this.listTplRiskFamilyProdPlayerHistEntity = listTplRiskFamilyProdPlayerHistEntity;
}
} |
import javax.sound.midi.*;
import java.io.*;
import javax.swing.*;
import java.awt.*;
class MyDrawPanel_M extends JPanel implements ControllerEventListener{
boolean msg = false;
public void controlChange(ShortMessage event){
msg = true;
repaint();
}
public void paintComponent(Graphics g){
if(msg){
Graphics2D g2 = (Graphics2D)g;
int r = (int)(Math.random()*250);
int gr = (int)(Math.random()*250);
int b = (int)(Math.random()*250);
g.setColor(new Color(r,gr,b));
int height = (int)((Math.random()*120)+10);
int width = (int)((Math.random()*120)+10);
int x = (int)(Math.random()*40+10);
int y = (int)(Math.random()*40+10);
g.fillRect(x,y,height,width);
msg = false;
}
}
} |
package io.t99.philesd.locations;
import java.util.HashMap;
public class LocationManager {
private static HashMap<String, Location> locations = new HashMap<>();
public static void register(String name, Location location) {
locations.put(name, location);
}
public static Location get(String name) {
return locations.get(name);
}
public static void remove(String name) {
locations.remove(name);
}
public static void rename(String oldName, String newName) {
locations.put(newName, locations.get(oldName));
locations.remove(oldName);
}
public static String getPath(String name) {
return locations.get(name).getPath().toString();
}
public static void getList() {
for (String name: locations.keySet()) {
System.out.println("Location Name: " + name);
System.out.println("Location Path: " + locations.get(name).getPath().toString() + "\n");
}
}
} |
package nowcoder;
import java.util.*;
public class Easy {
/**
* 反转字符串
* @param str string字符串
* @return string字符串
*/
public String solve (String str) {
char[] ans = new char[str.length()];
for (int i = 0; i < ans.length; i++) {
ans[i] = str.charAt(str.length()-1-i);
}
return new String(ans);
}
/**
* 螺旋矩阵
* @param matrix .
* @return .
*/
public void spiralOrder(int[][] matrix) {
}
} |
package com.xinhua.api.domain.xtBean;
import com.apsaras.aps.increment.domain.AbstractIncRequest;
import java.io.Serializable;
/**
* Created by ning on 15/7/21.
* 心跳交易 请求
*/
public class XtRequest extends AbstractIncRequest implements Serializable {
/**
*银行代码
*/
private String bankCode;
/**
*地区代码
*/
private String regionCode;
/**
*网点代码
*/
private String branch;
/**
*柜员代码
*/
private String teller;
/**
*请求中心代码
*/
private String ask;
/**
*保险公司代码
*/
private String carrierCode;
/**
*处理中心代码
*/
private String proc;
/**
*交易日期
*/
private String transExeDate;
/**
*请求方交易系统时间
*/
private String bkPlatTime;
/**
*交易类型
*/
private String cate;
/**
*交易科目
*/
private String subject;
/**
*交易流水号
*/
private String transRefGUID;
/**
*交易内容信息区
*/
private String content;
/**
*请求方交易流水号
*/
private String bkPlatSeqNo;
/**
*交易渠道代号
*/
private String bkChnlNo;
/**
*原始请求方机构代码
*/
private String bkBrchNo;
/**
*原始请求方机构名称
*/
private String bkBrchName;
/**
*请求方交易码
*/
private String bkTxCode;
/**
*银行交易流水号
*/
private String transNo;
/**
*保险公司流水号
*/
private String insuTrans;
/**
*交易发起方
*/
private String transSide;
/**
*委托方式
*/
private String entrustWay;
/**
*省市代码
*/
private String provCode;
/**
*预留字段1
*/
private String bkDetail1;
/**
*预留字段2
*/
private String bkDetail2;
/**
* 用于无法处理的字段
*/
private String no;
public String getNo() {
return no;
}
public void setNo(String no) {
this.no = no;
}
public String getBankCode() {
return bankCode;
}
public void setBankCode(String bankCode) {
this.bankCode = bankCode;
}
public String getRegionCode() {
return regionCode;
}
public void setRegionCode(String regionCode) {
this.regionCode = regionCode;
}
public String getBranch() {
return branch;
}
public void setBranch(String branch) {
this.branch = branch;
}
public String getTeller() {
return teller;
}
public void setTeller(String teller) {
this.teller = teller;
}
public String getAsk() {
return ask;
}
public void setAsk(String ask) {
this.ask = ask;
}
public String getCarrierCode() {
return carrierCode;
}
public void setCarrierCode(String carrierCode) {
this.carrierCode = carrierCode;
}
public String getProc() {
return proc;
}
public void setProc(String proc) {
this.proc = proc;
}
public String getTransExeDate() {
return transExeDate;
}
public void setTransExeDate(String transExeDate) {
this.transExeDate = transExeDate;
}
public String getBkPlatTime() {
return bkPlatTime;
}
public void setBkPlatTime(String bkPlatTime) {
this.bkPlatTime = bkPlatTime;
}
public String getCate() {
return cate;
}
public void setCate(String cate) {
this.cate = cate;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getTransRefGUID() {
return transRefGUID;
}
public void setTransRefGUID(String transRefGUID) {
this.transRefGUID = transRefGUID;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getBkPlatSeqNo() {
return bkPlatSeqNo;
}
public void setBkPlatSeqNo(String bkPlatSeqNo) {
this.bkPlatSeqNo = bkPlatSeqNo;
}
public String getBkChnlNo() {
return bkChnlNo;
}
public void setBkChnlNo(String bkChnlNo) {
this.bkChnlNo = bkChnlNo;
}
public String getBkBrchNo() {
return bkBrchNo;
}
public void setBkBrchNo(String bkBrchNo) {
this.bkBrchNo = bkBrchNo;
}
public String getBkBrchName() {
return bkBrchName;
}
public void setBkBrchName(String bkBrchName) {
this.bkBrchName = bkBrchName;
}
public String getBkTxCode() {
return bkTxCode;
}
public void setBkTxCode(String bkTxCode) {
this.bkTxCode = bkTxCode;
}
public String getTransNo() {
return transNo;
}
public void setTransNo(String transNo) {
this.transNo = transNo;
}
public String getInsuTrans() {
return insuTrans;
}
public void setInsuTrans(String insuTrans) {
this.insuTrans = insuTrans;
}
public String getTransSide() {
return transSide;
}
public void setTransSide(String transSide) {
this.transSide = transSide;
}
public String getEntrustWay() {
return entrustWay;
}
public void setEntrustWay(String entrustWay) {
this.entrustWay = entrustWay;
}
public String getProvCode() {
return provCode;
}
public void setProvCode(String provCode) {
this.provCode = provCode;
}
public String getBkDetail1() {
return bkDetail1;
}
public void setBkDetail1(String bkDetail1) {
this.bkDetail1 = bkDetail1;
}
public String getBkDetail2() {
return bkDetail2;
}
public void setBkDetail2(String bkDetail2) {
this.bkDetail2 = bkDetail2;
}
@Override
public String toString() {
return "XtRequest{" +
"bankCode='" + bankCode + '\'' +
", regionCode='" + regionCode + '\'' +
", branch='" + branch + '\'' +
", teller='" + teller + '\'' +
", ask='" + ask + '\'' +
", carrierCode='" + carrierCode + '\'' +
", proc='" + proc + '\'' +
", transExeDate='" + transExeDate + '\'' +
", bkPlatTime='" + bkPlatTime + '\'' +
", cate='" + cate + '\'' +
", subject='" + subject + '\'' +
", transRefGUID='" + transRefGUID + '\'' +
", content='" + content + '\'' +
", bkPlatSeqNo='" + bkPlatSeqNo + '\'' +
", bkChnlNo='" + bkChnlNo + '\'' +
", bkBrchNo='" + bkBrchNo + '\'' +
", bkBrchName='" + bkBrchName + '\'' +
", bkTxCode='" + bkTxCode + '\'' +
", transNo='" + transNo + '\'' +
", insuTrans='" + insuTrans + '\'' +
", transSide='" + transSide + '\'' +
", entrustWay='" + entrustWay + '\'' +
", provCode='" + provCode + '\'' +
", bkDetail1='" + bkDetail1 + '\'' +
", bkDetail2='" + bkDetail2 + '\'' +
'}';
}
}
|
/*
* Copyright (c) 2013-2014, Neuro4j.org
*
* 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 org.neuro4j.studio.debug.ui.views;
import org.eclipse.debug.internal.core.IInternalDebugCoreConstants;
import org.eclipse.debug.internal.ui.IDebugHelpContextIds;
import org.eclipse.debug.internal.ui.views.launch.LaunchViewMessages;
import org.eclipse.jface.action.Action;
import org.eclipse.ui.PlatformUI;
/**
* Action that controls the preference for whether elements should be
* automatically expanded in the breadcrumb drop down viewers.
*
* @since 3.5
*/
class BreadcrumbDropDownAutoExpandAction extends Action {
private final FlowLaunchView fLaunchView;
/**
* Creates a new action to set the debug view mode.
*
* @param view
* Reference to the debug view.
* @param mode
* The mode to be set by this action.
* @param parent
* The view's parent control used to calculate view size
* in auto mode.
*/
public BreadcrumbDropDownAutoExpandAction(FlowLaunchView view) {
super(IInternalDebugCoreConstants.EMPTY_STRING, AS_CHECK_BOX);
fLaunchView = view;
setText(LaunchViewMessages.BreadcrumbDropDownAutoExpandAction_label);
setToolTipText(LaunchViewMessages.BreadcrumbDropDownAutoExpandAction_tooltip);
setDescription(LaunchViewMessages.BreadcrumbDropDownAutoExpandAction_description);
PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IDebugHelpContextIds.DEBUG_VIEW_DROP_DOWN_AUTOEXPAND_ACTION);
setChecked(fLaunchView.getBreadcrumbDropDownAutoExpand());
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.action.IAction#run()
*/
public void run() {
fLaunchView.setBreadcrumbDropDownAutoExpand(isChecked());
}
}
|
package common.util.xml;
import java.io.StringReader;
import java.io.StringWriter;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import common.util.reflection.AnnotationFoundCallback;
import common.util.reflection.ReflectionUtil;
public class JaxbUtil {
private static HashMap<Class<?>, JAXBContext> jaxbContextMap = new HashMap<Class<?>, JAXBContext>();
public static JAXBContext getJAXBContext(Class<?> cls) throws JAXBException {
if (!jaxbContextMap.containsKey(cls)) {
JAXBContext ctx = JAXBContext.newInstance(cls);
jaxbContextMap.put(cls, ctx);
}
JAXBContext ctx = jaxbContextMap.get(cls);
return ctx;
}
public static String getXmlString(Object obj) throws JAXBException {
StringWriter sw = new StringWriter();
Marshaller marshaller = getJAXBContext(obj.getClass()).createMarshaller();
marshaller.setProperty("jaxb.formatted.output", Boolean.TRUE);
marshaller.marshal(obj, sw);
return sw.toString();
}
public static <T> T getObject(Class<T> cls, String xml) throws JAXBException {
StringReader sr = new StringReader(xml);
return (T) getJAXBContext(cls).createUnmarshaller().unmarshal(sr);
}
public static Document getDocument(Object obj) throws JAXBException, ParserConfigurationException {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.newDocument();
getJAXBContext(obj.getClass()).createMarshaller().marshal(obj, doc);
return doc;
}
public static HashMap<String, Node> getDocuments(Object... objs) throws JAXBException,
ParserConfigurationException {
HashMap<String, Node> ret = new HashMap<String, Node>();
for (Object o : objs) {
ret.put(o.getClass().getSimpleName(), getDocument(o));
}
return ret;
}
private static void copy(String fieldName, Class<?> type, Object src, Object dst, Class<?> expectedProfile, XmlProfile annotatedProfile)
throws Exception {
Field field = ReflectionUtil.getField(dst.getClass(), fieldName);
String setterName = "set" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
Method setter = dst.getClass().getMethod(setterName, type);
String getterName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
if(field.getType().equals(Boolean.class) || field.getType().equals(boolean.class)) {
getterName = "is" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
}
Method getter = src.getClass().getMethod(getterName, null);
if(field == null) {
return;
}
if (annotatedProfile != null) {
boolean found = false;
for (Class<?> s : annotatedProfile.value()) {
if (expectedProfile.equals(s)) {
found = true;
break;
}
}
if (!found) {
// Object[] args = new Object[1];
// setter.invoke(dst, args);
return;
}
}
if (ReflectionUtil.annotatedWith(type, XmlType.class)) {
Object subSrc = getter.invoke(src, null);
if (subSrc == null) {
return;
}
Object subDst = type.newInstance();
setter.invoke(dst, subDst);
copy(subSrc, subDst, expectedProfile);
return;
}
Object value = getter.invoke(src, null);
if (value instanceof List) {
Class<?> itemType = ReflectionUtil.getFieldGenericType(field);
List listSrc = (List) value;
List listDst = new ArrayList();
setter.invoke(dst, listDst);
for (Object srcItem : listSrc) {
Object dstItem = itemType.newInstance();
listDst.add(dstItem);
copy(srcItem, dstItem, expectedProfile);
}
} else {
setter.invoke(dst, value);
}
}
public static void copy(final Object src, final Object dst, final Class<?> profile) {
try {
ReflectionUtil.iterateAnnotation(dst, XmlElement.class, new AnnotationFoundCallback() {
public void field(Object obj, Field field) {
try {
copy(field.getName(), field.getType(), src, obj, profile, field.getAnnotation(XmlProfile.class));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void method(Object obj, Method method) {
String getterName = method.getName();
String fieldName = getterName.substring(3);
if(getterName.startsWith("is")) {
fieldName = getterName.substring(2);
}
fieldName = fieldName.substring(0, 1).toLowerCase() + fieldName.substring(1);
Class<?> retType = method.getReturnType();
try {
copy(fieldName, retType, src, obj, profile, method.getAnnotation(XmlProfile.class));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
});
ReflectionUtil.iterateAnnotation(dst, XmlAttribute.class, new AnnotationFoundCallback() {
public void field(Object obj, Field field) {
try {
copy(field.getName(), field.getType(), src, obj, profile, field.getAnnotation(XmlProfile.class));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void method(Object obj, Method method) {
String getterName = method.getName();
String fieldName = getterName.substring(3);
fieldName = fieldName.substring(0, 1).toLowerCase() + fieldName.substring(1);
Class<?> retType = method.getReturnType();
try {
copy(fieldName, retType, src, obj, profile, method.getAnnotation(XmlProfile.class));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
});
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
}
|
package org.beanone.xlogger.mock;
public class MockArg {
private final String id = "1";
private final String attribute = "attribute";
public String getAttribute() {
return this.attribute;
}
public String getId() {
return this.id;
}
}
|
package org.gatein.wcm.performance;
import java.io.File;
import java.text.DecimalFormat;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.annotation.Resource;
import junit.framework.Assert;
import org.gatein.wcm.api.services.WCMContentService;
import org.gatein.wcm.api.services.WCMRepositoryService;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.logging.Logger;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(Arquillian.class)
public class WcmSmallWriteTextTest {
// private static final Logger log = Logger.getLogger(WcmSmallWriteTextTest.class);
//
// private static final int NTHREADS = 10;
// private static final int NTESTS = 500;
//
// @Deployment
// public static Archive<?> createDeployment() {
//
// return ShrinkWrap.create(WebArchive.class, "gatein-wcm-integration-tests-performance.war")
// .addClasses(WcmSmallWorker.class, WcmThreadFactory.class)
// .addAsResource(new File("src/test/resources/jbossportletbridge.pdf"))
// .addAsResource(new File("src/test/resources/wcm-whiteboard.jpg"))
// .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml")
// .setManifest(new File("src/main/webapp/META-INF/MANIFEST.MF"));
//
// }
//
// @Resource(mappedName = "java:jboss/gatein-wcm")
// WCMRepositoryService repos;
//
// @Test
// public void performanceTextTest() {
//
// long start = System.currentTimeMillis();
// try {
// ExecutorService executor = Executors.newFixedThreadPool(NTHREADS, new WcmThreadFactory());
// for (int i = 0; i < NTESTS; i++) {
// WCMContentService cs = repos.createContentSession("sample", "default", "admin", "admin");
// Runnable worker = new WcmSmallWorker(i, cs);
// executor.execute(worker);
// }
// executor.shutdown();
// while (!executor.isTerminated()) {
// }
// } catch(Exception e) {
// log.error(e.getMessage());
// Assert.fail(e.getMessage());
// }
// long stop = System.currentTimeMillis();
// double total = ((double)(stop-start)/1000);
// double pertest = total / NTESTS;
// DecimalFormat df = new DecimalFormat("0.###");
//
// log.info( "[[ WcmSmallWriteTextTest # of operations " + NTESTS + " | # of threads " + NTHREADS +
// " | total time " + df.format(total) + " seconds " +
// " | time per operation " + df.format(pertest) + " seconds ]]");
//
// }
//
// public class WcmSmallWorker implements Runnable {
// private final int nTest;
//
// WCMContentService cs;
//
// WcmSmallWorker(int nTest, WCMContentService cs) {
// this.nTest = nTest;
// this.cs = cs;
// }
//
// @Override
// public void run() {
//
// try {
// log.debug( "WcmSmallWriteTextTest #" + nTest );
// cs.createTextContent("test" + nTest, "es", "/", WcmResources.HTML_ES);
// cs.createTextContent("test" + nTest, "en", "/", WcmResources.HTML_EN);
// cs.createTextContent("test" + nTest, "fr", "/", WcmResources.HTML_FR);
// cs.createTextContent("test" + nTest, "de", "/", WcmResources.HTML_DE);
//
// List<String> locales = cs.getContentLocales("/test" + nTest);
// if ( (!locales.contains("es")) ||
// (!locales.contains("en")) ||
// (!locales.contains("fr")) ||
// (!locales.contains("de"))
// ) {
// throw new Exception("Not locales in content");
// }
//
// // Cleaning test
// cs.deleteContent("/test" + nTest);
// cs.closeSession();
// } catch (Exception e) {
// log.error("WCM Small Test #" + nTest + " Failed " + e.getMessage());
// Assert.fail(e.getMessage());
// }
// }
//
// }
//
//
}
|
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
class TreeTraversal {
class TreeNode{
public TreeNode left;
public TreeNode right;
public int val;
public TreeNode(int val){
this.val = val;
}
}
public static void main(String[] args) {
TreeTraversal m = new TreeTraversal();
int[] nums = {1,2,3,4,5,6,7};
TreeNode root = m.buildBST(nums, 0, nums.length - 1);
preOrder(root);
System.out.println("\nRecursive PreOrder");
preOrder_r(root);
System.out.println("\nIterative InOrder");
inOrder(root);
System.out.println("\nIterative postOrder");
postOrder(root);
System.out.println("\nLevel Order");
levelOrder(root);
System.out.println("\nMorris InOrder");
morrisInOrder(root);
System.out.println("\nMorris PreOrder");
morrisPreOrder(root);
}
public TreeNode buildBST(int[] nums, int start, int end){
if(start > end){
return null;
}
int mid = (start + end)/2;
TreeNode node = new TreeNode(nums[mid]);
node.left = buildBST(nums, start, mid - 1);
node.right = buildBST(nums, mid + 1, end);
return node;
}
public static void preOrder(TreeNode root){
Stack<TreeNode> stack = new Stack<>();
if(root != null)stack.push(root);
while(!stack.isEmpty()){
TreeNode node = stack.pop();
System.out.print(node.val + " ");
if(node.right != null)stack.push(node.right);
if(node.left != null)stack.push(node.left);
}
}
public static void preOrder_r(TreeNode root){
if(root == null)return;
System.out.print(root.val + " ");
preOrder_r(root.left);
preOrder_r(root.right);
}
public static void inOrder(TreeNode root){
Stack<TreeNode> stack = new Stack<>();
while(!stack.isEmpty() || root != null){
if(root != null){
stack.push(root);
root = root.left;
}else{
root = stack.pop();
System.out.print(root.val + " ");
root = root.right;
}
}
}
public static void postOrder(TreeNode root){
Stack<TreeNode> stack = new Stack<>();
//p: 正在访问节点, q:刚刚访问过的节点
TreeNode p = root, q = null;
do{
while(p != null){//往左下
stack.push(p);
p = p.left;
}
q = null;//左下走不动了
while(!stack.isEmpty()){
p = stack.pop();//取一个出来看看
if(p.right == q){//右边没有或者已经访问过了
System.out.print(p.val + " ");
q = p;
}else{//现在不能访问,得再放进去,往右下走一步
stack.push(p);
p = p.right;
break;
}
}
}while(!stack.isEmpty());
}
public static void levelOrder(TreeNode root){
Queue<TreeNode> queue = new LinkedList<>();
if(root != null)queue.offer(root);
while(!queue.isEmpty()){
root = queue.poll();
System.out.print(root.val + " ");
if(root.left != null)queue.offer(root.left);
if(root.right != null)queue.offer(root.right);
}
}
public static void morrisInOrder(TreeNode root){
TreeNode cur = root, prev = null;
while(cur != null){
if(cur.left == null){
System.out.print(cur.val + " ");
prev = cur;
cur = cur.right;
}else{
//find precessor
TreeNode node = cur.left;
while(node.right != null && node.right != cur)node = node.right;
if(node.right == null){// not threaded yet
node.right = cur;
cur = cur.left;
}else{// has been threaded, visit cur and delete the thread
System.out.print(cur.val + " ");
node.right = null;
prev = cur;
cur = cur.right;
}
}
}
}
public static void morrisPreOrder(TreeNode root){
TreeNode prev = null;
TreeNode cur = root;
while(cur != null){
if(cur.left == null){
System.out.print(cur.val + " ");
prev = cur;
cur = cur.right;
}else{
TreeNode node = cur.left;
while(node.right != null && node.right != cur){
node = node.right;
}
if(node.right == null){
System.out.print(cur.val + " ");
node.right = cur;
prev = cur;
cur = cur.left;
}else{
node.right = null;
cur = cur.right;
}
}
}
}
} |
package fr.skytasul.quests.options;
import org.bukkit.entity.Player;
import fr.skytasul.quests.QuestsConfiguration;
import fr.skytasul.quests.api.options.OptionSet;
import fr.skytasul.quests.api.options.QuestOptionString;
import fr.skytasul.quests.utils.Lang;
import fr.skytasul.quests.utils.XMaterial;
public class OptionConfirmMessage extends QuestOptionString {
@Override
public void sendIndication(Player p) {
Lang.CONFIRM_MESSAGE.send(p);
}
@Override
public XMaterial getItemMaterial() {
return XMaterial.FEATHER;
}
@Override
public String getItemName() {
return Lang.customConfirmMessage.toString();
}
@Override
public String getItemDescription() {
return Lang.customConfirmMessageLore.toString();
}
@Override
public boolean shouldDisplay(OptionSet options) {
return QuestsConfiguration.questConfirmGUI();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.