text stringlengths 10 2.72M |
|---|
package fundamentos;
import java.util.ArrayList;
import java.util.Scanner;
public class Class27NombresArrayList {
public static void main(String[] args) {
Scanner teclado = new Scanner(System.in);
System.out.println("¿Cuantos nombres desea almacenar?");
String datonumero = teclado.nextLine();
int cantidad = Integer.parseInt(datonumero);
//CREAMOS UNA COLECCION PARA ALMACENAR NOMBRES
ArrayList<String> nombres = new ArrayList<>();
//LA UNICA FORMA DE HACER QUE NOMBRES TENGA MAS
//CAPACIDAD ES AÑADIR ELEMENTOS
//VAMOS A REALIZAR UN BUCLE QUE IRA DESDE 1 HASTA
//EL NUMERO DE ELEMENTOS QUE EL USUARIO QUIERA ALMACENAR
for (int i = 1; i <= cantidad; i++) {
System.out.println("Introduzca el nombre " + i);
String nombre = teclado.nextLine();
//ALMACENAMOS EL NOMBRE EN EL CONJUNTO (COLECCION)
nombres.add(nombre);
}
System.out.println("Nombres introducidos correctamente");
for (String nom : nombres) {
System.out.println(nom);
}
System.out.println("Fin de programa");
}
}
|
package structures;
/**
* Created by Administrator on 2015/10/6.
*/
public class InsPos {
int blockNum;
int blockOfs;
public InsPos() {blockNum = 0; blockOfs = 0;}
public int getBlockNum() {
return blockNum;
}
public int getBlockOfs() {
return blockOfs;
}
public void setBlockNum(int blockNum) {
this.blockNum = blockNum;
}
public void setBlockOfs(int blockOfs) {
this.blockOfs = blockOfs;
}
}
|
/**
* © All rights reserved for Group 1 - A copy and/or implementing of that class or any other class in this
* project without a written consent from Backbone nor Mr.Silver (known as QA), will results in a serious issue
* and will lead to further actions in court.
*
* @author Group 1
* @version 1.0
* @
*
* The Space_invadors3 class is used to create a game in which the user will be able to
* interact with the program using the java GUI interface.
*
* That particular class extending and implementing other classes such as JFrame or KeyListener,
* to construct a full functioning interactive game.
* */
/*
*
* Add a random number that will change the direction of the enemy each time.
*
* Add the music
*
* */
//import javax.swing.JProgressBar;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Iterator;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.*;
import java.applet.Applet;
import java.applet.AudioClip;
import java.net.URL;
public class Space_invadors3 extends JPanel implements KeyListener{//, Runnable {
//JProgressBar prg;
private static JFrame frame;
private Image background;
private ImageIcon deadMeat = new ImageIcon(this.getClass().getResource("Explosion.png")); // Add the explosion!!!!
private static final int NUM_OF_TARGETS_COL = 10;//Can't be less than 10
private static final int NUM_OF_TARGETS_ROW = 2;
private static final int NUM_OF_OBSTACLES = 7;
private int targetsVelocity = 0; // initial velocity of targets
private static int TARGET_LIVES = 1; // minimum life for the target
private static int TARGET_SPEED = 1; // minimum speed for the target
private Target[][] targets = new Target[NUM_OF_TARGETS_ROW][NUM_OF_TARGETS_COL]; // 2D array to hold more than 1 row of enemy
private Player player;
private static int PLAYER_LIVES = 10 ; // minimum life for the player
private Obstacle [] obstacles = new Obstacle[NUM_OF_OBSTACLES];
private boolean isAnyAlive = false; // Used with the player's bullets to determine if they are excited on the screen
private boolean isAnyAliveEnemy = false; // Used for the enemy's bullets
private boolean enemyAlive = false; // If the player didn't kill all the targets then a different menue will be shown
private URL enemyDie = Space_invadors3.class.getResource("Dying1.wav");
private URL playerDie = Space_invadors3.class.getResource("Dying2.wav");
private AudioClip enemyClip = Applet.newAudioClip(enemyDie);
private AudioClip playerClip = Applet.newAudioClip(playerDie);
/**
* The contractor of the class will instantiate the obstacle, target, Bullet and the player class in order to create full functioning game.
* Also, will create a new object for the background image.
*
* @param obstaclesIcon - Passing an image parameter to replace the default one for the obstacle view.
* @param enemyIcon - Passing an image parameter to replace the default one for the enemy view.
* @param playerIcon - Passing an image parameter to replace the default one for the player view.
* */
public Space_invadors3(ImageIcon obstaclesIcon,ImageIcon enemyIcon,ImageIcon playerIcon){
//enemyDie = Space_invadors3.class.getResource("Dying1.wav");
//enemyClip = Applet.newAudioClip(enemyDie);
/*
prg = new JProgressBar(0,100);
prg.setValue(100);
prg.setStringPainted(true);
prg.setEnabled(true);
add(prg);
//prg.setString("100");*/
setFocusable(true);
// Creates obstacles
int obstacleX = 25, lives = 5; // each brick has 5 lives
for (int i = 0; i < obstacles.length; i++, obstacleX += 100){
if(obstaclesIcon == null)
obstacles[i] = new Obstacle(null, obstacleX + 50, 500, lives);
else
obstacles[i] = new Obstacle(obstaclesIcon.getImage(), obstacleX + 50, 500, lives);
add(obstacles[i]);
}
// Create targets
int targetX = 0, targetY = 50;
for (int a = 0; a < NUM_OF_TARGETS_ROW; a++){
for (int i = 0; i < NUM_OF_TARGETS_COL; i++, targetX += 50){
if(enemyIcon == null)
targets[a][i] = new Target(null, targetX, targetY, TARGET_LIVES);
else
targets[a][i] = new Target(enemyIcon.getImage(), targetX, targetY, TARGET_LIVES);
add(targets[a][i]);
}
targetY += 50;
targetX = 0;
}
// Create the player:
if(playerIcon == null)
player = new Player(null, 350, 650, PLAYER_LIVES, 0);
else
player = new Player(playerIcon.getImage(), 350, 650, PLAYER_LIVES, 0);
add(player); // Adds player to the panel
this.addKeyListener(this); // Adds keyListener to the panel
// Add the background:
background = new ImageIcon(getClass().getResource("Background.jpg")).getImage();
}
/**
* The paint method is used to paint an object as a graphical user interface
*
* @param g - The specified graphic window
* */
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(background, 0, 0, getWidth(), getHeight(), null);
player.drawPlayer(g); // draws player on the screen
for (int i = 0; i < obstacles.length; i++) {
obstacles[i].drawObstacles(g); // draws obstacles on the screen
}
for(int a = 0; a < NUM_OF_TARGETS_ROW; a++){ // draws targets on the screen
for (int i = 0; i < NUM_OF_TARGETS_COL; i++) {
targets[a][i].drawTarget(g);
for (Iterator<Bullet> it = targets[a][i].bulletsE.iterator(); it.hasNext();/*NO arg*/) {
Bullet temp = it.next();
temp.drawBullet(g);
}
}
}
/*
for(int a = 0; a < NUM_OF_TARGETS_ROW; a++){ // draws targets on the screen
for (int i = 0; i < NUM_OF_TARGETS_COL; i++) {
for (Iterator<Bullet> it = targets[a][i].bulletsE.iterator(); it.hasNext();/*NO arg) {
Bullet temp = it.next();
temp.drawBullet(g);
}
}
}
*/
for (Iterator<Bullet> it = player.bulletsP.iterator(); it.hasNext();){// bullets.iterator()
Bullet b = it.next();
b.drawBullet(g); // draws bullets on the screen
}
g.dispose();
}
/**
* moveObjects method is used to move the objects on the screen, in this case the objects are the bullets.
* */
public void moveObjects() {
int moveY = 0; // A local variable to direct the enemy on the y-value, after the enemy reached every edge, it will go down ten levels.
/*
* The interface Iterator<E> takes a type (Bullet class in this case) and iterate among the elements inside an
* linked list.
*
* The "it" is a pointer pointing to the head of the list and as long that .iterator returns another element the for loop
* will continue
* */
for (Iterator<Bullet> it = player.bulletsP.iterator(); it.hasNext();/*NO arg*/) { // Draws the bullets fly up the screen (y decreases)
Bullet tempBullet = it.next(); // pull out Bullet objects from the list 1 at a time
isAnyAlive = tempBullet.isAlive ? true : false;
tempBullet.y = tempBullet.y - 13; // move the bullet 13 pixels up each repaint()
}
//----------------------------------------------------------------------------------------------------------------------------------
if (targets[0][NUM_OF_TARGETS_COL-1].x == 750) { // targets move in relation to the far right target
targetsVelocity = -1 * TARGET_SPEED; // targets move left
moveY = 10; // targets go down one row
}
else if (targets[0][NUM_OF_TARGETS_COL-1].x == 450) { // targets move in relation to the far right target
targetsVelocity = TARGET_SPEED; // targets move right
moveY = 10; // targets go down one row
}
//----------------------------------------------------------------------------------------------------------------------------------
for(int a = 0; a < NUM_OF_TARGETS_ROW; a++){
for (int i = 0; i < NUM_OF_TARGETS_COL; i++) {
//---------------------------------------------------------------------------------------
for (Iterator<Bullet> it = targets[a][i].bulletsE.iterator(); it.hasNext();/*NO arg*/) {
Bullet temp = it.next();
isAnyAliveEnemy = temp.isAlive ? true : false;
temp.y += 6;
}
//---------------------------------------------------------------------------------------
targets[a][i].x = targets[a][i].x + targetsVelocity; // move the targets to either left or right
targets[a][i].y = targets[a][i].y + moveY; // move the targets down
}
}
}
/**
* The anyHit method measuring the bullet and the target x and y axis to report if ther's a hit or not.
* */
public void anyHit() { // compares each bullet x,y to each target x,y
//-----------------------------THE PLAYER BULLET-------------------------------------------
for (Iterator<Bullet> it = player.bulletsP.iterator(); it.hasNext(); /*NO args*/){
Bullet tempBullet = it.next(); // pulling out 1 bullet object from the list at a time
if (tempBullet.isAlive) { // if bullet is still on the screen
//Check the position of the bullet corresponding to the target:
for(int a = 0; a < NUM_OF_TARGETS_ROW; a++){
for (int i = 0; i < NUM_OF_TARGETS_COL; i++) {
if (targets[a][i].isAlive) { //If the enemy is still in the game
boolean hit = false;
//Checking for matching locations:
if (tempBullet.x >= targets[a][i].x && tempBullet.x <= targets[a][i].x + 50 &&
tempBullet.y >= targets[a][i].y && tempBullet.y <= targets[a][i].y + 50)
hit = true; // If there is a hit then the variable will be change to true
if (hit) {//If the bullet hit the target:
tempBullet.isAlive = false;//The bullet is deleted from the screen
if(targets[a][i].lives > 0){//If the target had more than 0, subtract 1
targets[a][i].lives -= 1;
}
if(targets[a][i].lives == 0){// if target has 0 lives, delete the icon from the screen
targets[a][i].isAlive = false;
enemyClip.play();
}
}
}
if (tempBullet.isAlive && tempBullet.y <= 0) // if bullet flew off the screen without hitting any targets
tempBullet.isAlive = false;
}
}
//Check the position of the bullet corresponding to the obstacle:
for (int i = 0; i < obstacles.length; i++) {
boolean hit = false;
if (obstacles[i].isAlive) {
if (tempBullet.x >= obstacles[i].x && tempBullet.x <= obstacles[i].x + 55 &&
tempBullet.y >= obstacles[i].y && tempBullet.y <= obstacles[i].y + 30)
hit = true;
if (hit) {
tempBullet.isAlive = false;
obstacles[i].lives -= 1; // reduces the brick life by 1;
}
if (obstacles[i].lives == 0) {
obstacles[i].isAlive = false; // brick dies after 5 hits
}
}
}
}
}
//-----------------------------THE ENEMY BULLET-------------------------------------------
for(int a = 0; a < NUM_OF_TARGETS_ROW; a++){
for (int i = 0; i < NUM_OF_TARGETS_COL; i++) {
for (Iterator<Bullet> it = targets[a][i].bulletsE.iterator(); it.hasNext();/*NO arg*/) {
// Checking the position of the BULLET of EACH ENEMY:
Bullet temp = it.next();
if (temp.isAlive){
boolean hit = false;
//Check if one of the bullets of the enemy match the location of the player:
if (temp.x >= player.x && temp.x <= player.x + 50 &&
temp.y >= player.y && temp.y <= player.y + 50){
hit = true;
}
if (hit) {//If the bullet hit the Player:
temp.isAlive = false;//The enemy's bullet is deleted from the screen
if(player.lives > 0){//If the Player had more than 0, subtract 1
player.lives -= 1;
}
}
}
//If there was no hit:
if (temp.isAlive && temp.y >= 800){ // if bullet flew off the screen without hitting any targets
isAnyAliveEnemy = false;
temp.isAlive = false;
}
}
}
}
}
boolean isGameOver() { // Checks if alive targets are left
boolean gameOver = true;
Dead:
for(int a = 0; a < NUM_OF_TARGETS_ROW; a++){
for (int i = 0; i < NUM_OF_TARGETS_COL; i++) {
if (targets[a][i].isAlive){
gameOver = false;
//If the player didn't kill all the targets he/she automatically lose
if(targets[a][i].y == 500){
gameOver = true;
enemyAlive = true;
playerClip.play();
break Dead;
}
}
}
}
//ADD HERE THE CASE WHEN THE USER GOT KILLED BY THE ENEMY
if(player.lives == 0){
playerClip.play();
JOptionPane.showMessageDialog(null, "YOU'RE A DEAD MEAT!!!");
gameOver = true;
}
return gameOver;
}
@Override
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
if (code == KeyEvent.VK_RIGHT) {
if ( ! (player.x >= 750)) {
player.x = player.x + 10;
}
}
else if (code == KeyEvent.VK_LEFT) {
if ( ! (player.x <= 0)) {
player.x = player.x - 10;
}
}
else if (code == KeyEvent.VK_SPACE) { // releases a bullet each time SPACE pressed
if(!isAnyAlive){ // Checks that there is no bullets in the screen before shooting new one
Bullet bullet = new Bullet(player.x + 29, player.y + 0, 0); // Releases a bullet from where the player currently is
player.bulletsP.add(bullet); // add the bullet to the list of Bullets
add(bullet); // add the bullet to the screen
}
}
}
/*public void run() {
enemyShoot();
}*/
public void enemyShoot(){
for(int a = 0; a < NUM_OF_TARGETS_ROW; a++){
for (int i = 0; i < NUM_OF_TARGETS_COL; i++) {
if (targets[a][i].isAlive && !isAnyAliveEnemy) {// if there is an enemy at the corrent location AND there is no bullets on the screen from the enemy then:
Bullet enemyBullet = new Bullet(targets[a][i].x + 10, targets[a][i].y + 35, 1); // Releases a bullet from where the player currently is
targets[a][i].bulletsE.add(enemyBullet); // Add the bullet to the list of Bullets
add(enemyBullet); // Add the bullet to the screen
}
}
}
}
@Override public void keyTyped(KeyEvent e) {/*not in use*/}
@Override public void keyReleased(KeyEvent e) {/*not in use*/}
public static void playGame(Space_invadors3 obj){
frame = new JFrame();
frame.setTitle("Space Invaders Group 1");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 800);
frame.setResizable(false);
frame.setLocation(400, 100);
frame.add(obj);
frame.setVisible(true);
}
public static JComboBox startMenue(int firstLine){
if(firstLine == 1)
JOptionPane.showMessageDialog(null, "Hello player and wellcome! \n"+"Please choose a level of dificulty from the folowing menue");
String [] options = {"Grandma (Easy)", "Player (Mid)", "KILL ZONE (Hard)"};
JComboBox optionsMenue = new JComboBox(options);
optionsMenue.setEditable(true);
JOptionPane.showMessageDialog( null, optionsMenue, "SELECT YOUR LEVEL!", JOptionPane.QUESTION_MESSAGE);
return optionsMenue;
}
public static void main(String[] args) throws InterruptedException {
//Improving the basic java look and feel:
//DO NOT MOVE IT TO SOMEWHERE ELSE
try{UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());}
catch(Exception e){e.printStackTrace();}
URL mainURL = Space_invadors3.class.getResource("main_sound.wav");
AudioClip mainClip = Applet.newAudioClip(mainURL);
mainClip.loop();
JComboBox optionsMenue = startMenue(1);
switch(optionsMenue.getSelectedIndex()){
//No need for case 0, by default the life will be 1.
case 1:
{
TARGET_LIVES = 2;
TARGET_SPEED = 2;
break;
}
case 2:
{
TARGET_LIVES = 3;
TARGET_SPEED = 3;
break;
}
}
Space_invadors3 obj = new Space_invadors3(null,null,null);
playGame(obj);
while (true) {
obj.moveObjects();
obj.enemyShoot();
obj.anyHit();
Thread.sleep(20); // The game is very slow, must use 2 threads!
obj.repaint(); // This method call the paint (override) method by default
if (obj.isGameOver()){
if(!obj.enemyAlive){
int input = JOptionPane.showConfirmDialog(null, "WELL DONE!!! \nYou killed them all! \nWanna go for anouther round?!", "GOD BLESS AMERICA", 2);
/*IF THE PLAYER WON*/
if (input == 0){
JOptionPane.showMessageDialog(null, "YOU ARE THE MAN!!!\n" + "Select a difficulty level in the following menu\n" + "HAVE FUN!!!");
optionsMenue = startMenue(0);
switch(optionsMenue.getSelectedIndex()){
case 0:
{
TARGET_LIVES = 1;
TARGET_SPEED = 1;
break;
}
case 1:
{
TARGET_LIVES = 2;
TARGET_SPEED = 2;
break;
}
case 2:
{
TARGET_LIVES = 2;
TARGET_SPEED = 3;
break;
}
}
frame.dispose();//Closing the window
obj = new Space_invadors3(null,null,null); // Starting a new session
playGame(obj);
}
else{
JOptionPane.showMessageDialog(null, "See you next time!!");
mainClip.stop();
frame.dispose();//Closing the window
break;
}
}
/*IF THE PLAYER LOSE*/
else{
int input = JOptionPane.showConfirmDialog(null, "HEY GRANDPA! WHERE'S YOUR GLASSES?! Wanna try again?!", "Don't be a loser", 2);
if (input == 0){
JOptionPane.showMessageDialog(null, "DO YOUR BEST THIS TIME!\n" + "Select a difficulty level in the following menu");
optionsMenue = startMenue(0);
switch(optionsMenue.getSelectedIndex()){
case 0:
{
TARGET_LIVES = 1;
TARGET_SPEED = 1;
break;
}
case 1:
{
TARGET_LIVES = 2;
TARGET_SPEED = 2;
break;
}
case 2:
{
TARGET_LIVES = 3;
TARGET_SPEED = 3;
break;
}
}
frame.dispose();//Closing the window
obj = new Space_invadors3(null,null,null); // Starting a new session
playGame(obj);
}
else{
JOptionPane.showMessageDialog(null, "Tutoring sessions are in room N3029, good luck!");
mainClip.stop();
frame.dispose();//Closing the window
break;
}
}
}
}
}
}
|
package com.myflappybird.ui;
import com.myflappybird.dto.GameDto;
import javax.swing.*;
public class GameFrame extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* Frame宽度
*/
private static final int FRAME_WIDTH = 650;
/**
* Frame高度
*/
private final int FRAME_HEIGHT = 650;
/**
* FrameX坐标
*/
private final int FRAME_X = 350;
/**
* FrameY坐标
*/
private final int FRAME_Y = 50;
/**
* 游戏线程
*/
Thread gamethread;
/**
* 游戏panel
*/
GamePanel gamepanel;
/**
* 数据传输层
*/
GameDto dto;
public GameFrame(GamePanel gamepanel, GameDto dto) {
this.gamepanel = gamepanel;
this.dto = dto;
// 设置pan内容
this.setContentPane(gamepanel);
// 设置位置
this.setLocation(FRAME_X, FRAME_Y);
// frame大小
this.setSize(FRAME_WIDTH, FRAME_HEIGHT);
// 标题
this.setTitle("锟斤拷锟斤拷锟斤拷小锟斤拷");
// 是否大小可调节
this.setResizable(false);
// 关闭按钮
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
// 是否课件
this.setVisible(true);
// 刷新线程
this.reFleshThread();
}
/**
* 刷新画面
*/
public void reFleshThread() {
gamethread = new Thread() {
// 多线程
public void run() {
while (true) {
try {
Thread.sleep(50);
gamepanel.repaint();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
//锟斤拷锟斤拷锟竭筹拷
gamethread.start();
}
}
|
class Solution {
public boolean isMonotonic(int[] A) {
int inc=1;
int dec=1;
for(int i=1; i<A.length; i++){
if(A[i] - A[i-1] > 0)
inc++;
else if(A[i] - A[i-1] < 0)
dec++;
else {
inc++; dec++;
}
}
return inc == A.length || dec == A.length;
}
}
|
package com.example.benchmark.dao;
import com.example.benchmark.model.Version;
import com.example.benchmark.model.Query;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
import java.util.Optional;
public interface VersionRepository extends JpaRepository<Version, Long> {
List<Version> findByQuery(Query query);
List<Version> findByQueryOrderByCreatedDesc(Query query);
List<Version> findByQueryOrderByCreatedDesc(Query query, Pageable pageable);
} |
package com.zzl.monitoring.station;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.RelativeSizeSpan;
import android.util.Log;
import android.widget.TextView;
import com.zzl.monitoring.station.serialport.ComData;
import com.zzl.monitoring.station.serialport.Packet;
import com.zzl.monitoring.station.serialport.RealtimeData;
import com.zzl.monitoring.station.serialport.SerialPortHandler;
import com.zzl.monitoring.station.widget.AirMoistureChart;
import com.zzl.monitoring.station.widget.AirTemperatureChart;
import com.zzl.monitoring.station.widget.SimpleTotalRadiationChart;
import com.zzl.monitoring.station.widget.WindDirectionView;
import com.zzl.serialport.MyFunc;
import com.zzl.serialport.SerialPortClient;
import com.zzl.serialport.SerialPortManager;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Locale;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity
implements Handler.Callback, SerialPortHandler.Callback {
private TextView mainTitleText, pressureText, ultravioletRaysText, pmText, windSpeedText;
private AirTemperatureChart airTempChart;
private AirMoistureChart airMoistureChart;
private SimpleTotalRadiationChart simpleRadiationChart;
private WindDirectionView windDirView;
private SerialPortClient client;
private Handler handler = new Handler(this);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainTitleText = findViewById(R.id.mainTitleText);
pressureText = findViewById(R.id.pressureText);
ultravioletRaysText = findViewById(R.id.ultravioletRaysText);
pmText = findViewById(R.id.pmText);
windSpeedText = findViewById(R.id.windSpeedText);
windDirView = findViewById(R.id.windDirectionView);
airTempChart = findViewById(R.id.airTempChart);
airMoistureChart = findViewById(R.id.airMoistureChart);
simpleRadiationChart = findViewById(R.id.simpleRadiationChart);
handler.sendEmptyMessageDelayed(0, 1000);
}
@Override
protected void onPostCreate(@Nullable Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mainTitleText.setText(buildMainTitleSpannable());
pressureText.setText(buildItemSpannable(R.string.format_pressure, 0));
ultravioletRaysText.setText(buildItemSpannable(R.string.format_ultraviolet_rays, 0));
pmText.setText(buildItemSpannable(R.string.format_pm, 0));
initSerialPort();
}
private void initSerialPort() {
client = SerialPortManager.get()
.setPort("/dev/ttyS1")
.setBaudRate(9600)
.setDataHandler(new SerialPortHandler(this))
.create();
client.open();
client.post(Packet.getRealtimeDateCMD());
}
private void addEntry() {
airTempChart.addEntry((float) (Math.random() * 40));
airMoistureChart.addEntry((float) (Math.random() * 40));
simpleRadiationChart.addEntry((float) (Math.random() * 40));
}
@Override
public boolean handleMessage(Message msg) {
client.post(Packet.getRealtimeDateCMD());
// addEntry();
handler.sendEmptyMessageDelayed(0, 1000);
return true;
}
private SpannableStringBuilder buildItemSpannable(int resId, float value) {
String text = getString(resId, value);
SpannableStringBuilder builder = new SpannableStringBuilder(text);
int start = text.indexOf(" ") + 1;
RelativeSizeSpan size = new RelativeSizeSpan(.5f);
builder.setSpan(size, start, text.length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
return builder;
}
private SpannableStringBuilder buildMainTitleSpannable() {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd E hh:mm", Locale.CHINA);
String text = getString(R.string.format_main_title_text, format.format(new Date()));
SpannableStringBuilder builder = new SpannableStringBuilder(text);
int start = text.indexOf("\n") + 1;
RelativeSizeSpan size = new RelativeSizeSpan(.6f);
builder.setSpan(size, start, text.length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
return builder;
}
@Override
public void onReceivedData(ComData bean) {
// parseReceiveDate(bean);
RealtimeData data = Packet.parseRealtimeResp(bean.bRec);
Log.e("PortTest-->", Arrays.toString(data.getChannel()));
windSpeedText.setText(getString(R.string.format_wind_speed_text, data.getChannel(Channel.WIND_SPEED) / 10f));
windDirView.setDirection(data.getChannel(Channel.WIND_DIR));
pressureText.setText(buildItemSpannable(R.string.format_pressure,data.getChannel(Channel.PRESSURE)));
airTempChart.addEntry(data.getChannel(Channel.TEMPERATURE));
airMoistureChart.addEntry(data.getChannel(Channel.MOISTURE));
simpleRadiationChart.addEntry(data.getChannel(Channel.SIMPLE_TOTAL_RADIATION));
ultravioletRaysText.setText(buildItemSpannable(R.string.format_ultraviolet_rays, data.getChannel(Channel.U_RAY) / 100f));
}
private String parseReceiveDate(ComData bean) {
String hex = MyFunc.ByteArrToHex(bean.bRec);
Log.e("PortTest-->", "onReceivedData: " + hex);
return hex;
}
@Override
protected void onStop() {
super.onStop();
if (isFinishing() && client != null) {
client.close();
}
}
}
|
package testThread;
public class Thread2 implements Runnable {
public volatile static int j;
public Thread2(int j) {
this.j = j;
}
// public int getJ() {
// return j;
// }
//
// public void setJ(int j) {
// this.j = j;
// }
public void run() {
// while (true){
j = j * j;
// break;
// }
}
}
|
package com.test.qa.pageobjects.pages;
import com.test.qa.pageobjects.utils.PageBase;
import org.apache.log4j.Logger;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;
public class UserPage extends PageBase {
private static final Logger LOGGER = Logger.getLogger(LoginPage.class);
public static By hdrUser=By.id("menu_admin_viewSystemUsers");
public static By txtSerchUsername=By.id("searchSystemUser_userName");
public static By txtSerchEmployeename=By.xpath("//*[@id=\"searchSystemUser_employeeName_empName\"]");
public static By UserROle=By.id("searchSystemUser_userType");
public static By btnSearch=By.id("searchBtn");
public static By Status=By.id("searchSystemUser_status");
public static By btnReset=By.id("resetBtn");
public static By btnAdd=By.xpath("//*[@id=\"btnAdd\"]");
public static By btnDelete=By.id("btnDelete");
public static By tableAdmin= By.xpath("//a[text()=\"test121\"]");
public static By msgInvalidSearch=By.xpath("//*[@colspan=\"5\"]");
public static By checkbox=By.xpath("//*[@type=\"checkbox\"]");
public static By AdduName=By.xpath("//a[text()=\"thusya121\"]");
public static boolean isAdminPageDisplayed(){
return getDriver().findElement(btnSearch).isDisplayed();
}
public static String getInvalidSearchMsg(){
return getDriver().findElement(msgInvalidSearch).getText();
}
public static void clickUser(){
getDriver().findElement(hdrUser).click();
}
public static void clickAdd(){
getDriver().findElement(btnAdd).click();
}
public static void clickDelete(){
getDriver().findElement(btnDelete).click();
}
public static void setUsername(String username){
getDriver().findElement(txtSerchUsername).sendKeys(username);
}
public static void setEmplname(String empName){
getDriver().findElement(txtSerchEmployeename).sendKeys(empName);
}
public static void clickSearch(){
getDriver().findElement(btnSearch).click();
}
public static void waittillAdminPageLoad() {
waiTillVisible(tableAdmin, 2);
}
public static String getUsername(){
return getDriver().findElement(tableAdmin).getText();
}
public static String getRoleSelection(){
Select option = new Select(getDriver().findElement(UserROle));
return option.getFirstSelectedOption().getText();
}
public static void setRoleSelection(String role){
Select option = new Select(getDriver().findElement(UserROle));
option.selectByVisibleText(role);
}
public static String getStatusSelection(){
Select option = new Select(getDriver().findElement(Status));
return option.getFirstSelectedOption().getText();
}
public static void setStatusSelection(String status){
Select option = new Select(getDriver().findElement(Status));
option.selectByVisibleText(status);
}
public static void checkCheckBox() {
WebElement Checkbox = getDriver().findElement(checkbox);
if (!Checkbox.isSelected())
Checkbox.click();
}
public static void unCheckCheckBox() {
WebElement Checkbox = getDriver().findElement(checkbox);
if (Checkbox.isSelected())
Checkbox.click();
}
public static boolean isCheckBoxChecked() {
return getDriver().findElement(checkbox).isSelected();
}
public static String getAddData(){
return getDriver().findElement(AdduName).getText();
}
}
|
import info.gridworld.actor.ActorWorld;
import info.gridworld.actor.Bug;
import info.gridworld.grid.Location;
import info.gridworld.grid.UnboundedGrid;
import java.awt.Color;
class ibug extends Bug
{
int steps=0;
public ibug()
{
//face down
setDirection(180);
}
public void act()
{
if( steps < 5 )
{
move();
steps++;
}
}
}
class ibug2 extends Bug
{
int steps=0;
public ibug2()
{
//face down
setDirection(180);
}
public void act()
{
if( steps < 0 )
{
move();
steps++;
}
}
}
class vbug extends Bug
{
int steps=0;
/**
* Constructor
*/
public vbug()
{
//face down
setDirection(135);
}
public void act()
{
//draw vertical line
if( steps < 5 )
{
move();
steps++;
}
//change direction
if( steps == 5 )
{
setDirection(45);
}
if( steps >= 5 && steps < 10)
{
move();
steps++;
}
}
}
class xbug extends Bug
{
int steps=0;
/**
* Constructor
*/
public xbug()
{
//face down
setDirection(135);
}
public void act()
{
//draw vertical line
if( steps < 5 )
{
move();
steps++;
}
}
}
class xbug2 extends Bug
{
int steps=0;
/**
* Constructor
*/
public xbug2()
{
//face down
setDirection(225);
}
public void act()
{
//draw vertical line
if( steps < 5 )
{
move();
steps++;
}
}
}
class Lbug1 extends Bug
{
int steps=0;
/**
* Constructor
*/
public Lbug1()
{
//face down
setDirection(180);
}
/**
* Does something when step is pressed.
*/
public void act()
{
//draw vertical line
if( steps < 5 )
{
move();
steps++;
}
//change direction
if( steps == 5 )
{
setDirection(90);
}
//draw bottom line
if( steps >= 5 && steps < 7)
{
move();
steps++;
}
}
}
public class Proj_11_1 {
public static void main(String[] args)
{
//setup vBug
vbug bug1 = new vbug();
bug1.setColor(Color.BLUE);
Location bug1location = new Location(1, 1);
//setup xbug
xbug bug2 =new xbug();
bug2.setColor(Color.RED);
Location bug2location =new Location(10,1);
//setup xbug
xbug2 bug6 =new xbug2();
bug6.setColor(Color.RED);
Location bug6location =new Location(10,6);
//set L bug
Lbug1 bug3 = new Lbug1();
bug3.setColor(Color.GREEN);
Location bug3location = new Location(20, 1);
//set i bug
ibug bug4 = new ibug();
bug4.setColor(Color.YELLOW);
Location bug4location = new Location(32, 1);
//set i bug2
ibug2 bug5 = new ibug2();
bug5.setColor(Color.YELLOW);
Location bug5location = new Location(30, 1);
//setup Grid
UnboundedGrid myGrid = new UnboundedGrid();
//setup World
ActorWorld world = new ActorWorld(myGrid);
world.add(bug1location, bug1);
world.show();
world.add(bug2location, bug2);
world.add(bug3location, bug3);
world.add(bug4location, bug4);
world.add(bug5location, bug5);
world.add(bug6location, bug6);
}
}
|
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
/*
* I method reference possono essere applicati a 4 tipi di metodo
*/
public class Main {
public static void main(String[] args) {
Consumer<String> consumer1 = s -> System.out.println(s);
// metodi statici
Consumer<String> consumer2 = System.out::println;
class Example {
public Example() {
}
public Example(Integer integer) {
}
}
Supplier<Example> supplier1 = () -> new Example();
// costruttore senza argomenti
Supplier<Example> supplier2 = Example::new;
Function<Integer, Example> function1 = integer -> new Example(integer);
// costruttore con argomento
Function<Integer, Example> function2 = Example::new;
Function<String, String> supplier3 = s -> s.toLowerCase();
// metodo di istanza del tipo di oggetto
Function<String, String> supplier4 = String::toLowerCase;
Integer integer = 10;
Supplier<String> supplier5 = () -> integer.toString();
// metodo di istanza di un oggetto specifico
Supplier<String> supplier6 = integer::toString;
}
}
|
package personproject;
import java.util.Date;
public class Person {
public static int lastId = 0;
private String name;
private String gender;
private String address;
private int idNumber;
private Date dateOfBirth;
//constructor method with no arguments
public Person() {
address = "";
}
//constructor method with 3 String, 1 Date arguments
public Person(String name, String gender, String address, Date d) {
super();
this.name = name;
this.gender = gender;
this.address = address;
this.dateOfBirth = d;
lastId++;
this.idNumber = lastId;
}
public String getName() {
return name;
}
public void setName(String n) {
this.name = n;
}
public String getGender() {
return gender;
}
public void setGender(String g) {
this.gender = g;
}
public String getAddress() {
return address;
}
public void setAddress(String a) {
this.address = a;
}
public Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date d) {
this.dateOfBirth = d;
}
public String toString() {
return "Person [name=" + name + ", gender=" + gender + ", DOB=" + dateOfBirth
+ ", address=" + address + ", idNumber=" + idNumber + "]";
}
// return the person's age in years
public int age(){
int a = 0;
// finish coding this method
return a;
}
public boolean isHomeless() {
if (address.length() == 0) {
return true;
} else {
return false;
}
}
// check if two Person objects have similiar attribute values
// Ignore case when comparing attributes
public boolean isSimiliarTo(Person peep) {
boolean areTheyEqual = true;
if (!this.address.equalsIgnoreCase(peep.address)) {
areTheyEqual = false;
}
if (!this.name.equalsIgnoreCase(peep.name)) {
areTheyEqual = false;
}
if (!this.gender.equalsIgnoreCase(peep.gender)) {
areTheyEqual = false;
}
return areTheyEqual;
}
public boolean equals(Person p) {
if ((this.idNumber == p.idNumber) && (this.address.equals(p.address)) && (this.name.equals(p.name)) && (this.gender.equals(p.gender))) {
return true;
} else {
return false;
}
}
public static int numberOfPeople() {
return lastId;
}
}
|
package com.giga.service;
import org.springframework.stereotype.Service;
@Service
public class Email implements IEmail{
@Override
public String validate(String email) {
String regex = "^\\w+@\\w+\\.\\w{2,3}$";
String result = "not match";
if (email.matches(regex)) result = "match";
return result;
}
}
|
package Ex_55;
public class Employee {
private int INN;
private String firstName;
private String secondName;
private double salary;
final private double bonus = 0;
private final String position = "noob";
public String getPosition() {
return position;
}
public double getBonus() {
return salary*bonus;
}
public int getINN() {
return INN;
}
public void setINN(int iNN) {
INN = iNN;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getSecondName() {
return secondName;
}
public void setSecondName(String secondName) {
this.secondName = secondName;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public String getName(){
String name = getFirstName().charAt(0) + ". " + getSecondName();
return name;
}
public String transformData(int data){
String transformed = data + "";
return transformed;
}
public String transformData(double data){
String transformed = data + "";
return transformed;
}
public double getFullSalary() {
return (salary*bonus + salary);
}
public void setEmployee(int INN, String firstName, String secondName, double salary){
setINN(INN);
setFirstName(firstName);
setSecondName(secondName);
setSalary(salary);
}
public void prLine(){}
public Employee(){}
} |
package com.ospavliuk.springboottest.service;
import com.ospavliuk.springboottest.model.StackoverflowWebsite;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@Service
public class StackoverflowService {
private static List<StackoverflowWebsite> items = new ArrayList<>();
static{
items.add(new StackoverflowWebsite("stackoverflow","http://stackoverflow.com",
"http://cdn.sstatic.net/Sites/stackoverflow/img/favicon.ico","Stack Overflow (StackExchange)",
"for professional and enthusiast programmers"));
items.add(new StackoverflowWebsite("serverfault","http://serverfault.com",
"http://cdn.sstatic.net/Sites/serverfault/img/favicon.ico","Server Fault (StackExchange)",
"for for system and network administrators"));
items.add(new StackoverflowWebsite("superuser","http://superuser.com",
"http://cdn.sstatic.net/Sites/superuser/img/favicon.ico","Super User (StackExchange)",
"for computer enthusiast and power users"));
items.add(new StackoverflowWebsite("askubuntu","http://askubuntu.com",
"http://cdn.sstatic.net/Sites/askubuntu/img/favicon.ico","Ask Ubuntu (StackExchange)",
"for Ubuntu users and developers"));
items.add(new StackoverflowWebsite("apple","http://apple.stackexchange.com",
"http://cdn.sstatic.net/Sites/apple/img/favicon.ico","Ask Different (StackExchange)",
"for power users of Apple hardware and software"));
items.add(new StackoverflowWebsite("android","http://android.stackexchange.com",
"http://cdn.sstatic.net/Sites/android/img/favicon.ico","Android Enthusiasts (StackExchange)",
"for enthusiast and power users of the Android operating system"));
items.add(new StackoverflowWebsite("ru.stackoverflow","http://ru.stackoverflow.com",
"http://cdn.sstatic.net/Sites/ru/img/favicon.ico","Stack Overflow на русском (StackExchange)",
"для программистов"));
}
public List<StackoverflowWebsite> findAll() {
return items;
}
}
|
public class Main{
public static void main(String[] args){
main<int,int>length=new main <int,int>(size);
length.put("");
System.out.println(main.size(""));
}
Capacity<x> cap=main.list().Capacity();
while(cap.top()){
System.out.println(cap.max());
}
get<x> val=main.val();
for(x num: val){
System.out.println(num);
}
Collection<y> a=main.values();
for(y value :a){
System.out.println(value);
main.containsvalues();
}
Collection<y> a=main.num();
for(y num :a){
System.out.println(num);
main.con();
}
Set<put<x, y>> map=main.map();
for(put<x, y> put:map){
System.out.println(put);
}
} |
/*
* [y] hybris Platform
*
* Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* ("Confidential Information"). You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the
* license agreement you entered into with SAP.
*/
package de.hybris.platform.commerceservices.order.hook.impl;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import de.hybris.bootstrap.annotations.UnitTest;
import de.hybris.platform.commerceservices.enums.QuoteAction;
import de.hybris.platform.commerceservices.enums.QuoteUserType;
import de.hybris.platform.commerceservices.order.exceptions.IllegalQuoteStateException;
import de.hybris.platform.commerceservices.order.strategies.QuoteActionValidationStrategy;
import de.hybris.platform.commerceservices.order.strategies.QuoteUserIdentificationStrategy;
import de.hybris.platform.commerceservices.order.strategies.QuoteUserTypeIdentificationStrategy;
import de.hybris.platform.commerceservices.service.data.CommerceCartMetadataParameter;
import de.hybris.platform.core.model.order.CartModel;
import de.hybris.platform.core.model.order.QuoteModel;
import de.hybris.platform.core.model.user.UserModel;
import de.hybris.platform.servicelayer.time.TimeService;
import java.util.Calendar;
import java.util.Date;
import java.util.Optional;
import org.apache.commons.lang.time.DateUtils;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
@UnitTest
@RunWith(MockitoJUnitRunner.class)
public class QuoteCommerceCartMetadataUpdateValidationHookTest
{
@InjectMocks
public QuoteCommerceCartMetadataUpdateValidationHook quoteCommerceCartMetadataUpdateValidationHook = new QuoteCommerceCartMetadataUpdateValidationHook();
@Mock
private QuoteActionValidationStrategy quoteActionValidationStrategy;
@Mock
private QuoteUserIdentificationStrategy quoteUserIdentificationStrategy;
@Mock
private QuoteUserTypeIdentificationStrategy quoteUserTypeIdentificationStrategy;
@Mock
private TimeService timeService;
@Mock
private CommerceCartMetadataParameter metadataParameter;
@Mock
private CartModel cartModel;
@Mock
private QuoteModel cartQuoteModel;
@Mock
private UserModel quoteUser;
@Before
public void setup()
{
given(cartModel.getCode()).willReturn("00000001");
given(cartQuoteModel.getCode()).willReturn("00000001");
given(cartModel.getQuoteReference()).willReturn(cartQuoteModel);
given(quoteUserIdentificationStrategy.getCurrentQuoteUser()).willReturn(quoteUser);
given(metadataParameter.getCart()).willReturn(cartModel);
}
@Test
public void shouldNotUpdateWhenQuotReferenceNull()
{
given(cartModel.getQuoteReference()).willReturn(null);
quoteCommerceCartMetadataUpdateValidationHook.beforeMetadataUpdate(metadataParameter);
verify(quoteUserIdentificationStrategy, never()).getCurrentQuoteUser();
verify(quoteActionValidationStrategy, never()).validate(any(), any(), any());
}
@Test(expected = IllegalQuoteStateException.class)
public void shouldNotUpdateWhenActionValidationFails()
{
doThrow(new IllegalQuoteStateException(QuoteAction.SAVE, null, null, null)).when(quoteActionValidationStrategy)
.validate(QuoteAction.SAVE, cartQuoteModel, quoteUser);
quoteCommerceCartMetadataUpdateValidationHook.beforeMetadataUpdate(metadataParameter);
}
@Test(expected = IllegalArgumentException.class)
public void shouldNotUpdateWhenQuoteUserTypeCanNotBeDetermined()
{
given(quoteUserTypeIdentificationStrategy.getCurrentQuoteUserType(quoteUser)).willReturn(Optional.empty());
quoteCommerceCartMetadataUpdateValidationHook.beforeMetadataUpdate(metadataParameter);
}
@Test(expected = IllegalArgumentException.class)
public void shouldValidateExpirationTimeForBuyer()
{
given(quoteUserTypeIdentificationStrategy.getCurrentQuoteUserType(quoteUser)).willReturn(Optional.of(QuoteUserType.BUYER));
given(metadataParameter.getExpirationTime()).willReturn(Optional.of(DateUtils.addDays(new Date(), 1000)));
quoteCommerceCartMetadataUpdateValidationHook.beforeMetadataUpdate(metadataParameter);
}
@Test(expected = IllegalArgumentException.class)
public void shouldValidateRemoveExpirationTimeForBuyer()
{
given(quoteUserTypeIdentificationStrategy.getCurrentQuoteUserType(quoteUser)).willReturn(Optional.of(QuoteUserType.BUYER));
given(metadataParameter.getExpirationTime()).willReturn(Optional.empty());
given(Boolean.valueOf(metadataParameter.isRemoveExpirationTime())).willReturn(Boolean.TRUE);
quoteCommerceCartMetadataUpdateValidationHook.beforeMetadataUpdate(metadataParameter);
}
@Test(expected = IllegalArgumentException.class)
public void shouldValidateExpirationTimeForSeller()
{
given(quoteUserTypeIdentificationStrategy.getCurrentQuoteUserType(quoteUser)).willReturn(Optional.of(QuoteUserType.SELLER));
given(timeService.getCurrentDateWithTimeNormalized()).willReturn(DateUtils.truncate(new Date(), Calendar.DATE));
given(metadataParameter.getExpirationTime()).willReturn(Optional.of(DateUtils.addDays(new Date(), -100)));
quoteCommerceCartMetadataUpdateValidationHook.beforeMetadataUpdate(metadataParameter);
}
@Test(expected = IllegalArgumentException.class)
public void shouldValidateNameForSeller()
{
given(quoteUserTypeIdentificationStrategy.getCurrentQuoteUserType(quoteUser)).willReturn(Optional.of(QuoteUserType.SELLER));
given(timeService.getCurrentDateWithTimeNormalized()).willReturn(DateUtils.truncate(new Date(), Calendar.DATE));
given(metadataParameter.getExpirationTime()).willReturn(Optional.of(DateUtils.addDays(new Date(), 1000)));
given(metadataParameter.getName()).willReturn(Optional.of("myQuoteName"));
quoteCommerceCartMetadataUpdateValidationHook.beforeMetadataUpdate(metadataParameter);
}
@Test(expected = IllegalArgumentException.class)
public void shouldValidateDescriptionForSeller()
{
given(quoteUserTypeIdentificationStrategy.getCurrentQuoteUserType(quoteUser)).willReturn(Optional.of(QuoteUserType.SELLER));
given(timeService.getCurrentDateWithTimeNormalized()).willReturn(DateUtils.truncate(new Date(), Calendar.DATE));
given(metadataParameter.getExpirationTime()).willReturn(Optional.of(DateUtils.addDays(new Date(), 1000)));
given(metadataParameter.getName()).willReturn(Optional.empty());
given(metadataParameter.getDescription()).willReturn(Optional.of("myQuoteName"));
quoteCommerceCartMetadataUpdateValidationHook.beforeMetadataUpdate(metadataParameter);
}
@Test(expected = IllegalArgumentException.class)
public void shouldValidateSellerApprover()
{
given(quoteUserTypeIdentificationStrategy.getCurrentQuoteUserType(quoteUser))
.willReturn(Optional.of(QuoteUserType.SELLERAPPROVER));
quoteCommerceCartMetadataUpdateValidationHook.beforeMetadataUpdate(metadataParameter);
}
@Test
public void shouldValidateBuyer()
{
given(quoteUserTypeIdentificationStrategy.getCurrentQuoteUserType(quoteUser)).willReturn(Optional.of(QuoteUserType.BUYER));
given(metadataParameter.getExpirationTime()).willReturn(Optional.empty());
given(Boolean.valueOf(metadataParameter.isRemoveExpirationTime())).willReturn(Boolean.FALSE);
quoteCommerceCartMetadataUpdateValidationHook.beforeMetadataUpdate(metadataParameter);
}
@Test
public void shouldValidateSeller()
{
given(quoteUserTypeIdentificationStrategy.getCurrentQuoteUserType(quoteUser)).willReturn(Optional.of(QuoteUserType.SELLER));
given(timeService.getCurrentDateWithTimeNormalized()).willReturn(DateUtils.truncate(new Date(), Calendar.DATE));
given(metadataParameter.getExpirationTime()).willReturn(Optional.of(DateUtils.addDays(new Date(), 1000)));
given(metadataParameter.getName()).willReturn(Optional.empty());
given(metadataParameter.getDescription()).willReturn(Optional.empty());
quoteCommerceCartMetadataUpdateValidationHook.beforeMetadataUpdate(metadataParameter);
}
}
|
package com.tencent.mm.plugin.downloader.a;
public interface d extends com.tencent.mm.kernel.b.d {
}
|
package com.farald.DocumentRepresentation;
import com.farald.Parser.ParserRule;
import java.util.List;
public class BillFragmentWithRules {
public final BillFragment billFragment;
public final List<ParserRule> parserRules;
public final int startPosition; //Required to separate actual content from things to parse
public BillFragmentWithRules(BillFragment billFragment, List<ParserRule> parserRules, int startPosition) {
this.billFragment = billFragment;
this.parserRules = parserRules;
this.startPosition = startPosition;
}
}
|
/*
* Copyright (C) 2020-2023 Hedera Hashgraph, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hedera.mirror.monitor.publish.generator;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.from;
import static org.assertj.core.api.Assertions.withinPercentage;
import com.google.common.base.Stopwatch;
import com.google.common.base.Suppliers;
import com.google.common.collect.HashMultiset;
import com.google.common.collect.Multiset;
import com.hedera.mirror.monitor.ScenarioStatus;
import com.hedera.mirror.monitor.publish.PublishProperties;
import com.hedera.mirror.monitor.publish.PublishRequest;
import com.hedera.mirror.monitor.publish.PublishScenario;
import com.hedera.mirror.monitor.publish.PublishScenarioProperties;
import com.hedera.mirror.monitor.publish.transaction.TransactionType;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import org.apache.commons.math3.util.Pair;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
class CompositeTransactionGeneratorTest {
private PublishScenarioProperties publishScenarioProperties1;
private PublishScenarioProperties publishScenarioProperties2;
private PublishProperties properties;
private Supplier<CompositeTransactionGenerator> supplier;
private double totalTps;
@BeforeEach
void init() {
publishScenarioProperties1 = new PublishScenarioProperties();
publishScenarioProperties1.setName("test1");
publishScenarioProperties1.setProperties(Map.of("topicId", "0.0.1000"));
publishScenarioProperties1.setTps(750);
publishScenarioProperties1.setType(TransactionType.CONSENSUS_SUBMIT_MESSAGE);
totalTps = publishScenarioProperties1.getTps();
publishScenarioProperties2 = new PublishScenarioProperties();
publishScenarioProperties2.setName("test2");
publishScenarioProperties2.setTps(250);
publishScenarioProperties2.setType(TransactionType.ACCOUNT_CREATE);
totalTps += publishScenarioProperties2.getTps();
properties = new PublishProperties();
properties.getScenarios().put(publishScenarioProperties1.getName(), publishScenarioProperties1);
properties.getScenarios().put(publishScenarioProperties2.getName(), publishScenarioProperties2);
supplier = Suppliers.memoize(() -> new CompositeTransactionGenerator(
p -> p,
p -> p.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)),
properties));
prepare();
}
@ParameterizedTest(name = "batch request count {0}")
@ValueSource(ints = {0, -1})
void batchRequestDefault(int count) {
CompositeTransactionGenerator generator = supplier.get();
List<PublishRequest> publishRequests = generator.next(count);
assertThat(publishRequests).hasSize(generator.batchSize.get());
}
@Test
void batchRequestTwo() {
CompositeTransactionGenerator generator = supplier.get();
List<PublishRequest> publishRequests = generator.next(2);
assertThat(publishRequests).hasSize(2);
}
@Test
void batchRequestGreaterThanDefault() {
CompositeTransactionGenerator generator = supplier.get();
int count = generator.batchSize.get() + 1;
List<PublishRequest> publishRequests = generator.next(count);
assertThat(publishRequests).hasSize(count);
}
@Test
void distribution() {
properties.setWarmupPeriod(Duration.ZERO);
CompositeTransactionGenerator generator = supplier.get();
assertThat(generator.distribution.get().getPmf())
.hasSize(properties.getScenarios().size())
.extracting(Pair::getValue)
.containsExactly(0.75, 0.25);
Multiset<TransactionType> types = HashMultiset.create();
double seconds = 5;
for (int i = 0; i < totalTps * seconds; ) {
List<PublishRequest> requests = generator.next();
requests.stream()
.map(r -> r.getScenario().getProperties().getType())
.forEach(types::add);
i += requests.size();
}
for (PublishScenarioProperties publishScenarioProperties :
properties.getScenarios().values()) {
assertThat(types.count(publishScenarioProperties.getType()))
.isNotNegative()
.isNotZero()
.isCloseTo((int) (publishScenarioProperties.getTps() * seconds), withinPercentage(10));
}
}
@Test
void disabledScenario() {
publishScenarioProperties1.setEnabled(false);
CompositeTransactionGenerator generator = supplier.get();
assertThat(generator.distribution.get().getPmf())
.hasSize(1)
.extracting(Pair::getValue)
.containsExactly(1.0);
}
@Test
void noScenario() {
properties.getScenarios().clear();
assertInactive();
}
@Test
void noWarmup() {
properties.setWarmupPeriod(Duration.ZERO);
CompositeTransactionGenerator generator = supplier.get();
Stopwatch stopwatch = Stopwatch.createStarted();
double seconds = 4.0;
int total = (int) (totalTps * seconds);
for (int i = 0; i < total; i++) {
generator.next();
}
assertThat(stopwatch.elapsed().toMillis() * 1.0 / 1000).isCloseTo(seconds, withinPercentage(5));
}
@Test
void publishDisabled() {
properties.setEnabled(false);
assertInactive();
}
@Test
void scenariosComplete() {
properties.getScenarios().remove(publishScenarioProperties2.getName());
publishScenarioProperties1.setLimit(1L);
CompositeTransactionGenerator generator = supplier.get();
List<PublishScenario> scenarios = generator.scenarios().collectList().block();
assertThat(generator.next()).hasSize(1);
assertThat(generator.next()).isEmpty();
assertInactive();
assertThat(properties.getScenarios().values())
.extracting(PublishScenarioProperties::isEnabled)
.containsExactly(false);
assertThat(scenarios).extracting(PublishScenario::getStatus).containsOnly(ScenarioStatus.COMPLETED);
assertThat(generator.scenarios().count().block()).isZero();
}
@Test
void warmupBatchRequest() {
int warmUpSeconds = 4;
properties.setWarmupPeriod(Duration.ofSeconds(warmUpSeconds));
CompositeTransactionGenerator generator = supplier.get();
long begin = System.currentTimeMillis();
long elapsed = 0;
long lastElapsed = 0;
int count = 0;
List<Integer> counts = new ArrayList<>();
while (elapsed < (warmUpSeconds + 3) * 1000) {
List<PublishRequest> publishRequests = generator.next(0);
count += publishRequests.size();
elapsed = System.currentTimeMillis() - begin;
if (elapsed - lastElapsed >= 1000) {
counts.add(count);
count = 0;
lastElapsed = elapsed;
}
}
List<Integer> warmupCounts = counts.subList(0, warmUpSeconds);
List<Integer> stableCounts = counts.subList(warmUpSeconds, counts.size());
assertThat(warmupCounts).isSorted().allSatisfy(n -> assertThat(n * 1.0).isLessThan(totalTps));
assertThat(stableCounts).isNotEmpty().allSatisfy(n -> assertThat(n * 1.0)
.isCloseTo(totalTps, withinPercentage(5)));
}
@Test
@Timeout(10)
void scenariosDurationAfterFirstFinish() {
publishScenarioProperties1.setDuration(Duration.ofSeconds(3));
publishScenarioProperties2.setDuration(Duration.ofSeconds(5));
properties.setWarmupPeriod(Duration.ZERO);
CompositeTransactionGenerator generator = supplier.get();
long begin = System.currentTimeMillis();
do {
generator.next(0);
} while (System.currentTimeMillis() - begin <= 3100);
assertThat(generator.transactionGenerators)
.hasSize(1)
.first()
.returns(publishScenarioProperties2, from(ConfigurableTransactionGenerator::getProperties));
}
@Test
@Timeout(10)
void scenariosDurationAfterBothFinish() {
publishScenarioProperties1.setDuration(Duration.ofSeconds(3));
publishScenarioProperties2.setDuration(Duration.ofSeconds(5));
properties.setWarmupPeriod(Duration.ZERO);
CompositeTransactionGenerator generator = supplier.get();
long begin = System.currentTimeMillis();
while (true) {
List<PublishRequest> publishRequests = generator.next(1);
if (publishRequests.isEmpty()) {
break;
}
}
long elapsed = System.currentTimeMillis() - begin;
assertThat(generator.transactionGenerators).isEmpty();
assertThat(elapsed).isBetween(4950L, 5100L);
}
private void assertInactive() {
assertThat(supplier.get().rateLimiter.get()).isEqualTo(CompositeTransactionGenerator.INACTIVE_RATE_LIMITER);
}
private void prepare() {
// warmup so in tests the timing will be accurate
TransactionGenerator generator = Suppliers.synchronizedSupplier(() -> new CompositeTransactionGenerator(
p -> p,
p -> p.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)),
properties))
.get();
generator.next(0);
}
}
|
package com.ibeiliao.pay.idgen.api.dto;
import com.ibeiliao.pay.api.ApiCode;
import com.ibeiliao.pay.api.ApiResultBase;
/**
* 返回单个ID的 response
* @author linyi 2016/7/11.
*/
public class SingleId extends ApiResultBase {
private static final long serialVersionUID = 1;
/**
* ID的值
*/
private long id;
public SingleId() {}
public SingleId(int code, String message) {
super(code, message);
}
public SingleId(long id) {
this.id = id;
super.setCode(ApiCode.SUCCESS);
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
}
|
package com.tencent.mm.ui;
import com.tencent.mm.g.a.ph;
import com.tencent.mm.pluginsdk.c.a;
import com.tencent.mm.sdk.b.b;
class h$22 extends a {
final /* synthetic */ h tiG;
h$22(h hVar) {
this.tiG = hVar;
}
public final void j(b bVar) {
if (bVar instanceof ph) {
h.g(this.tiG);
h.a(this.tiG).notifyDataSetChanged();
}
}
}
|
package com.designpattern.dao.testcase;
import com.designpattern.dao.TransactionDao;
import com.designpattern.dao.TransactionDaoImpl;
public class DaoTestCase {
public static void main(String[] args) {
TransactionDao transaction=new TransactionDaoImpl();
System.out.println(transaction.getAllTransactions());
}
}
|
package com.tencent.mm.plugin.appbrand.dynamic;
import android.os.Bundle;
import com.tencent.mm.modelappbrand.r;
import com.tencent.mm.plugin.appbrand.dynamic.c.a;
class c$a$1 implements r {
final /* synthetic */ a fuC;
c$a$1(a aVar) {
this.fuC = aVar;
}
public final void b(boolean z, String str, Bundle bundle) {
}
}
|
package com.tencent.mm.app.plugin;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import com.tencent.mm.app.plugin.URISpanHandlerSet.TransferUriSpanHandler;
class URISpanHandlerSet$TransferUriSpanHandler$2 implements OnClickListener {
final /* synthetic */ TransferUriSpanHandler bAF;
URISpanHandlerSet$TransferUriSpanHandler$2(TransferUriSpanHandler transferUriSpanHandler) {
this.bAF = transferUriSpanHandler;
}
public final void onClick(DialogInterface dialogInterface, int i) {
}
}
|
/* ------------------------------------------------
* 8 Tiles GUI
*
* Class: CS 342, Fall 2016
* System: Windows 10, IntelliJ IDE
* Author: Five
* ------------------------------------------------- */
/**
* Driver class which runs the GUI
*/
public class TilesDriver
{
public static final int SIZE = Constants.BOARD_SIZE;
public static void main (String[] args)
{
System.out.println("**-----------------------------**");
System.out.println("Author: Five");
System.out.println("Class: CS 342, Fall 2016");
System.out.println("Program #4 : 8 Tiles GUI");
System.out.println("**-----------------------------**");
BoardGUI theGame = new BoardGUI();
}//End main
}//End class
|
package org.dota.model.buildings;
import lombok.Value;
@Value
public class TowersStatus {
private final TowersTierStatus tier1;
private final TowersTierStatus tier2;
private final TowersTierStatus tier3;
}
|
package com.smxknfie.softmarket.accesstoken.service;
import com.smxknfie.softmarket.accesstoken.domain.AccessToken;
public interface AccessTokenService {
String accessToken();
String flushAccessToken(String accessToken);
String flushAccessToken(AccessToken accessToken);
}
|
package edu.uoc.arbolgenealogico.controller.usuario;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import edu.uoc.arbolgenealogico.pojo.Usuario;
import edu.uoc.arbolgenealogico.service.interfaces.IUsuarioService;
@Controller
public class LogoutUsuarioController {
@Autowired
@Qualifier ("usuarioService")
private IUsuarioService userservice;
/**
* Método que cierra la sesion del usuario conectado
* @return ModelAndView
*/
@RequestMapping(value ="/usuarios/logout", method = RequestMethod.GET)
protected ModelAndView logoutusuariocontroller() {
ModelAndView modeloUsuario = new ModelAndView();
Usuario user = userservice.getByOnline();
if(user!=null){
user.setOnline(0);
userservice.update(user);
modeloUsuario.setViewName("logout");
}else{
modeloUsuario = new ModelAndView("error");
}
return modeloUsuario;
}
}
|
package com.hly.o2o.service;
import com.hly.o2o.dto.UserProductMapExecution;
import com.hly.o2o.entity.UserProductMap;
import com.hly.o2o.exceptions.UserProductMapOperationException;
public interface UserProductMapService {
/**
* 根据传入的条件分页查出用户消费信息列表
* @param userProductCondition
* @param pageIndex
* @param pageSize
* @return
*/
UserProductMapExecution listUserProductMap(UserProductMap userProductCondition, Integer pageIndex, Integer pageSize);
/**
* t添加消费记录
* @param userProductMap
* @return
* @throws UserProductMapOperationException
*/
UserProductMapExecution addUserProductMap(UserProductMap userProductMap) throws UserProductMapOperationException;
}
|
//The Fibonacci numbers are the integers in the following sequence:
//
// 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ...
//
//By definition, the first two numbers in the Fibonacci sequence are 0 and 1, and each subsequent number is the sum of the previous two.
//
//Write a command line program which prompts the user for an integer value and display the Fibonacci sequence leading up to that number.
//
//Please enter the Fibonacci number: 25
//
//0, 1, 1, 2, 3, 5, 8, 13, 21
package com.techelevator;
import java.util.Scanner;
public class Fibonacci {
public static void main(String[] args) {
Scanner inputScanner = new Scanner(System.in);
System.out.print("Please enter the Fibonacci number:");
String fibonacci = inputScanner.nextLine();
int fibonacciNum = Integer.parseInt(fibonacci);
System.out.print("0, 1");
int previousVal = 0;
for (int i = 1; i < fibonacciNum; i += previousVal) {
previousVal = i - previousVal;
System.out.print(", " + i);
}
}
}
|
package com.puxtech.reuters.rfa.Common;
public enum QuoteOperator {
GREATERTHAN, GREATEROREQUAL, EQUAL, LESSTHAN, LESSOREQUAL
}
|
package com.telyo.trainassistant.entity;
import java.util.ArrayList;
import java.util.List;
import cn.bmob.v3.BmobUser;
/**
* Created by Administrator on 2017/6/14.
*/
public class MyUser extends BmobUser {
private String userId;
private String name;
private String adCard;
private String adCardNumber;
private String auditingState;
private String phone;
private String passengerType;
private MyContent myContent;
private String img_url;
private List<MyContent> myContents = new ArrayList<>();
private List<MyOrders> myOrders = new ArrayList<>();
public List<MyOrders> getMyOrders() {
return myOrders;
}
public void setMyOrders(List<MyOrders> myOrders) {
this.myOrders = myOrders;
}
public String getImg_url() {
if (!"".equals(img_url)&& img_url != null) {
return img_url;
}else {
return "http://bmob-cdn-12269.b0.upaiyun.com/2017/06/27/e71272d593014a97a17b4dd0def07f3b.png";
}
}
public void setImg_url(String img_url) {
this.img_url = img_url;
}
public List<MyContent> getMyContents() {
return myContents;
}
public void setMyContents(List<MyContent> myContents) {
this.myContents = myContents;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAdCard() {
return adCard;
}
public void setAdCard(String adCard) {
this.adCard = adCard;
}
public String getAdCardNumber() {
return adCardNumber;
}
public void setAdCardNumber(String adCardNumber) {
this.adCardNumber = adCardNumber;
}
public String getAuditingState() {
return auditingState;
}
public void setAuditingState(String auditingState) {
this.auditingState = auditingState;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getPassengerType() {
return passengerType;
}
public void setPassengerType(String passengerType) {
this.passengerType = passengerType;
}
public MyContent instenceContents(){
if (myContent == null){
myContent = new MyContent();
}
return myContent;
}
public class MyContent {
private String contentName;
private String passengerType;
private String cardType;
private String cardNumber;
private String phoneNumber;
private String province;
private String school;
private String studentId;
private String studyYears;
private String startStudyTime;
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
public String getSchool() {
return school;
}
public void setSchool(String school) {
this.school = school;
}
public String getStudentId() {
return studentId;
}
public void setStudentId(String studentId) {
this.studentId = studentId;
}
public String getStudyYears() {
return studyYears;
}
public void setStudyYears(String studyYears) {
this.studyYears = studyYears;
}
public String getStartStudyTime() {
return startStudyTime;
}
public void setStartStudyTime(String startStudyTime) {
this.startStudyTime = startStudyTime;
}
public String getCardNumber() {
return cardNumber;
}
public void setCardNumber(String cardNumber) {
this.cardNumber = cardNumber;
}
public String getContentName() {
return contentName;
}
public void setContentName(String contentName) {
this.contentName = contentName;
}
public String getPassengerType() {
return passengerType;
}
public void setPassengerType(String passengerType) {
this.passengerType = passengerType;
}
public String getCardType() {
return cardType;
}
public void setCardType(String cardType) {
this.cardType = cardType;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
}
public static class MyOrders{
private String trainName;
private String price_all;
private List<OrderDetail> orderDetails = new ArrayList<>();
private String date;
private boolean isDown;
public boolean isDown() {
return isDown;
}
public void setDown(boolean down) {
isDown = down;
}
public String getTrainName() {
return trainName;
}
public void setTrainName(String trainName) {
this.trainName = trainName;
}
public String getPrice_all() {
return price_all;
}
public void setPrice_all(String price_all) {
this.price_all = price_all;
}
public List<OrderDetail> getOrderDetails() {
return orderDetails;
}
public void setOrderDetails(List<OrderDetail> orderDetails) {
this.orderDetails = orderDetails;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public static class OrderDetail{
private String passengerName;
private String sdCard;
private String setNum;
private String carriage;
private String ticketType;
private String price;
private String setType;
public String getSetType() {
return setType;
}
public void setSetType(String setType) {
this.setType = setType;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getPassengerName() {
return passengerName;
}
public void setPassengerName(String passengerName) {
this.passengerName = passengerName;
}
public String getSdCard() {
return sdCard;
}
public void setSdCard(String sdCard) {
this.sdCard = sdCard;
}
public String getSetNum() {
return setNum;
}
public void setSetNum(String setNum) {
this.setNum = setNum;
}
public String getCarriage() {
return carriage;
}
public void setCarriage(String carriage) {
this.carriage = carriage;
}
public String getTicketType() {
return ticketType;
}
public void setTicketType(String ticketType) {
this.ticketType = ticketType;
}
}
}
}
|
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
public class view_fees extends javax.swing.JFrame {
public view_fees() {
initComponents(); //initialise components (set default values etc.)
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
roll = new javax.swing.JLabel();
fieldroll = new javax.swing.JTextField();
btnview = new javax.swing.JButton();
month = new javax.swing.JTextField();
name = new javax.swing.JTextField();
seatrent = new javax.swing.JTextField();
mealcharge = new javax.swing.JTextField();
total = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
manu = new javax.swing.JButton();
service = new javax.swing.JTextField();
jLabel6 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setBackground(new java.awt.Color(0, 153, 255));
roll.setText("Enter the roll");
fieldroll.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
fieldrollActionPerformed(evt);
}
});
btnview.setText("View Fees");
btnview.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnviewActionPerformed(evt);
}
});
name.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
nameActionPerformed(evt);
}
});
jLabel1.setText("Month");
jLabel2.setText("Name");
jLabel3.setText("Seatrent");
jLabel4.setText("Meal Charge");
jLabel5.setText("Total");
manu.setText("Main Menu");
manu.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
manuActionPerformed(evt);
}
});
jLabel6.setText("Service Charge");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(63, 63, 63)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(roll, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1)
.addComponent(jLabel2)
.addComponent(jLabel3)
.addComponent(jLabel4)
.addComponent(jLabel5)
.addComponent(jLabel6)))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(183, 183, 183)
.addComponent(btnview, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 59, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(service, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(month, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(114, 114, 114))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(fieldroll, javax.swing.GroupLayout.DEFAULT_SIZE, 145, Short.MAX_VALUE)
.addComponent(seatrent)
.addComponent(mealcharge)
.addComponent(total)
.addComponent(name))
.addGap(18, 18, 18)
.addComponent(manu, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap()))))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(fieldroll, javax.swing.GroupLayout.DEFAULT_SIZE, 33, Short.MAX_VALUE)
.addComponent(roll, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(month, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1))
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnview, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(149, 149, 149))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(36, 36, 36)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(name, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(seatrent, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(mealcharge, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(service, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel6))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 11, Short.MAX_VALUE)))
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(manu, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel5)
.addComponent(total, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(16, 16, 16))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void fieldrollActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fieldrollActionPerformed
}//GEN-LAST:event_fieldrollActionPerformed
private void btnviewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnviewActionPerformed
String path = "G:\\project\\My project\\Feesmanagement\\"; //initialize the path
Integer input_roll;
input_roll = Integer.parseInt(fieldroll.getText()); //converts the string from fieldroll to Integer
String filename = path+input_roll.toString()+".txt"; //create filename basis of input given
Scanner sc = null;
try {
sc = new Scanner(new File(filename)); //creates a Scanner object for reding from the File filename
} catch (FileNotFoundException ex) {
}
String m = month.getText(); //initialize m as the string from month text field for searching
int line_number=0;
while(sc.hasNext()) //checks untill the file has date to read
{
if(m.equalsIgnoreCase(sc.next())) //if the data is equals to the month that search
{
String a = sc.next(); // read and initialize string variable a,b,c,d,e to File's next data
String b = sc.next();
String c = sc.next();
String d = sc.next();
String e = sc.next();
name.setText(a); //set a as name
seatrent.setText(b); //set b as seatrent
mealcharge.setText(c); //set c as mealcharge
service.setText(d); //set d as service charge
total.setText(e); //set e as total
}
line_number++;
}
sc.close(); //close the file
}//GEN-LAST:event_btnviewActionPerformed
private void nameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nameActionPerformed
}//GEN-LAST:event_nameActionPerformed
private void manuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_manuActionPerformed
Home h = new Home(); //create object of Home
h.setVisible(true); //make Home visible
dispose(); //close view_fees window
}//GEN-LAST:event_manuActionPerformed
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new view_fees().setVisible(true); //make view_fees visible
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnview;
private javax.swing.JTextField fieldroll;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JPanel jPanel1;
private javax.swing.JButton manu;
private javax.swing.JTextField mealcharge;
private javax.swing.JTextField month;
private javax.swing.JTextField name;
private javax.swing.JLabel roll;
private javax.swing.JTextField seatrent;
private javax.swing.JTextField service;
private javax.swing.JTextField total;
// End of variables declaration//GEN-END:variables
}
|
package com.huifu.newdemo.retrofit;
public class Info {
}
|
/**
*
*/
package com.xtel.examthread.bai6c;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
* @author TUAN
*
*/
public class ThreadProducer extends Thread {
Message message = new Message();
QueueMessage queueMessage = new QueueMessage();
private QueueMessage queueData;
public ThreadProducer(QueueMessage queueData) {
this.queueData = queueData;
}
Random random = new Random();
@Override
public void run() {
Random random = new Random();
String customerName = " ";
String giftName = " ";
message.dataMessage();
int i = 0;
do {
for (i = 0; i < message.listCustomerName.size(); i++) {
customerName = message.listCustomerName.get(random.nextInt(message.listCustomerName.size()));
}
for (i = 0; i < message.listGiftName.size(); i++) {
giftName = message.listGiftName.get(random.nextInt(message.listGiftName.size()));
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
String listInfo = String.format("Chuc mung %s la khach hang may man man nhan duoc %s tu chuong trinh tri an khach hang",
customerName, giftName);
queueMessage.queueMessage.offer(listInfo);
// System.out.println(listInfo);
// System.out.println(String.format("Chuoi: %s", queueMessage.queueMessage.poll()));
} while (true);
}
public static void main(String[] args) {
QueueMessage queueMessage = new QueueMessage();
ThreadProducer t = new ThreadProducer(queueMessage);
t.start();
}
}
|
package com.anywaycloud.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class CloudController {
@RequestMapping("/index")
public String index() {
return "index";
}
@RequestMapping("/home")
public String home() {
return "home";
}
@RequestMapping("/users")
public String users() {
return "users";
}
}
|
package io.bega.kduino.datamodel;
/**
* Clase profile que guarda el perfil del usuario y los datos del menu_makeakaduino
*/
public class Profile {
//declaramos las variables
private String depth_1="0.0";
private String depth_2="0.0";
private String depth_3="0.0";
private String depth_4="0.0";
private String depth_5="0.0";
private String depth_6="0.0";
private String lat;
private String longi;
private int numberofsensor;
private String date;
private String time;
private String markername;
private String kduinoname;
public String getLat() {
return lat;
}
public void setLat(String lat) {
this.lat = lat;
}
public String getLongi() {
return longi;
}
public void setLongi(String longi) {
this.longi = longi;
}
public String getDepth_1() {
return depth_1;
}
public void setDepth_1(String depth_1) {
this.depth_1 = depth_1;
}
public String getDepth_2() {
return depth_2;
}
public void setDepth_2(String depth_2) {
this.depth_2 = depth_2;
}
public String getDepth_3() {
return depth_3;
}
public void setDepth_3(String depth_3) {
this.depth_3 = depth_3;
}
public String getDepth_4() {
return depth_4;
}
public void setDepth_4(String depth_4) {
this.depth_4 = depth_4;
}
public String getDepth_5() {
return depth_5;
}
public void setDepth_5(String depth_5) {
this.depth_5 = depth_5;
}
public String getDepth_6() {
return depth_6;
}
public void setDepth_6(String depth_6) {
this.depth_6 = depth_6;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public int getNumberofsensor() {
return numberofsensor;
}
public void setNumberofsensor(int numberofsensor) {
this.numberofsensor = numberofsensor;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getMarkername() {
return markername;
}
public void setMarkername(String markername) {
this.markername = markername;
}
public String getKduinoname() {
return kduinoname;
}
public void setKduinoname(String kduinoname) {
this.kduinoname = kduinoname;
}
//pasamos los datos a una string
@Override
public String toString() {
return
kduinoname+
"\n" + numberofsensor+
"\n" + depth_1 +
"\n" + depth_2 +
"\n" + depth_3 +
"\n" + depth_4 +
"\n" + depth_5 +
"\n" + depth_6 +
"\n" + lat +
"\n" + longi +
"\n" + markername +
"\n" + date+
"\n" + time+
"\n";
}
}
|
package valatava.lab.warehouse.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import valatava.lab.warehouse.model.Store;
/**
* Spring Data JPA repository for the {@link Store} entity.
*
* @author Yuriy Govorushkin
*/
public interface StoreRepository extends JpaRepository<Store, Long> {
}
|
package assignment2_Student;
import java.util.*;
public class Service_Implement implements Service_Interface {
List<Student> x;
Persistance_implement p;
public Service_Implement() {
super();
x = new ArrayList<Student>();
p = new Persistance_implement();
x = p.getRecords();
}
@Override
public void insertData(String nm, int e, int m, int s) {
p.insertRecords(new Student(x.size() + 1, nm, e, m, s));
}
@Override
public List<Student> return_roll_Name() {
return x;
}
@Override
public Student highestAll() {
double avg = Integer.MIN_VALUE;
Student z = null;
for (Student s : x)
if ((s.getE() + s.getM() + s.getS()) / 3.0 > avg) {
avg = (s.getE() + s.getM() + s.getS()) / 3.0;
z=s;
}
return z;
}
@Override
public Student highestMaths() {
int maths=Integer.MIN_VALUE;
Student z=null;
for(Student s:x)
if(s.getM()>maths) {
maths=s.getM();
z=s;
}
return z;
}
@Override
public List<Student> highestMaths_Science() {
List<Student> l=new ArrayList<Student>();
for(Student s:x) l.add(s);
double avg,avg1;
Student temp;
for(int i=0;i<x.size()-1;i++) {
for (int j = 0; j < x.size()-1-i; j++) {
temp=l.get(j);
avg=(temp.getM()+temp.getS())/2;
temp=l.get(j+1);
avg1=(temp.getM()+temp.getS())/2;
if(avg>avg1) {
temp=l.get(j);
l.set(j, l.get(j+1));
l.set(j+1, temp);
}
}
}
return l;
}
@Override
public List<Student> ReportCards() {
List<Student> l=new ArrayList<Student>();
for(Student s:x) l.add(s);
double avg,avg1;
Student temp;
for(int i=0;i<x.size()-1;i++) {
for (int j = 0; j < x.size()-1-i; j++) {
temp=l.get(j);
avg=(temp.getE()+temp.getM()+temp.getS())/3;
temp=l.get(j+1);
avg1=(temp.getE()+temp.getM()+temp.getS())/3;
if(avg<avg1) {
temp=l.get(j);
l.set(j, l.get(j+1));
l.set(j+1, temp);
}
}
}
return l;
}
}
|
package com.thoughtworks.training.guessnumber;/*
* This Java source file was generated by the Gradle 'init' task.
*/
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
public class AppTest {
@Test
public void shouldGuessNubmber() {
String output = new GuessNumberGame(new OddRule()).process("1 2 3 4 5");
assertThat(output,is("1 3 5"));
}
@Test
public void shouldGuessNubmber2() {
String output = new GuessNumberGame(new EvenRule()).process("3 4 5 6 7");
assertThat(output,is("4 6"));
}
@Test
public void shouldGuessNubmber3() {
String output = new GuessNumberGame(new OddRule(),new AddRule()).process("6 7 8 9");
assertThat(output,is("9 11"));
}
}
|
import java.util.Scanner;
/**
* Write a program to generate and print all 3-letter words consisting of given set of characters.
* For example if we have the characters 'a' and 'b', all possible words will be "aaa", "aab", "aba", "abb",
* "baa", "bab", "bba" and "bbb".
* The input characters are given as string at the first line of the input. Input characters are unique (
*/
public class Generate3LetterWord {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
String str = input.nextLine();
char[] arr = str.toCharArray();
for (char i = 0; i < arr.length; i++) {
for (char j = 0; j < arr.length; j++) {
for (char k = 0; k < arr.length; k++) {
System.out.print("" + arr[i] + arr[j] + arr[k] + " ");
}
}
}
}
} |
package edu.uci.ics.inf225.webcrawler.stats;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import org.junit.Test;
public class TotalSizeCalculator {
public TotalSizeCalculator() {
}
@Test
public void calculateSize() throws IOException {
BufferedReader reader = new BufferedReader(new FileReader("crawledpages.20140202.log"));
String line;
long totalSizeBytes = 0L;
long counter = 0L;
long zeroCounter = 0L;
while (true) {
line = reader.readLine();
if (line == null) {
break;
}
String numberString = line.substring(line.lastIndexOf(",") + 1, line.length() - 1);
Long pageContentLength = Long.valueOf(numberString);
totalSizeBytes += pageContentLength;
if (pageContentLength == 0) {
zeroCounter++;
}
counter++;
}
reader.close();
long totalSizeMB = totalSizeBytes / 1024 / 1024;
double percentageOfUnknownPageLengths = (double) zeroCounter / (double) counter;
System.out.println(totalSizeMB + " (~" + totalSizeMB / (1 - percentageOfUnknownPageLengths) + ") MB ");
System.out.println(counter + " pages crawled.");
System.out.println(zeroCounter + " pages with unknown size crawled (" + percentageOfUnknownPageLengths + ").");
}
}
|
package com.tencent.weui.base.preference;
import com.tencent.mm.ui.widget.MMSwitchBtn.a;
class CheckBoxPreference$1 implements a {
final /* synthetic */ CheckBoxPreference vzx;
CheckBoxPreference$1(CheckBoxPreference checkBoxPreference) {
this.vzx = checkBoxPreference;
}
public final void cf(boolean z) {
CheckBoxPreference.a(this.vzx, Boolean.valueOf(z));
}
}
|
package com.mochasoft.fk.db.page;
/**
* <strong>Title : Dialect </strong>. <br>
* <strong>Description : 数据库方言接口.</strong> <br>
* <strong>Create on : 2013-1-31 下午1:49:55 </strong>. <br>
* <p>
* <strong>Copyright (C) Mocha Software Co.,Ltd.</strong> <br>
* </p>
* @author wanghe wanghe@mochasoft.com.cn <br>
* @version <strong>FrameWork v0.8</strong> <br>
* <br>
* <strong>修改历史: .</strong> <br>
* 修改人 修改日期 修改描述<br>
* -------------------------------------------<br>
* <br>
* <br>
*/
public interface Dialect {
public static enum Type{
MYSQL,
ORACLE,
DB2
}
/**
* 获取分页SQL.
* @param sql 原始查询SQL
* @param offset 开始记录索引(从0开始计算)
* @param pageSize 每页记录大小
* @return 返回数据库相关的分页SQL语句
*/
public abstract String getPageSql(String sql, int offset, int pageSize);
}
|
/*
* 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 quicksort;
import java.util.Random;
/**
*
* @author ESTUDIANTE
*/
public class QuickSort {
public static void quickSort(int[] vector, int izquierda, int derecha) {
int pivote = vector[izquierda];
int i = izquierda;
int j = derecha;
int auxIntercambio;
while (i < j) {
while (vector[i] <= pivote && i < j) {
i++;
}
while (vector[j] > pivote) {
j--;
}
if (i < j) {
auxIntercambio = vector[i];
vector[i] = vector[j];
vector[j] = auxIntercambio;
}
}
vector[izquierda] = vector[j];
vector[j] = pivote;
if (izquierda < j - 1) {
quickSort(vector, izquierda, j - 1);
}
if (j + 1 < derecha) {
quickSort(vector, j + 1, derecha);
}
}
public static void main(String[] args) {
int[] numeros = new int[40];
Random rnd = new Random();
System.out.println("Vector desordenado");
for (int i = 0; i < numeros.length; i++) {
numeros[i] = rnd.nextInt(50);
System.out.print(numeros[i] + " ");
}
QuickSort.quickSort(numeros, 0, numeros.length - 1);
System.out.println("\nVector Ordenado");
for (int n : numeros) {
System.out.print(n + " ");
}
}}
|
package com.nightlife.controller;
import com.nightlife.repository.Ticket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.nightlife.model.*;
import java.util.List;
import java.util.Optional;
@RestController
@RequestMapping("/api/sales")
public class HistoricController {
@Autowired
private Ticket ticket;
@GetMapping
public ResponseEntity<List<Historic>> listusers() {
try {
List<Historic> historics = ticket.findAll();
return ResponseEntity.ok().body(historics);
} catch (Exception e) {
return ResponseEntity.badRequest().build();
}
}
@GetMapping("{id}")
public ResponseEntity<Historic> userhistoric(@PathVariable Long id) {
try {
Historic historic = ticket.findById(id).get();
return ResponseEntity.ok().body(historic);
} catch (Exception e) {
return ResponseEntity.badRequest().build();
}
}
}
|
/*
* 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 uuu.totalbuy.model;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import uuu.totalbuy.domain.*;
/**
*
* @author PattyTai
*/
public class RDBCustomersDAO implements DAOInterface<String, Customer> {
private static final String INSERT_SQL = "INSERT INTO customers "
+ "(id,name,gender,password,email,birthday,phone,address,married,blood_type,type,discount) "
+ "VALUES(?,?,?,?,?,?,?,?,?,?,?,?)";
private static final String UPDATE_SQL = "UPDATE customers "
+ "SET name=?,gender=?,password=?,email=?,birthday=?,phone=?,address=?,married=?,blood_type=?,type=?,discount=? "
+ "WHERE id=?";
private static final String DELETE_SQL = "DELETE FROM customers WHERE id=?";
private static final String SELECT_ALL_SQL
= "SELECT id,name,gender,password,email,birthday,phone,address,married,blood_type,type,discount,status "
+ "FROM customers";
private static final String sql
= SELECT_ALL_SQL + " WHERE id = ?"; // AND password='123456'";
@Override
public void insert(Customer c) throws TotalBuyException {
if (c == null) {
throw new TotalBuyException("無法新增null客戶資料");
}
try (Connection connection = RDBConnection.getConnection(); //2. 建立連線
PreparedStatement pstmt = connection.prepareStatement(INSERT_SQL); //3. 準備指令
) {
//3.1 傳入參數
pstmt.setString(1, c.getId());
pstmt.setString(2, c.getName());
pstmt.setString(3, String.valueOf(c.getGender()));
pstmt.setString(4, c.getPassword());
pstmt.setString(5, c.getEmail());
pstmt.setDate(6, c.getBirthday() != null ? new java.sql.Date(c.getBirthday().getTime()) : null);
pstmt.setString(7, c.getPhone());
pstmt.setString(8, c.getAddress());
pstmt.setBoolean(9, c.isMarried());
pstmt.setString(10, c.getBloodType() != null ? c.getBloodType().name() : null);
pstmt.setString(11, c.getClass().getSimpleName());
pstmt.setInt(12, c instanceof VIP ? ((VIP) c).getDiscount() : 0);
//4. 執行指令
pstmt.executeUpdate();
} catch (SQLException ex) {
System.out.println("新增客戶失敗: " + c + "發生" + ex);
throw new TotalBuyException("新增客戶失敗: " + c, ex);
}
}
@Override
public void update(Customer c) throws TotalBuyException {
if (c == null) {
throw new TotalBuyException("無法修改null客戶資料");
}
try (Connection connection = RDBConnection.getConnection(); //2. 建立連線
PreparedStatement pstmt = connection.prepareStatement(UPDATE_SQL); //3. 準備指令
) {
//3.1 傳入參數
pstmt.setString(1, c.getName());
pstmt.setString(2, String.valueOf(c.getGender()));
pstmt.setString(3, c.getPassword());
pstmt.setString(4, c.getEmail());
pstmt.setDate(5, c.getBirthday() != null ? new java.sql.Date(c.getBirthday().getTime()) : null);
pstmt.setString(6, c.getPhone());
pstmt.setString(7, c.getAddress());
pstmt.setBoolean(8, c.isMarried());
pstmt.setString(9, c.getBloodType() != null ? c.getBloodType().name() : null);
pstmt.setString(10, c.getClass().getSimpleName());
pstmt.setInt(11, c instanceof VIP ? ((VIP) c).getDiscount() : 0);
pstmt.setString(12, c.getId());
//4. 執行指令
pstmt.executeUpdate();
} catch (SQLException ex) {
System.out.println("修改客戶失敗: " + c + "發生" + ex);
throw new TotalBuyException("修改客戶失敗: " + c, ex);
}
}
@Override
public void delete(Customer c) throws TotalBuyException {
if (c == null) {
throw new TotalBuyException("無法刪除null客戶資料");
}
try (Connection connection = RDBConnection.getConnection(); //2. 建立連線
PreparedStatement pstmt = connection.prepareStatement(DELETE_SQL); //3. 準備指令
) {
//3.1 傳入參數
pstmt.setString(1, c.getId());
//4. 執行指令
pstmt.executeUpdate();
} catch (SQLException ex) {
System.out.println("刪除客戶失敗: " + c + "發生" + ex);
throw new TotalBuyException("刪除客戶失敗: " + c, ex);
}
}
private Customer createCustomer(String t) {
Customer cust = null;
if ("VIP".equals(t)) {
cust = new VIP();
} else {
cust = new Customer();
}
return cust;
}
@Override
public Customer get(String id) throws TotalBuyException {
Customer cust = null;
try (Connection c = RDBConnection.getConnection();//2. 建立連線
PreparedStatement stmt = c.prepareStatement(sql);//3. 建立指令物件
) {
System.out.println(c.getCatalog());
stmt.setString(1, id); //3.2 傳入?參數的值
try (ResultSet rs = stmt.executeQuery();) {//4. 執行指令
//5.處理Resultset
while (rs.next()) {
try {
String t = rs.getString("type");
cust = this.createCustomer(t);
if (cust instanceof VIP) {
((VIP) cust).setDiscount(rs.getInt("discount"));
}
cust.setId(rs.getString("id"));
cust.setName(rs.getString("name"));
cust.setPassword(rs.getString("password"));
cust.setGender(rs.getString("gender").charAt(0));
cust.setEmail(rs.getString("email"));
cust.setBirthday(rs.getDate("birthday"));
cust.setPhone(rs.getString("phone"));
cust.setAddress(rs.getString("address"));
cust.setMarried(rs.getBoolean("married"));
String bType = rs.getString("blood_type");
if (bType != null && (bType = bType.trim()).length() > 0) {
cust.setBloodType(BloodType.valueOf(bType));
}
System.out.println("cust:" + cust);
} catch (TotalBuyException ex) {
System.out.println(ex);
throw new TotalBuyException("查詢客戶建立指派客戶物件資料失敗", ex);
}
}
}
//c.close();
} catch (SQLException ex) {
Logger.getLogger(RDBCustomersDAO.class.getName()).log(Level.SEVERE, "查詢客戶失敗", ex);
throw new TotalBuyException("查詢客戶失敗", ex);
}
return cust;
}
@Override
public List<Customer> getAll() throws TotalBuyException {
List<Customer> customers = new ArrayList<>();
//JDBC 查詢customers的所有資料>...
try (Connection c = RDBConnection.getConnection();//2. 建立連線
PreparedStatement stmt = c.prepareStatement(SELECT_ALL_SQL);//3. 建立指令物件
) {
//System.out.println(c.getCatalog());
//stmt.setString(1, id); //3.2 傳入?參數的值
try (ResultSet rs = stmt.executeQuery();) {//4. 執行指令
//5.處理Resultset
while (rs.next()) {
try {
String t = rs.getString("type");
Customer cust = this.createCustomer(t);
if (cust instanceof VIP) {
((VIP) cust).setDiscount(rs.getInt("discount"));
}
cust.setId(rs.getString("id"));
cust.setName(rs.getString("name"));
cust.setPassword(rs.getString("password"));
cust.setGender(rs.getString("gender").charAt(0));
cust.setEmail(rs.getString("email"));
cust.setBirthday(rs.getDate("birthday"));
cust.setPhone(rs.getString("phone"));
cust.setAddress(rs.getString("address"));
cust.setMarried(rs.getBoolean("married"));
String bType = rs.getString("blood_type");
if (bType != null && (bType = bType.trim()).length() > 0) {
cust.setBloodType(BloodType.valueOf(bType));
}
System.out.println("cust:" + cust);
customers.add(cust);
} catch (TotalBuyException ex) {
System.out.println(ex);
throw new TotalBuyException("查詢全部客戶建立指派客戶物件資料失敗", ex);
}
}
}
//c.close();
} catch (SQLException ex) {
Logger.getLogger(RDBCustomersDAO.class.getName()).log(Level.SEVERE, "查詢全部客戶失敗", ex);
throw new TotalBuyException("查詢全部客戶失敗", ex);
}
return customers;
}
}
|
/*
* 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 mude.srl.ssc.entity.utils;
import java.math.BigDecimal;
import java.util.Date;
import mude.srl.ssc.entity.Users;
/**
*
* @author jackarian
*/
public class Request {
private Date start;
private Date end;
private Date start_fatture;
private Date end_fatture;
private String doc_type;
private String channel;
private String orderList;
private String orderStatus;
private Boolean deferred;
private Boolean date_fattura;
private Boolean date_order;
private String logisticStatus;
private Long batchId;
private Long spedizione;
private String channelExcl;
private String skus;
private Long fatturaSpezione;
private String indirizzo;
private String civico;
private String citta;
private String provincia;
private String provinciaEstesa;
private String cap;
private String country;
private String codRep;
private String tipDoc;
private String numDoc;
private String cap_list;
private BigDecimal delta_min;
private BigDecimal delta_max;
private BigDecimal delta_riga_min;
private BigDecimal delta_riga_max;
private String rag_soc;
private String rif_mitt_num;
private String rif_mitt_alfa;
private String fatture;
private String ordine_int;
private boolean paginate = true;
private boolean fatturaVettore=false;
private boolean fatturaDeferred=false;
public boolean isFatturaDeferred() {
return fatturaDeferred;
}
public void setFatturaDeferred(boolean fatturaDeferred) {
this.fatturaDeferred = fatturaDeferred;
}
public boolean isFatturaVettore() {
return fatturaVettore;
}
public void setFatturaVettore(boolean fatturaVettore) {
this.fatturaVettore = fatturaVettore;
}
public boolean isPaginate() {
return paginate;
}
public void setPaginate(boolean paginate) {
this.paginate = paginate;
}
public String getOrdine_int() {
return ordine_int;
}
public void setOrdine_int(String ordine_int) {
this.ordine_int = ordine_int;
}
public Date getStart_fatture() {
return start_fatture;
}
public void setStart_fatture(Date start_fatture) {
this.start_fatture = start_fatture;
}
public Date getEnd_fatture() {
return end_fatture;
}
public void setEnd_fatture(Date end_fatture) {
this.end_fatture = end_fatture;
}
public String getDoc_type() {
return doc_type;
}
public void setDoc_type(String doc_type) {
this.doc_type = doc_type;
}
public Boolean getDate_fattura() {
return date_fattura;
}
public void setDate_fattura(Boolean date_fattura) {
this.date_fattura = date_fattura;
}
public Boolean getDate_order() {
return date_order;
}
public void setDate_order(Boolean date_order) {
this.date_order = date_order;
}
public String getFatture() {
return fatture;
}
public void setFatture(String fatture) {
this.fatture = fatture;
}
public String getRag_soc() {
return rag_soc;
}
public void setRag_soc(String rag_soc) {
this.rag_soc = rag_soc;
}
public String getRif_mitt_num() {
return rif_mitt_num;
}
public void setRif_mitt_num(String rif_mitt_num) {
this.rif_mitt_num = rif_mitt_num;
}
public String getRif_mitt_alfa() {
return rif_mitt_alfa;
}
public void setRif_mitt_alfa(String rif_mitt_alfa) {
this.rif_mitt_alfa = rif_mitt_alfa;
}
public String getCap_list() {
return cap_list;
}
public void setCap_list(String cap_list) {
this.cap_list = cap_list;
}
public BigDecimal getDelta_min() {
return delta_min;
}
public void setDelta_min(BigDecimal delta_min) {
this.delta_min = delta_min;
}
public BigDecimal getDelta_max() {
return delta_max;
}
public void setDelta_max(BigDecimal delta_max) {
this.delta_max = delta_max;
}
public BigDecimal getDelta_riga_min() {
return delta_riga_min;
}
public void setDelta_riga_min(BigDecimal delta_riga_min) {
this.delta_riga_min = delta_riga_min;
}
public BigDecimal getDelta_riga_max() {
return delta_riga_max;
}
public void setDelta_riga_max(BigDecimal delta_riga_max) {
this.delta_riga_max = delta_riga_max;
}
public Long getFatturaSpezione() {
return fatturaSpezione;
}
public void setFatturaSpezione(Long fatturaSpezione) {
this.fatturaSpezione = fatturaSpezione;
}
public String getSkus() {
return skus;
}
public void setSkus(String skus) {
this.skus = skus;
}
public String getProvinciaEstesa() {
return provinciaEstesa;
}
public void setProvinciaEstesa(String provinciaEstesa) {
this.provinciaEstesa = provinciaEstesa;
}
public String getIndirizzo() {
return indirizzo;
}
public void setIndirizzo(String indirizzo) {
this.indirizzo = indirizzo;
}
public String getCivico() {
return civico;
}
public void setCivico(String civico) {
this.civico = civico;
}
public String getCitta() {
return citta;
}
public void setCitta(String citta) {
this.citta = citta;
}
public String getProvincia() {
return provincia;
}
public void setProvincia(String provincia) {
this.provincia = provincia;
}
public String getCap() {
return cap;
}
public void setCap(String cap) {
this.cap = cap;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getCodRep() {
return codRep;
}
public void setCodRep(String codRep) {
this.codRep = codRep;
}
public String getTipDoc() {
return tipDoc;
}
public void setTipDoc(String tipDoc) {
this.tipDoc = tipDoc;
}
public String getNumDoc() {
return numDoc;
}
public void setNumDoc(String numDoc) {
this.numDoc = numDoc;
}
public String getChannelExcl() {
return channelExcl;
}
public void setChannelExcl(String channelExcl) {
this.channelExcl = channelExcl;
}
private long pageSize;
public Long getSpedizione() {
return spedizione;
}
public void setSpedizione(Long spedizione) {
this.spedizione = spedizione;
}
public Long getBatchId() {
return batchId;
}
public void setBatchId(Long batchId) {
this.batchId = batchId;
}
public long getPageSize() {
return pageSize;
}
public void setPageSize(long pageSize) {
this.pageSize = pageSize;
}
Long channelOrderid;
public Long getChannelOrderid() {
return channelOrderid;
}
public void setChannelOrderid(Long channelOrderid) {
this.channelOrderid = channelOrderid;
}
private Users user;
public Users getUser() {
return user;
}
public Boolean getDeferred() {
return deferred;
}
/**
*
* @param deferred
*/
public void setDeferred(Boolean deferred) {
this.deferred = deferred;
}
public String getOrderStatus() {
return orderStatus;
}
public void setOrderStatus(String orderStatus) {
this.orderStatus = orderStatus;
}
Pager pager;
public Date getStart() {
return start;
}
public void setStart(Date start) {
this.start = start;
}
public Date getEnd() {
return end;
}
public void setEnd(Date end) {
this.end = end;
}
public Pager getPager() {
return pager;
}
public void setPager(Pager pager) {
this.pager = pager;
}
public String getOrderList() {
return orderList;
}
public void setOrderList(String orderList) {
this.orderList = orderList;
}
public String getChannel() {
return channel;
}
public void setChannel(String channel) {
this.channel = channel;
}
public void setUser(Users user) {
this.user = user;
}
public String getLogisticStatus() {
return logisticStatus;
}
public void setLogisticStatus(String logisticStatus) {
this.logisticStatus = logisticStatus;
}
}
|
package com.takshine.wxcrm.service;
import com.takshine.wxcrm.base.services.EntityService;
/**
* 微信 用户位置服务 实现类
* @author liulin
*
*/
public interface WxUserLocationService extends EntityService {
}
|
package edu.troy.cs.bio;
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.bson.Document;
public class TsvToMongo {
private static String path = "/home/hadoop/Downloads/chemicals.v4.0.tsv";
static List<Document> mongoData = new ArrayList<Document>();
static int writeCount = 0;
static int flushSize = 50;
public static void execute() throws IOException {
BufferedReader tsvFile = new BufferedReader(new FileReader(path));
String line = tsvFile.readLine();
// ignore first line
line = tsvFile.readLine();
while (line != null) {
String[] datas = line.split("\t");
Document doc = new Document();
doc.append("CID", datas[0]);
doc.append("SMILES", datas[3]);
mongoData.add(doc);
bulkWrite();
line = tsvFile.readLine();
}
closeIO(tsvFile);
System.out.println("write from tsv to mongo done!");
}
private static void bulkWrite() {
if (mongoData.size() >= flushSize) {
System.out.println(writeCount * flushSize);
MongoDB.sequenceCollection().insertMany(mongoData);
mongoData = new ArrayList<Document>();
writeCount++;
}
}
private static void closeIO(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String args[]) throws IOException {
execute();
}
}
|
package com.lc.exstreetseller.activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import com.lc.exstreetseller.base.BaseActivity;
import com.lc.exstreetseller.R;
import com.lc.exstreetseller.constant.Constant;
import com.lc.exstreetseller.view.CountDownTextView;
import com.xjl.elibrary.util.UtilSTRWithToast;
import butterknife.BindView;
import butterknife.OnClick;
public class PhoneFastActivity extends BaseActivity {
@BindView(R.id.et_phone_fast_phone_number)
EditText phoneNumberEt;
@BindView(R.id.et_phone_fast_message_code)
EditText messageCodeEt;
@BindView(R.id.iv_phone_fast_clear_phone_number)
ImageView clearPhoneNumberIv;
@BindView(R.id.iv_phone_fast_clear_message_code)
ImageView clearMessageCodeIv;
@BindView(R.id.tv_phone_fast_count_down)
CountDownTextView countDownTv;
@BindView(R.id.tv_phone_fast_login)
TextView loginTv;
UtilSTRWithToast STRWithToast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_phone_fast);
STRWithToast = new UtilSTRWithToast(activity);
initView();
}
private void initView() {
setETitle("手机登录");
getTitleView().setLeftIcon(R.mipmap.black_fh);
phoneNumberEt.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void afterTextChanged(Editable s) {
clearPhoneNumberIv.setVisibility(s.toString().length() > 0 ? View.VISIBLE : View.INVISIBLE);
checkLogin();
}
});
messageCodeEt.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void afterTextChanged(Editable s) {
clearMessageCodeIv.setVisibility(s.toString().length() > 0 ? View.VISIBLE : View.INVISIBLE);
checkLogin();
}
});
loginTv.setClickable(false);
}
private void checkLogin() {
if (phoneNumberEt.getText().toString().length() == 11 &&
messageCodeEt.getText().toString().length() >= 6) {
loginTv.setClickable(true);
loginTv.setSelected(true);
} else {
loginTv.setClickable(false);
loginTv.setSelected(false);
}
}
@OnClick({R.id.iv_phone_fast_clear_phone_number,
R.id.iv_phone_fast_clear_message_code,
R.id.tv_phone_fast_count_down,
R.id.tv_phone_fast_login})
public void click(View v) {
switch (v.getId()) {
case R.id.iv_phone_fast_clear_phone_number:
phoneNumberEt.setText("");
break;
case R.id.iv_phone_fast_clear_message_code:
messageCodeEt.setText("");
break;
case R.id.tv_phone_fast_count_down:
countDownTv.startCountDown(Constant.get_msg_code_count_down_time);
break;
case R.id.tv_phone_fast_login:
t(MainActivity.class);
break;
}
}
}
|
package com.mx.profuturo.bolsa.util.formatter;
public class TextUtil {
public static String capitalize(String source){
String response = null;
String original = null;
if(source.length()==0){
response = source;
}else{
original = source.toLowerCase();
response = original.substring(0, 1).toUpperCase() + original.substring(1);
}
return response;
}
public static String replaceEmpty(String source){
return replaceEmpty(source,false);
}
public static String replaceEmpty(String source, Boolean checkZero){
String response = null;
if(checkZero){
response = (null != source && !("".equals(source))&&!(("0".equals(source))))? source:"N/A";
}else{
response = (null != source && !("".equals(source)))? source:"N/A";
}
return response;
}
public static String replaceNull(String source) {
return(source == null)?"":source;
}
}
|
package category.bitOperation;
/**
* there is an integrate array which has only different value, 0, 1, 2
* how to store the number in most efficient way
*
* how about frequently query?
* please imlpment two method set and get
* @author Meng
*
*/
public class CompressBits {
private int[] inputs = { 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 1, 1, 0, 1, 0, 2, 0, 1, 2 };
private int[] cache = new int[(int) Math.ceil(inputs.length / 8)];
public void set(int index, int val){
int target = cache[index / 16];
int bit = index % 16;
int mask = 3 << (30 - bit * 2);
target = (target & ~mask) | (val << 30 - bit * 2);
}
public int get(int index){
int target = cache[index / 16];
int bit = index % 16;
return (target << bit * 2) >>> 30;
}
public static void main(String[] args) {
System.out.println(Math.ceil(4.2));
}
}
|
package com.yinghai.a24divine_user.module.collect.mvp;
import com.example.fansonlib.base.BaseView;
import com.yinghai.a24divine_user.bean.CollectBean;
import com.yinghai.a24divine_user.callback.IHandleCodeCallback;
/**
* @author Created by:fanson
* Created Time: 2017/11/10 13:50
* Describe:我的收藏的契约类
*/
public interface ContractCollect {
interface ICollectView extends BaseView {
/**
* 成功获取收藏
*
* @param bean
*/
void getCollectSuccess(CollectBean bean);
/**
* 获取收藏失败
*/
void getCollectFailure(String errorMsg);
/**
* 取消收藏成功
* @param id 取消成功的对应ID
*/
void onCancelCollectSuceess(int id);
/**
* 取消收藏
*
* @param errMsg
*/
void onCancelCollectFailure(String errMsg);
/**
* 添加收藏成功
* @param id 收藏成功的对应ID
*/
void onAddCollectSuccess(int id);
/**
* 添加收藏失败
*
* @param errMsg
*/
void onAddCollectFailure(String errMsg);
}
interface ICollectPresenter {
/**
* 获取我的收藏
*/
void onGetCollect();
/**
* 添加收藏、取消收藏
*
* @param type 收藏类型,1大师 2文章 3商品
* @param id type=1时为大师id,type=2时为文章id,type=3为商品id (取消收藏时,id 为 coleectionId)
* @param isCollect true:收藏 false:取消收藏
*/
void onCollect(int type, int id, boolean isCollect);
/**
* 取消收藏
*
* @param type 收藏类型,1大师 2文章 3商品
* @param id type=1时为大师id,type=2时为文章id,type=3为商品id (取消收藏时,id 为 coleectionId)
*/
void onCancelCollect(int type, int id);
}
interface ICollectModel {
void getCollect(int pageNum, ICollectCallback callback);
interface ICollectCallback extends IHandleCodeCallback {
void onCollectSuccess(CollectBean bean);
void onCollectFailure(String errorMsg);
}
/**
* 添加收藏
*
* @param type 收藏类型,1大师 2文章 3商品
* @param id type=1时为大师id,type=2时为文章id,type=3为商品id
*/
void addCollect(int type, int id, IAddCollectCallback callback);
interface IAddCollectCallback extends IHandleCodeCallback {
void onAddCollectSuccess(CollectBean bean,int id);
/**
* 添加收藏失败
* @param errMsg 提示语
*/
void onAddCollectFailure(String errMsg);
}
/**
* 取消收藏
*
* @param type 收藏类型,1大师 2文章 3商品
* @param keyId type=1时为大师id,type=2时为文章id,type=3为商品id
*/
void cancelCollect(int type, int keyId, ICancelCollectCallback callback);
interface ICancelCollectCallback extends IHandleCodeCallback {
/**
* 取消收藏成功
* @param bean
* @param id ID
*/
void onCancelCollectSuceess(CollectBean bean,int id);
/**
* 取消收藏失败
* @param errMsg 提示语
*/
void onCancelCollectFailure(String errMsg);
}
}
}
|
package org.alienideology.jcord.event.channel.group;
import org.alienideology.jcord.event.channel.ChannelDeleteEvent;
import org.alienideology.jcord.handle.channel.IGroup;
import org.alienideology.jcord.internal.object.IdentityImpl;
import org.alienideology.jcord.internal.object.channel.Channel;
import java.time.OffsetDateTime;
/**
* @author AlienIdeology
*/
public class GroupDeleteEvent extends ChannelDeleteEvent implements IGroupEvent {
public GroupDeleteEvent(IdentityImpl identity, int sequence, Channel channel, OffsetDateTime timeStamp) {
super(identity, sequence, channel, timeStamp);
}
@Override
public IGroup getGroup() {
return (IGroup) getChannel();
}
}
|
package com.zjc.netty.http;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpServerCodec;
/**
* @author : zoujc
* @date : 2021/7/7
* @description :
*/
public class TestServerInitializer extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
//向管道加入处理器
//得到管道
ChannelPipeline pipeline = socketChannel.pipeline();
//加入一个netty提供的httpServerCodec codec => [code - decoder]
//作用:1.httpServerCodec是netty提供的处理http的编解码器
//浏览器每刷新一次就会有一个新的pipeline
pipeline.addLast("MyHttpServerCodec", new HttpServerCodec());
//增加自定义处理器handler
pipeline.addLast("MyTestHttpServerHandler", new TestHttpServerHandler());
}
}
|
/**
*
*/
package test.nz.org.take.r2ml.d;
import org.apache.log4j.BasicConfigurator;
import junit.framework.TestCase;
import nz.org.take.deployment.KnowledgeBaseManager;
import nz.org.take.r2ml.R2MLDriver;
import nz.org.take.r2ml.R2MLException;
import nz.org.take.r2ml.R2MLKnowledgeSource;
import nz.org.take.rt.ResultSet;
import test.nz.org.take.r2ml.d.generated.ThingKB;
import test.nz.org.take.r2ml.d.generated.result;
import de.tu_cottbus.r2ml.RuleBase;
/**
* @author Bastian Schenke (bastian.schenke(at)googlemail.com)
*
*/
public class ReplacePropertyFunctionTest extends TestCase {
private ThingKB kb;
/**
* @param name
*/
public ReplacePropertyFunctionTest(String name) {
super(name);
BasicConfigurator.configure();
}
/* (non-Javadoc)
* @see junit.framework.TestCase#setUp()
*/
protected void setUp() throws Exception {
super.setUp();
R2MLKnowledgeSource kSrc = new R2MLKnowledgeSource(GenerateKbIf.class.getResourceAsStream("/test/nz/org/take/r2ml/d/properties2.r2ml"));
kSrc.setPropertyMode(R2MLDriver.INFER_PROPERTIES_MODE);
kSrc.setDatatypeMapper(new ThingMapper());
kSrc.setQueryGenerator(new ThingQueryGenerator());
KnowledgeBaseManager<ThingKB> kbM = new KnowledgeBaseManager<ThingKB>();
kb = kbM.getKnowledgeBase(ThingKB.class, kSrc);
}
/* (non-Javadoc)
* @see junit.framework.TestCase#tearDown()
*/
protected void tearDown() throws Exception {
super.tearDown();
kb = null;
}
public void test01 () throws R2MLException {
System.out.println("value>15");
assertNotNull(kb);
Thing thing1 = new Thing();
thing1.setValue(20);
ResultSet<result> result = kb.result_10(thing1);
assertTrue(result.hasNext());
System.out.println("20 is greater than 15");
result r1 = result.next();
assertFalse(result.hasNext());
Thing thing2 = new Thing();
thing2.setValue(10);
result = kb.result_10(thing2);
assertFalse(result.hasNext());
System.out.println("10 is not greater than 15");
}
}
|
package com.mango.leo.zsproject.login.listener;
import com.mango.leo.zsproject.bean.ErrorBean;
import com.mango.leo.zsproject.login.bean.UserMessageBean;
/**
* Created by admin on 2018/5/18.
*/
public interface OnUserStateListener {
void onSuccess(String string);
void onFailure(String msg, Exception e);
void getSuccessUserMessage(UserMessageBean bean);
void getErrorUserMessage(ErrorBean bean);
}
|
import mypack.DateImpl;
class DisplayDate
{
public static void main(String args[])
{
DateImpl obj=new DateImpl();
obj.showdate();
}
} |
/*
* The purpose of this lab is to learn about using the for loop
* and nested loops to create structured tables.
*
* Author: Victor (Zach) Johnson
* Date: 9/30/17
*/
package chapter5;
public class Ex5_18 {
public static void main(String[] args) {
patternA();
patternB();
patternC();
patternD();
}
public static void patternA() {
System.out.println("Pattern I");
for (int i = 1; i <= 6; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(j + " ");
}
System.out.println();
}
System.out.println();
}
public static void patternB() {
System.out.println("Pattern II");
for (int i = 1; i <= 6; i++) {
for (int j = 1; j <= 7 - i; j++) {
System.out.print(j + " ");
}
System.out.println();
}
System.out.println();
}
public static void patternC() {
System.out.println("Pattern III");
for (int i = 1; i <= 6; i++) {
for (int k = 1; k <= 6 - i; k++) {
System.out.print(" ");
}
for (int j = 1; j <= i; j++) {
System.out.print(j + " ");
}
System.out.println();
}
System.out.println();
}
public static void patternD() {
System.out.println("Pattern IV");
for (int i = 1; i <= 6; i++) {
for (int k = i; k > 1; k--) {
System.out.print(" ");
}
for (int j = 1; j <= 7 - i; j++) {
System.out.print(j + " ");
}
System.out.println();
}
System.out.println();
}
}
|
/**
* @Author: Mr.M
* @Date: 2019-05-21 21:08
* @Description:
**/
public class mapsizeDemo {
private static final int MAXIMUM_CAPACITY = 100;
public static void main(String[] args) {
int cap = 3;
int n = cap - 1;
n |= n >>> 1;
System.out.println(n);
n |= n >>> 2;
System.out.println(n);
n |= n >>> 4;
System.out.println(n);
n |= n >>> 8;
System.out.println(n);
n |= n >>> 16;
System.out.println(n);
System.out.println((n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1);
String a = "abc";
}
}
|
package com.atn.app.webservices;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.atn.app.datamodels.AtnPromotion;
import com.atn.app.datamodels.AtnPromotion.PromotionType;
import com.atn.app.datamodels.AtnRegisteredVenueData;
import com.atn.app.datamodels.UserDetail;
import com.atn.app.pool.UserDataPool;
import com.atn.app.utils.AtnUtils;
import com.atn.app.utils.HttpUtility;
import com.atn.app.webservices.WebserviceType.ServiceType;
public class MyDealsWebService extends WebserviceBase{
private final static String ATN_MY_DEALS = "/user/promotions";
private String userId;
private MyDealsWebServiceListener mMyDealsWebServiceListener;
public MyDealsWebService(String userId)
{
super(HttpUtility.BASE_SERVICE_URL + ATN_MY_DEALS);
setRequestType(RequestType.GET);
setWebserviceType(ServiceType.MY_DEAL);
setWebserviceListener(mWebserviceListener);
this.userId = userId;
}
public void setMyDealsWebServiceListener(MyDealsWebServiceListener listener)
{
mMyDealsWebServiceListener = listener;
}
WebserviceListener mWebserviceListener = new WebserviceListener()
{
@Override
public void onSetUrlError(ServiceType serviceType, Exception ex)
{
if(mMyDealsWebServiceListener != null)
{
if(serviceType == ServiceType.ADD_DEALS)
{
mMyDealsWebServiceListener.onFailed(WebserviceError.URL_ERROR, ex.getMessage());
}
}
}
@Override
public void onServiceResult(ServiceType serviceType, String result)
{
if(mMyDealsWebServiceListener != null)
{
if(serviceType == ServiceType.ADD_DEALS)
{
mMyDealsWebServiceListener.onSuccess(getAtnMyDealsData(result));
}
}
}
@Override
public void onServiceError(ServiceType serviceType, int errorCode, String errorMessage)
{
if(mMyDealsWebServiceListener != null)
{
if(serviceType == ServiceType.ADD_DEALS)
{
mMyDealsWebServiceListener.onFailed(errorCode, errorMessage);
}
}
}
@Override
public void onNoInternet(ServiceType serviceType, Exception ex)
{
if(mMyDealsWebServiceListener != null)
{
if(serviceType == ServiceType.ADD_DEALS)
{
mMyDealsWebServiceListener.onFailed(WebserviceError.INTERNET_ERROR, ex.getMessage());
}
}
}
};
/**
* Returns the parsed list of all ATN registered venue details using specified response from the server.
* It parses the ATN business details and add the ATN promotion details to that business if available.
*
* @param response data received from the server.
* @return Collection of ATN registered venue details.
*/
public ArrayList<AtnRegisteredVenueData> getAtnMyDealsData(String response)
{
ArrayList<AtnRegisteredVenueData> atnRegisteredVenueData = new ArrayList<AtnRegisteredVenueData>();
AtnRegisteredVenueData atnVenueData;
try
{
JSONArray jsonArray = new JSONArray(response);
JSONObject dataObject = null;
for(int i=0; i<jsonArray.length(); i++)
{
dataObject = (JSONObject) jsonArray.get(i);
if(dataObject == null)
{
return null;
}
atnVenueData = new AtnRegisteredVenueData();
/**
* Parsing JSON data to AtnRegisteredVenueData object.
*/
if(!dataObject.isNull(AtnRegisteredVenueData.BUSINESS))
{
if(!dataObject.getJSONObject(AtnRegisteredVenueData.BUSINESS).isNull(AtnRegisteredVenueData.BUSINESS_ID))
{
atnVenueData.setBusinessId(dataObject.getJSONObject(AtnRegisteredVenueData.BUSINESS).getString(AtnRegisteredVenueData.BUSINESS_ID));
}
if(!dataObject.getJSONObject(AtnRegisteredVenueData.BUSINESS).isNull(AtnRegisteredVenueData.BUSINESS_NAME))
{
atnVenueData.setBusinessName(dataObject.getJSONObject(AtnRegisteredVenueData.BUSINESS).getString(AtnRegisteredVenueData.BUSINESS_NAME));
}
if(!dataObject.getJSONObject(AtnRegisteredVenueData.BUSINESS).isNull(AtnRegisteredVenueData.BUSINESS_STREET))
{
atnVenueData.setBusinessStreet(dataObject.getJSONObject(AtnRegisteredVenueData.BUSINESS).getString(AtnRegisteredVenueData.BUSINESS_STREET));
}
if(!dataObject.getJSONObject(AtnRegisteredVenueData.BUSINESS).isNull(AtnRegisteredVenueData.BUSINESS_CITY))
{
atnVenueData.setBusinessCity(dataObject.getJSONObject(AtnRegisteredVenueData.BUSINESS).getString(AtnRegisteredVenueData.BUSINESS_CITY));
}
if(!dataObject.getJSONObject(AtnRegisteredVenueData.BUSINESS).isNull(AtnRegisteredVenueData.BUSINESS_STATE))
{
atnVenueData.setBusinessState(dataObject.getJSONObject(AtnRegisteredVenueData.BUSINESS).getString(AtnRegisteredVenueData.BUSINESS_STATE));
}
if(!dataObject.getJSONObject(AtnRegisteredVenueData.BUSINESS).isNull(AtnRegisteredVenueData.BUSINESS_ZIP))
{
atnVenueData.setBusinessZip(dataObject.getJSONObject(AtnRegisteredVenueData.BUSINESS).getString(AtnRegisteredVenueData.BUSINESS_ZIP));
}
if(!dataObject.getJSONObject(AtnRegisteredVenueData.BUSINESS).isNull(AtnRegisteredVenueData.BUSINESS_LAT))
{
atnVenueData.setBusinessLat(dataObject.getJSONObject(AtnRegisteredVenueData.BUSINESS).getString(AtnRegisteredVenueData.BUSINESS_LAT));
}
if(!dataObject.getJSONObject(AtnRegisteredVenueData.BUSINESS).isNull(AtnRegisteredVenueData.BUSINESS_LNG))
{
atnVenueData.setBusinessLng(dataObject.getJSONObject(AtnRegisteredVenueData.BUSINESS).getString(AtnRegisteredVenueData.BUSINESS_LNG));
}
if(!dataObject.getJSONObject(AtnRegisteredVenueData.BUSINESS).isNull(AtnRegisteredVenueData.BUSINESS_PHONE))
{
atnVenueData.setBusinessPhone(dataObject.getJSONObject(AtnRegisteredVenueData.BUSINESS).getString(AtnRegisteredVenueData.BUSINESS_PHONE));
}
if(!dataObject.getJSONObject(AtnRegisteredVenueData.BUSINESS).isNull(AtnRegisteredVenueData.BUSINESS_FB_LINK))
{
atnVenueData.setBusinessFacebookLink(dataObject.getJSONObject(AtnRegisteredVenueData.BUSINESS).getString(AtnRegisteredVenueData.BUSINESS_FB_LINK));
}
if(!dataObject.getJSONObject(AtnRegisteredVenueData.BUSINESS).isNull(AtnRegisteredVenueData.BUSINESS_FB_LINK_ID))
{
atnVenueData.setBusinessFacebookLinkId(dataObject.getJSONObject(AtnRegisteredVenueData.BUSINESS).getString(AtnRegisteredVenueData.BUSINESS_FB_LINK_ID));
}
if(!dataObject.getJSONObject(AtnRegisteredVenueData.BUSINESS).isNull(AtnRegisteredVenueData.BUSINESS_FS_VENUE_LINK))
{
atnVenueData.setBusinessFoursquareVenueLink(dataObject.getJSONObject(AtnRegisteredVenueData.BUSINESS).getString(AtnRegisteredVenueData.BUSINESS_FS_VENUE_LINK));
}
if(!dataObject.getJSONObject(AtnRegisteredVenueData.BUSINESS).isNull(AtnRegisteredVenueData.BUSINESS_FS_VENUE_ID))
{
atnVenueData.setBusinessFoursquareVenueId(dataObject.getJSONObject(AtnRegisteredVenueData.BUSINESS).getString(AtnRegisteredVenueData.BUSINESS_FS_VENUE_ID));
}
if(!dataObject.getJSONObject(AtnRegisteredVenueData.BUSINESS).isNull(AtnRegisteredVenueData.BUSINESS_IMAGE))
{
atnVenueData.setBusinessImageUrl(dataObject.getJSONObject(AtnRegisteredVenueData.BUSINESS).getString(AtnRegisteredVenueData.BUSINESS_IMAGE));
}
if(!dataObject.getJSONObject(AtnRegisteredVenueData.BUSINESS).isNull(AtnRegisteredVenueData.BUSINESS_FAVORITE))
{
atnVenueData.setFavorited(false);
}
else
{
atnVenueData.setFavorited(true);
}
if(!dataObject.getJSONObject(AtnRegisteredVenueData.BUSINESS).isNull(AtnRegisteredVenueData.BUSINESS_SUBSCRIBE))
{
atnVenueData.setSubscribed(false);
}
else
{
atnVenueData.setSubscribed(true);
}
/**
* After parsing data check whether there are any promotions available or not. If promotions
* are available then parse the promotion details and add promotion details to the specified
* ATN venue.
*/
JSONArray promotionArray = dataObject.getJSONArray(AtnPromotion.PROMOTION);
if(promotionArray.length() > 0)
{
for(int j=0; j<promotionArray.length(); j++)
{
AtnPromotion promotionDetail = getAtnPromotion(atnVenueData.getBusinessId(), promotionArray.getJSONObject(j));
if(promotionDetail != null)
{
atnVenueData.addPromotion(promotionDetail);
}
}
}
}
atnRegisteredVenueData.add(atnVenueData);
}
return atnRegisteredVenueData;
}
catch(JSONException ex)
{
ex.printStackTrace();
return null;
}
}
/**
* Returns the parsed AtnPromotion data from the JSON data.
*
* @param promotionObject JSON data of promotion
* @return AtnPromotion
*/
public AtnPromotion getAtnPromotion(String businessId, JSONObject promotionObject)
{
AtnPromotion atnPromotion = null;
try
{
JSONObject dataObject = promotionObject;
if(dataObject == null)
{
return null;
}
atnPromotion = new AtnPromotion();
atnPromotion.setBusinessId(businessId);
/**
* Parsing the promotion details to AtnPromotion.
*
*/
if(!dataObject.isNull(AtnPromotion.PROMOTION_ID))
{
atnPromotion.setPromotionId(dataObject.getString(AtnPromotion.PROMOTION_ID));
}
if(!dataObject.isNull(AtnPromotion.PROMOTION_TITLE))
{
atnPromotion.setPromotionTitle(dataObject.getString(AtnPromotion.PROMOTION_TITLE));
}
if(!dataObject.isNull(AtnPromotion.PROMOTION_DETAIL))
{
atnPromotion.setPromotionDetail(dataObject.getString(AtnPromotion.PROMOTION_DETAIL));
}
if(!dataObject.isNull(AtnPromotion.PROMOTION_EXPIRE_TIME))
{
atnPromotion.setCouponExpiryDate(dataObject.getString(AtnPromotion.PROMOTION_EXPIRE_TIME));
}
if(!dataObject.isNull(AtnPromotion.PROMOTION_TYPE))
{
int type = dataObject.getInt(AtnPromotion.PROMOTION_TYPE);
switch(type)
{
case 2:
atnPromotion.setPromotionType(PromotionType.Event);
break;
default:
atnPromotion.setPromotionType(PromotionType.Offer);
break;
}
}
if (!dataObject.isNull(AtnPromotion.PROMOTION_IS_GROUP)) {
if (dataObject.getInt(AtnPromotion.PROMOTION_IS_GROUP) > 0) {
atnPromotion.setGroup(true);
} else {
atnPromotion.setGroup(false);
}
}
if(!dataObject.isNull(AtnPromotion.PROMOTION_START_DATE)){
atnPromotion.setStartDate(dataObject.getString(AtnPromotion.PROMOTION_START_DATE));
}
if(!dataObject.isNull(AtnPromotion.PROMOTION_END_DATE)){
atnPromotion.setEndDate(dataObject.getString(AtnPromotion.PROMOTION_END_DATE));
}
if(!dataObject.isNull(AtnPromotion.PROMOTION_IS_NOTIFIED)){
atnPromotion.setNotified(dataObject.getBoolean(AtnPromotion.PROMOTION_IS_NOTIFIED));
}
if(!dataObject.isNull(AtnPromotion.PROMOTION_LOGO)){
atnPromotion.setPromotionLogoUrl(dataObject.getString(AtnPromotion.PROMOTION_LOGO));
}
if(!dataObject.isNull(AtnPromotion.PROMOTION_DAYS)){
atnPromotion.setPromotionDays(dataObject.getString(AtnPromotion.PROMOTION_DAYS));
}
if(!dataObject.isNull(AtnPromotion.PROMOTION_IS_DUPLICATE)){
atnPromotion.setDuplicate(dataObject.getBoolean(AtnPromotion.PROMOTION_IS_DUPLICATE));
}
/**
* Check the promotion's current status whether it is opened/shared/claimed/redeemed or expired.
*/
if(!dataObject.isNull(AtnPromotion.PROMOTION_STATUS))
{
atnPromotion.setPromotionStatus(AtnUtils.getInt(dataObject.getString(AtnPromotion.PROMOTION_STATUS)));
}
if (!dataObject.isNull(AtnPromotion.PROMOTION_SHARED)) {
atnPromotion.setShared(true);
} else {
atnPromotion.setShared(false);
}
/**
* Check the device DPI type and then set the image url of promotion.
*/
switch (AtnUtils.getDeviceType()) {
case LDPI:
if (!dataObject.isNull(AtnPromotion.PROMOTION_IMAGE_SMALL)) {
atnPromotion.setPromotionImageSmallUrl(dataObject.getString(AtnPromotion.PROMOTION_IMAGE_SMALL));
}
break;
case MDPI:
if (!dataObject.isNull(AtnPromotion.PROMOTION_IMAGE_SMALL)) {
atnPromotion.setPromotionImageSmallUrl(dataObject.getString(AtnPromotion.PROMOTION_IMAGE_SMALL));
}
break;
default:
if (!dataObject.isNull(AtnPromotion.PROMOTION_IMAGE_LARGE)) {
atnPromotion.setPromotionImageLargeUrl(dataObject.getString(AtnPromotion.PROMOTION_IMAGE_LARGE));
}
break;
}
return atnPromotion;
}
catch(JSONException ex){
ex.printStackTrace();
return null;
}
}
/**
* Asynchronously calls the web service to get the my Total Deals . Response of this web service can
* be captured from web service listener.
*/
public void getMyDeals()
{
try
{
ArrayList<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
if(userId != null)
{
nameValuePair.add(new BasicNameValuePair(UserDetail.USER_ID, userId));
setPostData(nameValuePair);
doRequestAsync();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
public WebserviceResponse getMyDealsSynchronous() {
try {
ArrayList<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
if (userId != null) {
nameValuePair.add(new BasicNameValuePair(UserDetail.USER_ID,UserDataPool.getInstance().getUserDetail().getUserId()));
setPostData(nameValuePair);
return doRequestSynch();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
|
/*
* 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 agendascc.DATA;
import java.beans.*;
/**
*
* @author JTF
*/
public class ContactoBeanInfo extends SimpleBeanInfo {
// Bean descriptor//GEN-FIRST:BeanDescriptor
/*lazy BeanDescriptor*/
private static BeanDescriptor getBdescriptor(){
BeanDescriptor beanDescriptor = new BeanDescriptor ( agendascc.DATA.Contacto.class , null ); // NOI18N
beanDescriptor.setExpert ( true );
beanDescriptor.setPreferred ( true );//GEN-HEADEREND:BeanDescriptor
// Here you can add code for customizing the BeanDescriptor.
return beanDescriptor; }//GEN-LAST:BeanDescriptor
// Property identifiers//GEN-FIRST:Properties
private static final int PROPERTY_codigoPostal = 0;
private static final int PROPERTY_colonia = 1;
private static final int PROPERTY_comentarios = 2;
private static final int PROPERTY_direccion = 3;
private static final int PROPERTY_direccionReferencias = 4;
private static final int PROPERTY_email = 5;
private static final int PROPERTY_estado = 6;
private static final int PROPERTY_idContacto = 7;
private static final int PROPERTY_imagen = 8;
private static final int PROPERTY_localidad = 9;
private static final int PROPERTY_municipio = 10;
private static final int PROPERTY_nombre = 11;
private static final int PROPERTY_pais = 12;
private static final int PROPERTY_pseudonimo = 13;
private static final int PROPERTY_telefonoList = 14;
private static final int PROPERTY_tipo = 15;
// Property array
/*lazy PropertyDescriptor*/
private static PropertyDescriptor[] getPdescriptor(){
PropertyDescriptor[] properties = new PropertyDescriptor[16];
try {
properties[PROPERTY_codigoPostal] = new PropertyDescriptor ( "codigoPostal", agendascc.DATA.Contacto.class, "getCodigoPostal", "setCodigoPostal" ); // NOI18N
properties[PROPERTY_codigoPostal].setExpert ( true );
properties[PROPERTY_codigoPostal].setPreferred ( true );
properties[PROPERTY_codigoPostal].setBound ( true );
properties[PROPERTY_colonia] = new PropertyDescriptor ( "colonia", agendascc.DATA.Contacto.class, "getColonia", "setColonia" ); // NOI18N
properties[PROPERTY_colonia].setExpert ( true );
properties[PROPERTY_colonia].setPreferred ( true );
properties[PROPERTY_colonia].setBound ( true );
properties[PROPERTY_comentarios] = new PropertyDescriptor ( "comentarios", agendascc.DATA.Contacto.class, "getComentarios", "setComentarios" ); // NOI18N
properties[PROPERTY_comentarios].setExpert ( true );
properties[PROPERTY_comentarios].setPreferred ( true );
properties[PROPERTY_comentarios].setBound ( true );
properties[PROPERTY_direccion] = new PropertyDescriptor ( "direccion", agendascc.DATA.Contacto.class, "getDireccion", "setDireccion" ); // NOI18N
properties[PROPERTY_direccion].setExpert ( true );
properties[PROPERTY_direccion].setPreferred ( true );
properties[PROPERTY_direccion].setBound ( true );
properties[PROPERTY_direccionReferencias] = new PropertyDescriptor ( "direccionReferencias", agendascc.DATA.Contacto.class, "getDireccionReferencias", "setDireccionReferencias" ); // NOI18N
properties[PROPERTY_direccionReferencias].setExpert ( true );
properties[PROPERTY_direccionReferencias].setPreferred ( true );
properties[PROPERTY_direccionReferencias].setBound ( true );
properties[PROPERTY_email] = new PropertyDescriptor ( "email", agendascc.DATA.Contacto.class, "getEmail", "setEmail" ); // NOI18N
properties[PROPERTY_email].setExpert ( true );
properties[PROPERTY_email].setPreferred ( true );
properties[PROPERTY_email].setBound ( true );
properties[PROPERTY_estado] = new PropertyDescriptor ( "estado", agendascc.DATA.Contacto.class, "getEstado", "setEstado" ); // NOI18N
properties[PROPERTY_estado].setExpert ( true );
properties[PROPERTY_estado].setPreferred ( true );
properties[PROPERTY_estado].setBound ( true );
properties[PROPERTY_idContacto] = new PropertyDescriptor ( "idContacto", agendascc.DATA.Contacto.class, "getIdContacto", "setIdContacto" ); // NOI18N
properties[PROPERTY_idContacto].setExpert ( true );
properties[PROPERTY_idContacto].setPreferred ( true );
properties[PROPERTY_idContacto].setBound ( true );
properties[PROPERTY_imagen] = new PropertyDescriptor ( "imagen", agendascc.DATA.Contacto.class, "getImagen", "setImagen" ); // NOI18N
properties[PROPERTY_imagen].setExpert ( true );
properties[PROPERTY_imagen].setPreferred ( true );
properties[PROPERTY_imagen].setBound ( true );
properties[PROPERTY_localidad] = new PropertyDescriptor ( "localidad", agendascc.DATA.Contacto.class, "getLocalidad", "setLocalidad" ); // NOI18N
properties[PROPERTY_localidad].setExpert ( true );
properties[PROPERTY_localidad].setPreferred ( true );
properties[PROPERTY_localidad].setBound ( true );
properties[PROPERTY_municipio] = new PropertyDescriptor ( "municipio", agendascc.DATA.Contacto.class, "getMunicipio", "setMunicipio" ); // NOI18N
properties[PROPERTY_municipio].setExpert ( true );
properties[PROPERTY_municipio].setPreferred ( true );
properties[PROPERTY_municipio].setBound ( true );
properties[PROPERTY_nombre] = new PropertyDescriptor ( "nombre", agendascc.DATA.Contacto.class, "getNombre", "setNombre" ); // NOI18N
properties[PROPERTY_nombre].setExpert ( true );
properties[PROPERTY_nombre].setPreferred ( true );
properties[PROPERTY_nombre].setBound ( true );
properties[PROPERTY_pais] = new PropertyDescriptor ( "pais", agendascc.DATA.Contacto.class, "getPais", "setPais" ); // NOI18N
properties[PROPERTY_pais].setExpert ( true );
properties[PROPERTY_pais].setPreferred ( true );
properties[PROPERTY_pais].setBound ( true );
properties[PROPERTY_pseudonimo] = new PropertyDescriptor ( "pseudonimo", agendascc.DATA.Contacto.class, "getPseudonimo", "setPseudonimo" ); // NOI18N
properties[PROPERTY_pseudonimo].setExpert ( true );
properties[PROPERTY_pseudonimo].setPreferred ( true );
properties[PROPERTY_pseudonimo].setBound ( true );
properties[PROPERTY_telefonoList] = new PropertyDescriptor ( "telefonoList", agendascc.DATA.Contacto.class, "getTelefonoList", "setTelefonoList" ); // NOI18N
properties[PROPERTY_telefonoList].setExpert ( true );
properties[PROPERTY_telefonoList].setPreferred ( true );
properties[PROPERTY_telefonoList].setBound ( true );
properties[PROPERTY_tipo] = new PropertyDescriptor ( "tipo", agendascc.DATA.Contacto.class, "getTipo", "setTipo" ); // NOI18N
properties[PROPERTY_tipo].setExpert ( true );
properties[PROPERTY_tipo].setPreferred ( true );
properties[PROPERTY_tipo].setBound ( true );
}
catch(IntrospectionException e) {
e.printStackTrace();
}//GEN-HEADEREND:Properties
// Here you can add code for customizing the properties array.
return properties; }//GEN-LAST:Properties
// EventSet identifiers//GEN-FIRST:Events
// EventSet array
/*lazy EventSetDescriptor*/
private static EventSetDescriptor[] getEdescriptor(){
EventSetDescriptor[] eventSets = new EventSetDescriptor[0];//GEN-HEADEREND:Events
// Here you can add code for customizing the event sets array.
return eventSets; }//GEN-LAST:Events
// Method information will be obtained from introspection.//GEN-FIRST:Methods
private static MethodDescriptor[] methods = null;
private static MethodDescriptor[] getMdescriptor(){//GEN-HEADEREND:Methods
// Here you can add code for customizing the methods array.
return methods; }//GEN-LAST:Methods
private static java.awt.Image iconColor16 = null;//GEN-BEGIN:IconsDef
private static java.awt.Image iconColor32 = null;
private static java.awt.Image iconMono16 = null;
private static java.awt.Image iconMono32 = null;//GEN-END:IconsDef
private static String iconNameC16 = null;//GEN-BEGIN:Icons
private static String iconNameC32 = null;
private static String iconNameM16 = null;
private static String iconNameM32 = null;//GEN-END:Icons
private static final int defaultPropertyIndex = -1;//GEN-BEGIN:Idx
private static final int defaultEventIndex = -1;//GEN-END:Idx
//GEN-FIRST:Superclass
// Here you can add code for customizing the Superclass BeanInfo.
//GEN-LAST:Superclass
/**
* Gets the bean's <code>BeanDescriptor</code>s.
*
* @return BeanDescriptor describing the editable properties of this bean.
* May return null if the information should be obtained by automatic
* analysis.
*/
@Override
public BeanDescriptor getBeanDescriptor() {
return getBdescriptor();
}
/**
* Gets the bean's <code>PropertyDescriptor</code>s.
*
* @return An array of PropertyDescriptors describing the editable
* properties supported by this bean. May return null if the information
* should be obtained by automatic analysis.
* <p>
* If a property is indexed, then its entry in the result array will belong
* to the IndexedPropertyDescriptor subclass of PropertyDescriptor. A client
* of getPropertyDescriptors can use "instanceof" to check if a given
* PropertyDescriptor is an IndexedPropertyDescriptor.
*/
@Override
public PropertyDescriptor[] getPropertyDescriptors() {
return getPdescriptor();
}
/**
* Gets the bean's <code>EventSetDescriptor</code>s.
*
* @return An array of EventSetDescriptors describing the kinds of events
* fired by this bean. May return null if the information should be obtained
* by automatic analysis.
*/
@Override
public EventSetDescriptor[] getEventSetDescriptors() {
return getEdescriptor();
}
/**
* Gets the bean's <code>MethodDescriptor</code>s.
*
* @return An array of MethodDescriptors describing the methods implemented
* by this bean. May return null if the information should be obtained by
* automatic analysis.
*/
@Override
public MethodDescriptor[] getMethodDescriptors() {
return getMdescriptor();
}
/**
* A bean may have a "default" property that is the property that will
* mostly commonly be initially chosen for update by human's who are
* customizing the bean.
*
* @return Index of default property in the PropertyDescriptor array
* returned by getPropertyDescriptors.
* <P>
* Returns -1 if there is no default property.
*/
@Override
public int getDefaultPropertyIndex() {
return defaultPropertyIndex;
}
/**
* A bean may have a "default" event that is the event that will mostly
* commonly be used by human's when using the bean.
*
* @return Index of default event in the EventSetDescriptor array returned
* by getEventSetDescriptors.
* <P>
* Returns -1 if there is no default event.
*/
@Override
public int getDefaultEventIndex() {
return defaultEventIndex;
}
/**
* This method returns an image object that can be used to represent the
* bean in toolboxes, toolbars, etc. Icon images will typically be GIFs, but
* may in future include other formats.
* <p>
* Beans aren't required to provide icons and may return null from this
* method.
* <p>
* There are four possible flavors of icons (16x16 color, 32x32 color, 16x16
* mono, 32x32 mono). If a bean choses to only support a single icon we
* recommend supporting 16x16 color.
* <p>
* We recommend that icons have a "transparent" background so they can be
* rendered onto an existing background.
*
* @param iconKind The kind of icon requested. This should be one of the
* constant values ICON_COLOR_16x16, ICON_COLOR_32x32, ICON_MONO_16x16, or
* ICON_MONO_32x32.
* @return An image object representing the requested icon. May return null
* if no suitable icon is available.
*/
@Override
public java.awt.Image getIcon(int iconKind) {
switch (iconKind) {
case ICON_COLOR_16x16:
if (iconNameC16 == null) {
return null;
} else {
if (iconColor16 == null) {
iconColor16 = loadImage(iconNameC16);
}
return iconColor16;
}
case ICON_COLOR_32x32:
if (iconNameC32 == null) {
return null;
} else {
if (iconColor32 == null) {
iconColor32 = loadImage(iconNameC32);
}
return iconColor32;
}
case ICON_MONO_16x16:
if (iconNameM16 == null) {
return null;
} else {
if (iconMono16 == null) {
iconMono16 = loadImage(iconNameM16);
}
return iconMono16;
}
case ICON_MONO_32x32:
if (iconNameM32 == null) {
return null;
} else {
if (iconMono32 == null) {
iconMono32 = loadImage(iconNameM32);
}
return iconMono32;
}
default:
return null;
}
}
}
|
package com.aummn.suburb.validator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SuburbValidator {
public final static String SUBURB_NAME_PATTERN = "^[a-zA-Z0-9',.\\s-]{1,100}$";
public final static String POSTCODE_PATTERN = "^[0-9]{4}$";
public static FieldValidationResult validateSuburbName(String name) {
boolean isValid = false;
Pattern pattern = Pattern.compile(SUBURB_NAME_PATTERN, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(name);
boolean matchFound = matcher.find();
if(matchFound) {
if(name.length() >= 1 && name.length() <= 100) {
}
isValid = true;
}
String message = isValid ? "" : "name error";
return FieldValidationResult.builder().valid(isValid).message(message).build();
}
public static FieldValidationResult validatePostcode(String postcode) {
boolean isValid = false;
Pattern pattern = Pattern.compile(POSTCODE_PATTERN, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(postcode);
boolean matchFound = matcher.find();
if(matchFound) {
isValid = true;
}
String message = isValid ? "" : "post code error";
return FieldValidationResult.builder().valid(isValid).message(message).build();
}
public static FieldValidationResult validateSuburbId(Long id) {
boolean isValid = false;
if(id > 0) {
isValid = true;
}
String message = isValid ? "" : "id error";
return FieldValidationResult.builder().valid(isValid).message(message).build();
}
}
|
package com.espendwise.manta.dao;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.espendwise.manta.model.data.BusEntityAssocData;
import com.espendwise.manta.model.data.BusEntityData;
import com.espendwise.manta.model.data.ItemData;
import com.espendwise.manta.model.data.ItemMetaData;
import com.espendwise.manta.model.data.ShoppingControlData;
import com.espendwise.manta.model.view.CatalogListView;
import com.espendwise.manta.model.view.ShoppingControlItemView;
import com.espendwise.manta.util.Constants;
import com.espendwise.manta.util.RefCodeNames;
import com.espendwise.manta.util.Utility;
import com.espendwise.manta.util.criteria.AccountShoppingControlItemViewCriteria;
@Repository
public class ShoppingControlDAOImpl extends DAOImpl implements ShoppingControlDAO {
private static final Logger logger = Logger.getLogger(ShoppingControlDAOImpl.class);
public static final Long DEFAULT_QUANTITY = new Long(-1);
public static final Long DEFAULT_BUS_ENTITY_ID = new Long(0);
public ShoppingControlDAOImpl() {
this(null);
}
public ShoppingControlDAOImpl(EntityManager entityManager) {
super(entityManager);
}
@Override
public List<ShoppingControlItemView> findShoppingControls(AccountShoppingControlItemViewCriteria criteria) {
//get the account catalog id
//JEE TODO - use the CatalogDAO for this
StringBuilder accountCatalogQuery = new StringBuilder("select distinct new com.espendwise.manta.model.view.CatalogListView(");
accountCatalogQuery.append(" catalog.catalogId) ");
accountCatalogQuery.append(" from com.espendwise.manta.model.fullentity.CatalogFullEntity catalog ");
accountCatalogQuery.append(" inner join catalog.catalogAssocs assoc ");
accountCatalogQuery.append(" where catalog.catalogTypeCd = '");
accountCatalogQuery.append(RefCodeNames.CATALOG_TYPE_CD.ACCOUNT);
accountCatalogQuery.append("' and catalog.catalogStatusCd <> '");
accountCatalogQuery.append(RefCodeNames.CATALOG_STATUS_CD.INACTIVE);
accountCatalogQuery.append("' and catalog.catalogId = assoc.catalogId ");
accountCatalogQuery.append(" and assoc.catalogAssocCd = '");
accountCatalogQuery.append(RefCodeNames.CATALOG_ASSOC_CD.CATALOG_ACCOUNT);
accountCatalogQuery.append("' and assoc.busEntityId = ");
accountCatalogQuery.append(criteria.getAccountId());
Query q = em.createQuery(accountCatalogQuery.toString());
List<CatalogListView> catalogs = q.getResultList();
Long accountCatalogId = null;
if (catalogs.size() == 0) {
throw new IllegalStateException("No active account catalog has been specified.");
}
else if (catalogs.size() > 1) {
throw new IllegalStateException("Multiple active account catalogs have been specified.");
}
else {
accountCatalogId = catalogs.get(0).getCatalogId();
}
//now get the store catalog id
//first we need to get the id of the store associated with the account
BusEntityAssocDAO busEntityAssocDao = new BusEntityAssocDAOImpl(em);
List<BusEntityAssocData> busEntityAssocs = busEntityAssocDao.findAssocs(criteria.getAccountId(), new ArrayList<Long>(), RefCodeNames.BUS_ENTITY_ASSOC_CD.ACCOUNT_OF_STORE);
Long storeId = null;
if (busEntityAssocs.size() == 0) {
throw new IllegalStateException("No store is associated with the specified account.");
}
else if (busEntityAssocs.size() > 1) {
throw new IllegalStateException("Multiple stores are associated with the specified account.");
}
else {
storeId = busEntityAssocs.get(0).getBusEntity2Id();
}
//now we can get the catalog id
//JEE TODO - use the CatalogDAO for this
StringBuilder storeCatalogQuery = new StringBuilder("select distinct new com.espendwise.manta.model.view.CatalogListView(");
storeCatalogQuery.append(" catalog.catalogId) ");
storeCatalogQuery.append(" from com.espendwise.manta.model.fullentity.CatalogFullEntity catalog ");
storeCatalogQuery.append(" inner join catalog.catalogAssocs assoc ");
storeCatalogQuery.append(" where catalog.catalogTypeCd = '");
storeCatalogQuery.append(RefCodeNames.CATALOG_TYPE_CD.STORE);
storeCatalogQuery.append("' and catalog.catalogStatusCd = '");
storeCatalogQuery.append(RefCodeNames.CATALOG_STATUS_CD.ACTIVE);
storeCatalogQuery.append("' and catalog.catalogId = assoc.catalogId ");
storeCatalogQuery.append(" and assoc.catalogAssocCd = '");
storeCatalogQuery.append(RefCodeNames.CATALOG_ASSOC_CD.CATALOG_STORE);
storeCatalogQuery.append("' and assoc.busEntityId = ");
storeCatalogQuery.append(storeId);
q = em.createQuery(storeCatalogQuery.toString());
catalogs = q.getResultList();
Long storeCatalogId = null;
if (catalogs.size() == 0) {
throw new IllegalStateException("No active store catalog has been specified.");
}
else if (catalogs.size() > 1) {
throw new IllegalStateException("Multiple active store catalogs have been specified.");
}
else {
storeCatalogId = catalogs.get(0).getCatalogId();
}
//now get the ids of the items in both the account and store catalogs.
StringBuilder accountCatalogItemQuery = new StringBuilder("Select distinct catalogStructure.itemId from CatalogStructureData catalogStructure");
accountCatalogItemQuery.append(" where catalogStructure.catalogId = ");
accountCatalogItemQuery.append(accountCatalogId);
accountCatalogItemQuery.append(" and catalogStructure.catalogStructureCd = '");
accountCatalogItemQuery.append(RefCodeNames.CATALOG_STRUCTURE_CD.CATALOG_PRODUCT);
accountCatalogItemQuery.append("'");
StringBuilder storeCatalogItemQuery = new StringBuilder("Select distinct catalogStructure.itemId from CatalogStructureData catalogStructure");
storeCatalogItemQuery.append(" where catalogStructure.catalogId = ");
storeCatalogItemQuery.append(storeCatalogId);
storeCatalogItemQuery.append(" and catalogStructure.catalogStructureCd = '");
storeCatalogItemQuery.append(RefCodeNames.CATALOG_STRUCTURE_CD.CATALOG_PRODUCT);
storeCatalogItemQuery.append("'");
StringBuilder itemQuery = new StringBuilder("select item.itemId from ItemData item");
itemQuery.append(" where item.itemTypeCd = '");
itemQuery.append(RefCodeNames.ITEM_TYPE_CD.PRODUCT);
itemQuery.append("'");
itemQuery.append(" and item.itemId in (");
itemQuery.append(accountCatalogItemQuery.toString());
itemQuery.append(")");
itemQuery.append(" and item.itemId in (");
itemQuery.append(storeCatalogItemQuery.toString());
itemQuery.append(")");
//if any item ids were specified in the search criteria, restrict the search to just those items
List<Long> criteriaIds = Utility.toIds(criteria.getItems());
if (Utility.isSet(criteriaIds)) {
//JEE TODO - handle situation where criteriaIds > 1000
itemQuery.append(" and item.itemId in (:criteriaIds)");
}
q = em.createQuery(itemQuery.toString());
if (Utility.isSet(criteriaIds)) {
//JEE TODO - handle situation where criteriaIds > 1000
q.setParameter("criteriaIds", criteriaIds);
}
List<Long> itemIds = q.getResultList();
//MANTA-442
if (!Utility.isSet(itemIds)) {
return new ArrayList<ShoppingControlItemView>();
}
//if a maximum number of results was specified in the search criteria, pare the item ids down to
//that maximum if necessary
//JEE TODO - need to show a message somehow if more results were found than what we return
if (criteria.getLimit() != null && itemIds.size() > criteria.getLimit().intValue()) {
itemIds = itemIds.subList(0, criteria.getLimit().intValue());
}
//If the user has requested to view uncontrolled items, create a ShoppingControlItemView object for each
//item id found above. Populate it with the account id and item id.
Map<Long, ShoppingControlItemView> shoppingControlItemViewMap = new HashMap<Long, ShoppingControlItemView>();
if (criteria.getShowUncontrolledItems()) {
Iterator<Long> itemIdIterator = itemIds.iterator();
while (itemIdIterator.hasNext()) {
Long itemId = itemIdIterator.next();
ShoppingControlItemView shoppingControlItemView = new ShoppingControlItemView();
shoppingControlItemView.setShoppingControlAccountId(criteria.getAccountId());
shoppingControlItemView.setItemId(itemId);
shoppingControlItemViewMap.put(itemId, shoppingControlItemView);
}
}
//get any existing shopping controls for the item ids retrieved above. if we retrieve any
//shopping controls, replace the corresponding empty ones created in the previous
//step with the existing ones
StringBuilder shoppingControlQuery = new StringBuilder("select object(shoppingControl) from ShoppingControlData shoppingControl");
shoppingControlQuery.append(" where shoppingControl.accountId = ");
shoppingControlQuery.append(criteria.getAccountId());
shoppingControlQuery.append(" and shoppingControl.siteId = ");
shoppingControlQuery.append(criteria.getLocationId());
//JEE TODO - handle situation where itemIds > 1000
shoppingControlQuery.append(" and shoppingControl.itemId in (:itemIds)");
q = em.createQuery(shoppingControlQuery.toString());
//JEE TODO - handle situation where itemIds > 1000
q.setParameter("itemIds", itemIds);
List<ShoppingControlData> shoppingControls = q.getResultList();
if (Utility.isSet(shoppingControls)) {
Iterator<ShoppingControlData> shoppingControlIterator = shoppingControls.iterator();
while (shoppingControlIterator.hasNext()) {
ShoppingControlData shoppingControl = shoppingControlIterator.next();
ShoppingControlItemView shoppingControlItemView = shoppingControlItemViewMap.get(shoppingControl.getItemId());
if (shoppingControlItemView == null) {
shoppingControlItemView = new ShoppingControlItemView();
shoppingControlItemView.setShoppingControlAccountId(shoppingControl.getAccountId());
shoppingControlItemView.setItemId(shoppingControl.getItemId());
shoppingControlItemViewMap.put(shoppingControl.getItemId(), shoppingControlItemView);
}
shoppingControlItemView.setShoppingControlId(shoppingControl.getShoppingControlId());
shoppingControlItemView.setShoppingControlLocationId(shoppingControl.getSiteId());
shoppingControlItemView.setShoppingControlMaxOrderQty(shoppingControl.getMaxOrderQty().toString());
shoppingControlItemView.setShoppingControlRestrictionDays(shoppingControl.getRestrictionDays().toString());
shoppingControlItemView.setShoppingControlAction(shoppingControl.getActionCd());
}
}
//get item information about the specified items
itemQuery = new StringBuilder("select object(item) from ItemData item where item.itemId in (:itemIds) order by item.itemId asc");
//JEE TODO - handle situation where itemIds > 1000
q = em.createQuery(itemQuery.toString());
//JEE TODO - handle situation where itemIds > 1000
q.setParameter("itemIds", itemIds);
List<ItemData> items = q.getResultList();
//populate the ShoppingControlItemViews created above with information about the items
Iterator<ItemData> itemIterator = items.iterator();
while (itemIterator.hasNext()) {
ItemData item = itemIterator.next();
ShoppingControlItemView shoppingControlItemView = shoppingControlItemViewMap.get(item.getItemId());
if (shoppingControlItemView != null) {
shoppingControlItemView.setItemId(item.getItemId());
shoppingControlItemView.setItemShortDesc(item.getShortDesc());
shoppingControlItemView.setItemSku(item.getSkuNum().toString());
}
}
//get item meta data information about the specified items
StringBuilder itemMetaDataQuery = new StringBuilder("select object(itemMetaData) from ItemMetaData itemMetaData");
itemMetaDataQuery.append(" where itemMetaData.itemId in (:itemIds)");
itemMetaDataQuery.append(" and itemMetaData.nameValue in (:nameValues)");
itemMetaDataQuery.append(" order by itemMetaData.itemId asc, itemMetaData.itemMetaId asc");
//JEE TODO - handle situation where itemIds > 1000
q = em.createQuery(itemMetaDataQuery.toString());
//JEE TODO - handle situation where itemIds > 1000
q.setParameter("itemIds", itemIds);
List<String> nameValues = new ArrayList<String>();
nameValues.add(RefCodeNames.NAME_VALUE_CD.PACK);
nameValues.add(RefCodeNames.NAME_VALUE_CD.SIZE);
nameValues.add(RefCodeNames.NAME_VALUE_CD.UNIT_OF_MEASURE);
q.setParameter("nameValues", nameValues);
List<ItemMetaData> itemMetaDatas = q.getResultList();
//populate the ShoppingControlItemViews created above with meta information about the items
Iterator<ItemMetaData> itemMetaDataIterator = itemMetaDatas.iterator();
while (itemMetaDataIterator.hasNext()) {
ItemMetaData itemMetaData = itemMetaDataIterator.next();
ShoppingControlItemView shoppingControlItemView = shoppingControlItemViewMap.get(itemMetaData.getItemId());
if (shoppingControlItemView != null) {
if (RefCodeNames.NAME_VALUE_CD.PACK.equalsIgnoreCase(itemMetaData.getNameValue())) {
shoppingControlItemView.setItemPack(itemMetaData.getValue());
}
else if (RefCodeNames.NAME_VALUE_CD.SIZE.equalsIgnoreCase(itemMetaData.getNameValue())) {
shoppingControlItemView.setItemSize(itemMetaData.getValue());
}
else if (RefCodeNames.NAME_VALUE_CD.UNIT_OF_MEASURE.equalsIgnoreCase(itemMetaData.getNameValue())) {
shoppingControlItemView.setItemUom(itemMetaData.getValue());
}
}
}
//return the list of ShoppingControlItemView objects. First though populate the original action, max quantity,
//and restriction days values and then convert any unlimited values to asterisks
List<ShoppingControlItemView> result = new ArrayList<ShoppingControlItemView>(shoppingControlItemViewMap.values());
Iterator<ShoppingControlItemView> resultIterator = result.iterator();
while (resultIterator.hasNext()) {
ShoppingControlItemView shoppingControl = resultIterator.next();
shoppingControl.setShoppingControlOriginalAction(shoppingControl.getShoppingControlAction());
shoppingControl.setShoppingControlOriginalMaxOrderQty(shoppingControl.getShoppingControlMaxOrderQty());
shoppingControl.setShoppingControlOriginalRestrictionDays(shoppingControl.getShoppingControlRestrictionDays());
if (DEFAULT_QUANTITY.toString().equals(shoppingControl.getShoppingControlMaxOrderQty())) {
shoppingControl.setShoppingControlMaxOrderQty(Constants.CHARS.ASTERISK);
}
if (DEFAULT_QUANTITY.toString().equals(shoppingControl.getShoppingControlRestrictionDays())) {
shoppingControl.setShoppingControlRestrictionDays(Constants.CHARS.ASTERISK);
}
}
logger.info("findShoppingControls()===> found : "+ result.size());
return result;
}
@Override
@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
public Map<String,List<ShoppingControlItemView>> updateShoppingControls(List<ShoppingControlItemView> shoppingControls) {
Map<String,List<ShoppingControlItemView>> returnValue = new HashMap<String,List<ShoppingControlItemView>>();
returnValue.put(RefCodeNames.HISTORY_TYPE_CD.CREATED, new ArrayList<ShoppingControlItemView>());
returnValue.put(RefCodeNames.HISTORY_TYPE_CD.MODIFIED, new ArrayList<ShoppingControlItemView>());
if (Utility.isSet(shoppingControls)) {
Map<Long, String> busEntityMap = new HashMap<Long,String>();
Iterator<ShoppingControlItemView> shoppingControlIterator = shoppingControls.iterator();
while (shoppingControlIterator.hasNext()) {
ShoppingControlItemView shoppingControl = shoppingControlIterator.next();
//convert any asterisks to their default values
if (Constants.CHARS.ASTERISK.equals(shoppingControl.getShoppingControlMaxOrderQty())) {
shoppingControl.setShoppingControlMaxOrderQty(ShoppingControlDAOImpl.DEFAULT_QUANTITY.toString());
}
if (Constants.CHARS.ASTERISK.equals(shoppingControl.getShoppingControlRestrictionDays())) {
shoppingControl.setShoppingControlRestrictionDays(ShoppingControlDAOImpl.DEFAULT_QUANTITY.toString());
}
if (shoppingControlIsModified(shoppingControl)) {
populateBusEntityInfo(shoppingControl, busEntityMap);
if (Utility.isNew(shoppingControl)) {
createShoppingControl(shoppingControl);
returnValue.get(RefCodeNames.HISTORY_TYPE_CD.CREATED).add(shoppingControl);
}
else {
updateShoppingControl(shoppingControl);
returnValue.get(RefCodeNames.HISTORY_TYPE_CD.MODIFIED).add(shoppingControl);
}
}
}
}
return returnValue;
}
private void populateBusEntityInfo(ShoppingControlItemView shoppingControl, Map<Long, String> busEntityMap) {
Long locationId = shoppingControl.getShoppingControlLocationId();
if (Utility.isSet(locationId) && !ShoppingControlDAOImpl.DEFAULT_BUS_ENTITY_ID.equals(locationId)) {
String busEntityName = busEntityMap.get(locationId);
if (!Utility.isSet(busEntityName)) {
busEntityName = getBusEntityName(locationId);
busEntityMap.put(locationId, busEntityName);
}
shoppingControl.setShoppingControlLocationName(busEntityName);
}
Long accountId = shoppingControl.getShoppingControlAccountId();
if (Utility.isSet(accountId) && !ShoppingControlDAOImpl.DEFAULT_BUS_ENTITY_ID.equals(accountId)) {
String busEntityName = busEntityMap.get(accountId);
if (!Utility.isSet(busEntityName)) {
busEntityName = getBusEntityName(accountId);
busEntityMap.put(accountId, busEntityName);
}
shoppingControl.setShoppingControlAccountName(busEntityName);
}
//populate the store id and name. Use the account id if it exists, otherwise use the location id
Long storeId = null;
String storeName = null;
if (Utility.isSet(accountId) && !ShoppingControlDAOImpl.DEFAULT_BUS_ENTITY_ID.equals(accountId)) {
storeId = getStoreId(accountId, RefCodeNames.BUS_ENTITY_TYPE_CD.ACCOUNT);
storeName = busEntityMap.get(storeId);
if (!Utility.isSet(storeName)) {
storeName = getBusEntityName(storeId);
busEntityMap.put(storeId, storeName);
}
}
else if (Utility.isSet(locationId) && !ShoppingControlDAOImpl.DEFAULT_BUS_ENTITY_ID.equals(locationId)) {
storeId = getStoreId(locationId, RefCodeNames.BUS_ENTITY_TYPE_CD.SITE);
storeName = busEntityMap.get(storeId);
if (!Utility.isSet(storeName)) {
storeName = getBusEntityName(storeId);
busEntityMap.put(storeId, storeName);
}
}
shoppingControl.setShoppingControlStoreId(storeId);
shoppingControl.setShoppingControlStoreName(storeName);
}
private String getBusEntityName(Long busEntityId) {
String returnValue = "";
try {
BusEntityDAO busEntityDao = new BusEntityDAOImpl(em);
List<Long> busEntityIds = new ArrayList<Long>();
busEntityIds.add(busEntityId);
List<BusEntityData> busEntities = busEntityDao.find(busEntityIds);
if (Utility.isSet(busEntities)) {
returnValue = busEntities.get(0).getShortDesc();
}
}
catch (Exception e) {
logger.error("Unable to retrieve bus entity name for id = " + busEntityId);
}
return returnValue;
}
private Long getStoreId(Long busEntityId, String busEntityTypeCode) {
Long returnValue = null;
try {
BusEntityAssocDAO busEntityAssocDao = new BusEntityAssocDAOImpl(em);
Long accountId = null;
if (RefCodeNames.BUS_ENTITY_TYPE_CD.SITE.equalsIgnoreCase(busEntityTypeCode)) {
List<Long> busEntities = new ArrayList<Long>();
busEntities.add(busEntityId);
accountId = busEntityAssocDao.findAssocs(busEntities, null, RefCodeNames.BUS_ENTITY_ASSOC_CD.SITE_OF_ACCOUNT).get(0).getBusEntity2Id();
}
else {
accountId = busEntityId;
}
List<Long> busEntities = new ArrayList<Long>();
busEntities.add(accountId);
returnValue = busEntityAssocDao.findAssocs(busEntities, null, RefCodeNames.BUS_ENTITY_ASSOC_CD.ACCOUNT_OF_STORE).get(0).getBusEntity2Id();
}
catch (Exception e) {
logger.error("Unable to retrieve store id for " + busEntityTypeCode + " with id = " + busEntityId);
}
return returnValue;
}
private boolean shoppingControlIsModified(ShoppingControlItemView shoppingControl) {
boolean actionChanged = !Utility.isEqual(shoppingControl.getShoppingControlOriginalAction(), shoppingControl.getShoppingControlAction());
boolean maxQuantityChanged = !Utility.isEqual(shoppingControl.getShoppingControlOriginalMaxOrderQty(), shoppingControl.getShoppingControlMaxOrderQty());
boolean restrictionDaysChanged = !Utility.isEqual(shoppingControl.getShoppingControlOriginalRestrictionDays(), shoppingControl.getShoppingControlRestrictionDays());
boolean returnValue = actionChanged || maxQuantityChanged || restrictionDaysChanged;
return returnValue;
}
private void createShoppingControl(ShoppingControlItemView shoppingControl) {
ShoppingControlData shoppingControlData = new ShoppingControlData();
//account id or site id should be set but not both. If a site id value is specified then use it,
//otherwise use the account id value. Also, since action values are only applicable to account
//based shopping controls, set the value to be null if this is a site based shopping control and use
//the specified value if it is an account based shopping control.
Long locationId = shoppingControl.getShoppingControlLocationId();
if (Utility.isSet(locationId)) {
shoppingControlData.setAccountId(DEFAULT_BUS_ENTITY_ID);
shoppingControlData.setSiteId(locationId);
shoppingControlData.setActionCd(null);
}
else {
shoppingControlData.setAccountId(shoppingControl.getShoppingControlAccountId());
shoppingControlData.setSiteId(DEFAULT_BUS_ENTITY_ID);
String actionCode = shoppingControl.getShoppingControlAction();
if (Utility.isSet(actionCode)) {
shoppingControlData.setActionCd(shoppingControl.getShoppingControlAction());
}
else {
shoppingControlData.setActionCd(null);
}
}
shoppingControlData.setActualMaxQty(DEFAULT_QUANTITY);
//addDate and addBy are handled automatically
//control status code
shoppingControlData.setControlStatusCd(RefCodeNames.SHOPPING_CONTROL_STATUS_CD.ACTIVE);
shoppingControlData.setExpDate(null);
shoppingControlData.setHistoryOrderQty(DEFAULT_QUANTITY);
//item id
shoppingControlData.setItemId(shoppingControl.getItemId());
//max order quantity
String maxOrderQuantity = shoppingControl.getShoppingControlMaxOrderQty();
if (Utility.isSet(maxOrderQuantity) && !Constants.CHARS.ASTERISK.equalsIgnoreCase(maxOrderQuantity)) {
shoppingControlData.setMaxOrderQty(new Long(maxOrderQuantity));
}
else {
shoppingControlData.setMaxOrderQty(DEFAULT_QUANTITY);
}
//modDate and modBy are handled automatically
//restriction days
String restrictionDays = shoppingControl.getShoppingControlRestrictionDays();
if (Utility.isSet(restrictionDays) && !Constants.CHARS.ASTERISK.equalsIgnoreCase(restrictionDays)) {
shoppingControlData.setRestrictionDays(new Long(restrictionDays));
}
else {
shoppingControlData.setRestrictionDays(DEFAULT_QUANTITY);
}
ShoppingControlData newShoppingControlData = super.create(shoppingControlData);
shoppingControl.setShoppingControlId(newShoppingControlData.getShoppingControlId());
}
private void updateShoppingControl(ShoppingControlItemView shoppingControl) {
StringBuilder query = new StringBuilder("Select shoppingControl from ShoppingControlData shoppingControl ");
query.append(" where shoppingControl.shoppingControlId = (:shoppingControlId)");
String queryString = query.toString();
Query q = em.createQuery(queryString);
q.setParameter("shoppingControlId", shoppingControl.getShoppingControlId());
List<ShoppingControlData> shoppingControls = (List<ShoppingControlData>) q.getResultList();
if (Utility.isSet(shoppingControls)) {
ShoppingControlData scd = shoppingControls.get(0);
String maxOrderQuantity = shoppingControl.getShoppingControlMaxOrderQty();
if (Utility.isSet(maxOrderQuantity) && !Constants.CHARS.ASTERISK.equalsIgnoreCase(maxOrderQuantity)) {
scd.setMaxOrderQty(new Long(maxOrderQuantity));
}
else {
scd.setMaxOrderQty(DEFAULT_QUANTITY);
}
String restrictionDays = shoppingControl.getShoppingControlRestrictionDays();
if (Utility.isSet(restrictionDays) && !Constants.CHARS.ASTERISK.equalsIgnoreCase(restrictionDays)) {
scd.setRestrictionDays(new Long(restrictionDays));
}
else {
scd.setRestrictionDays(DEFAULT_QUANTITY);
}
//if the shopping control is account based then use the specified action, and if not then set
//it to be null since action is not applicable to site based shopping controls.
if (scd.getAccountId() > DEFAULT_BUS_ENTITY_ID) {
scd.setActionCd(shoppingControl.getShoppingControlAction());
}
else {
scd.setActionCd(null);
}
ShoppingControlData modifiedShoppingControlData = super.update(scd);
}
}
}
|
package com.tencent.mm.plugin.gallery.ui;
import java.util.ArrayList;
class SelectAlbumPreviewFolderUI$2 implements Runnable {
final /* synthetic */ SelectAlbumPreviewFolderUI jEF;
final /* synthetic */ ArrayList jEG;
SelectAlbumPreviewFolderUI$2(SelectAlbumPreviewFolderUI selectAlbumPreviewFolderUI, ArrayList arrayList) {
this.jEF = selectAlbumPreviewFolderUI;
this.jEG = arrayList;
}
public final void run() {
SelectAlbumPreviewFolderUI.a(this.jEF).addAll(this.jEG);
SelectAlbumPreviewFolderUI.b(this.jEF).RR.notifyChanged();
}
}
|
package com.tencent.mm.plugin.honey_pay.ui;
import com.tencent.mm.ab.l;
import com.tencent.mm.plugin.honey_pay.a.i;
import com.tencent.mm.ui.widget.MMSwitchBtn;
import com.tencent.mm.wallet_core.c.h$a;
class HoneyPayCardManagerUI$12 implements h$a {
final /* synthetic */ HoneyPayCardManagerUI kkT;
final /* synthetic */ i kkW;
HoneyPayCardManagerUI$12(HoneyPayCardManagerUI honeyPayCardManagerUI, i iVar) {
this.kkT = honeyPayCardManagerUI;
this.kkW = iVar;
}
public final void g(int i, int i2, String str, l lVar) {
boolean z = true;
MMSwitchBtn a = HoneyPayCardManagerUI.a(this.kkT);
if (this.kkW.bWA == 1) {
z = false;
}
a.setCheck(z);
}
}
|
package sc.ustc.dao;
import sc.ustc.Proxy.BeanProxy;
import sc.ustc.model.BaseBean;
import sc.ustc.model.jdbc.JDBCClass;
import sc.ustc.model.jdbc.JDBCConfig;
import sc.ustc.model.jdbc.Property;
import sc.ustc.utils.SCUtil;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
/**
* Author Daniel
* Class: Conversation
* Date: 2018/1/1 15:44
* Description: 数据表操作,实现CRUD
*/
public class Conversation {
private static List<JDBCClass> jdbcClassList;
private static JDBCConfig jdbcConfig;
private static Connection conn = null;
private static Statement statement = null;
static void setJdbcClassList(List<JDBCClass> jdbcClassList) {
Conversation.jdbcClassList = jdbcClassList;
}
static void setJdbcConfig(JDBCConfig jdbcConfig) {
Conversation.jdbcConfig = jdbcConfig;
}
public static void openDBConnection() {
try {
Class.forName(jdbcConfig.getDriverClass());// 指定连接类型
conn = DriverManager.getConnection(jdbcConfig.getUrlPath(), jdbcConfig.getDbUserName(), jdbcConfig
.getDbUserPassword());// 获取连接
statement = conn.createStatement();// 获取执行sql语句的statement对象
} catch (Exception e) {
e.printStackTrace();
}
}
public static void closeDBConnection() {
try {
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* author: Daniel
* description: 通过某个键值来查询对象
*/
public static <T extends BaseBean> T getObject(T bean) {
T proxy = null;
JDBCClass jdbcClass = getCurrentORMap(bean);
try {
// 初始化懒加载列表,提供给代理判断
List<Property> lazyPropertyList = new ArrayList<>();
// 初始化非懒加载SQL语句
StringBuilder builder = new StringBuilder("");
for (Property property : jdbcClass.getPropertyList()) {
if (!property.isLazy()) {
builder.append(property.getColumn());
builder.append(",");
} else {
lazyPropertyList.add(property);
}
}
System.out.println("正常加载启动:"+builder.toString());
ResultSet resultSet = query(bean, jdbcClass.getTable(), builder.substring(0, builder.length() - 1));
// 获取cglib动态代理
System.out.println("代理启动");
BeanProxy beanProxy = new BeanProxy(lazyPropertyList, jdbcClass.getTable());
proxy = (T) beanProxy.getProxy(bean.getClass());
proxy = SCUtil.resultSetToBean(resultSet, proxy);
proxy.setColumn(bean.getColumn());
proxy.setValue(bean.getValue());
System.out.println("正常加载完成");
} catch (Exception e) {
e.printStackTrace();
}
return proxy;
}
/**
* author: Daniel
* description: 查表原子操作
*/
public static ResultSet query(BaseBean bean, String table, String fieldName) {
JDBCClass jdbcClass = getCurrentORMap(bean);
try {
// 提供任意单个参数查询,如果没定义列,默认使用xml定义的主键column
String column = bean.getColumn() == null ? jdbcClass.getId().getName() : bean.getColumn();
String select = "select " + fieldName;
String from = " from " + table;
String where = " where " + column + "='" + bean.getValue() + "'";
// 查表
return statement.executeQuery(select + from + where);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* author: Daniel
* description: 获取当前的映射对象
*/
private static <T extends BaseBean> JDBCClass getCurrentORMap(T t) {
// 获取并截取代理的真实类名
String simpleName = t.getClass().getSimpleName();
simpleName = simpleName.indexOf('$')>0?simpleName.substring(0,simpleName.indexOf('$')):simpleName;
for (JDBCClass jdbcClass : jdbcClassList) {
if (simpleName.equals(jdbcClass.getName())) {
return jdbcClass;
}
}
return new JDBCClass();
}
/**
* author: Daniel
* description: 通过某个键值来删除对象
*/
public static <T extends BaseBean> boolean deleteObject(T bean) {
JDBCClass jdbcClass = getCurrentORMap(bean);
try {
String column = bean.getColumn() == null ? jdbcClass.getId().getName() : bean.getColumn();
String delete = "delete from " + jdbcClass.getTable();
String where = " where " + column + "='" + bean.getValue() + "'";
return statement.executeUpdate(delete + where)>0;
}
catch(Exception e){
e.printStackTrace();
}
return false;
}
/**
* author: Daniel
* description: 添加对象
*/
public static <T extends BaseBean> boolean insertObject(T bean) {
JDBCClass jdbcClass = getCurrentORMap(bean);
try {
// todo 插入对象sql语句构造
String sql = "insert into user(...) values(...)";
return statement.executeUpdate(sql)>0;
}
catch(Exception e){
e.printStackTrace();
}
return false;
}
/**
* author: Daniel
* description: 更新对象
*/
public static <T extends BaseBean> boolean updateObject(T bean) {
JDBCClass jdbcClass = getCurrentORMap(bean);
try {
// todo 更新对象sql语句构造
String sql = "insert into user(...) values(...)";
return statement.executeUpdate(sql)>0;
}
catch(Exception e){
e.printStackTrace();
}
return false;
}
}
|
package Controllers;
import backend.model.Person;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.*;
/**
* This is singleton class is used to centralize our navigation and globalize our session authentication key.
**/
public class ViewSwitcher implements Initializable {
public static ActionEvent globalAction;
@FXML
private AnchorPane rootPane;
private StringBuilder stringToken = new StringBuilder();
private List<Person> people;
private static ViewSwitcher instance = null;
public ViewSwitcher() {
}
public static ViewSwitcher getInstance(){
if( instance == null){
instance = new ViewSwitcher();
}
return instance;
}
public void switchView(ViewType viewtype) throws IOException {
URL url;
AddPerson person = new AddPerson();
Stage window;
Scene scene;
switch (viewtype) {
case addPerson:
url = new File("src/main/resources/Add.fxml").toURI().toURL();
rootPane = FXMLLoader.load(url);
scene = new Scene(rootPane);// pane you are GOING TO show
window = (Stage) ((Node) ViewSwitcher.globalAction.getSource()).getScene().getWindow();
window.setScene(scene);
window.show();
break;
case ListViewController:
url = new File("src/main/resources/ListView.fxml").toURI().toURL();
rootPane = FXMLLoader.load(url);
scene = new Scene(rootPane);// pane you are GOING TO show
window = (Stage) ((Node) ViewSwitcher.globalAction.getSource()).getScene().getWindow();
window.setScene(scene);
window.show();
break;
case updatePerson:
url = new File("src/main/resources/UpdateProfile.fxml").toURI().toURL();
rootPane = FXMLLoader.load(url);
scene = new Scene(rootPane);// pane you are GOING TO show
window = (Stage) ((Node) ViewSwitcher.globalAction.getSource()).getScene().getWindow();
window.setScene(scene);
window.show();
break;
case auditTrail:
url = new File("src/main/resources/audittrail.fxml").toURI().toURL();
rootPane = FXMLLoader.load(url);
scene = new Scene(rootPane);// pane you are GOING TO show
window = (Stage) ((Node) ViewSwitcher.globalAction.getSource()).getScene().getWindow();
window.setScene(scene);
window.show();
break;
default:
break;
}
}
public String getSessionid(){return stringToken.toString();}
public void sessionID(String session){
ViewSwitcher.getInstance().stringToken.append(session);
}
public void setPerson(List<Person> new_person){this.people = new_person;}
public List<Person> getPeople(){return this.people;}
public List<Person> peopleFetch(int pageNumber, String lastname){
PersonGateway pg = new PersonGateway("http://localhost:8080/people?pageNum=" + pageNumber +"&lastName="+lastname ,this.getSessionid());
List<Person> people = pg.fetchPeople();
//System.out.println("The people are: " + people.toString());
return people;
}
public void deletePerson(Person person) throws IOException {
PersonGateway pg = new PersonGateway("http://localhost:8080/people",this.getSessionid());
pg.deletePerson(person);
}
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
}
}
|
package com.simpson.kisen.product.model.dao;
import java.util.List;
import com.simpson.kisen.admin.model.vo.SlideImg;
import com.simpson.kisen.product.model.vo.Basket;
import com.simpson.kisen.product.model.vo.ProductImgExt;
import com.simpson.kisen.product.model.vo.ProductOption;
public interface ProductDao {
List<ProductImgExt> selectNewGoodsProductList();
ProductImgExt selectOneProduct(int no);
List<ProductImgExt> selectRandomProductList();
List<ProductImgExt> selectBestSellProductList();
List<SlideImg> selectSlideList();
List<ProductImgExt> selectIdolProductList(int no);
List<ProductImgExt> selectIdolAlbumList(int no);
int insertBasket(Basket basket);
ProductOption selectOptionNo(int[] opNo);
int insertBasketNoOption(Basket basket);
ProductOption selectOptionNo(String opName);
}
|
package com.spring3.dao;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
/**
* com.spring3.dao
*
* @author jh
* @date 2018/8/22 15:22
* description:
*/
public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao {
@Override
public void addMoney(Integer id, Double money) {
getJdbcTemplate ().update ("update account set money =money+? where id=?",money,id);
}
@Override
public void decrMoney(Integer id, Double money) {
getJdbcTemplate ().update ("update account set money =money-? where id=?",money,id);
}
}
|
package com.cn.my.bean;
import java.util.Date;
public class Code {
private Integer id;
private Long codeId;
private String codeNameCn;
private String codeNameEn;
private String codeDesc;
private Boolean codeStatus;
private Date createTime;
private Long createBy;
private Date updateDate;
private Long updateBy;
/**
* @return code_id
*/
public Long getCodeId() {
return codeId;
}
/**
* @param codeId
*/
public void setCodeId(Long codeId) {
this.codeId = codeId;
}
/**
* @return code_name_cn
*/
public String getCodeNameCn() {
return codeNameCn;
}
/**
* @param codeNameCn
*/
public void setCodeNameCn(String codeNameCn) {
this.codeNameCn = codeNameCn == null ? null : codeNameCn.trim();
}
/**
* @return code_name_en
*/
public String getCodeNameEn() {
return codeNameEn;
}
/**
* @param codeNameEn
*/
public void setCodeNameEn(String codeNameEn) {
this.codeNameEn = codeNameEn == null ? null : codeNameEn.trim();
}
/**
* @return code_desc
*/
public String getCodeDesc() {
return codeDesc;
}
/**
* @param codeDesc
*/
public void setCodeDesc(String codeDesc) {
this.codeDesc = codeDesc == null ? null : codeDesc.trim();
}
/**
* @return code_status
*/
public Boolean getCodeStatus() {
return codeStatus;
}
/**
* @param codeStatus
*/
public void setCodeStatus(Boolean codeStatus) {
this.codeStatus = codeStatus;
}
/**
* @return create_time
*/
public Date getCreateTime() {
return createTime;
}
/**
* @param createTime
*/
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
/**
* @return create_by
*/
public Long getCreateBy() {
return createBy;
}
/**
* @param createBy
*/
public void setCreateBy(Long createBy) {
this.createBy = createBy;
}
/**
* @return update_date
*/
public Date getUpdateDate() {
return updateDate;
}
/**
* @param updateDate
*/
public void setUpdateDate(Date updateDate) {
this.updateDate = updateDate;
}
/**
* @return update_by
*/
public Long getUpdateBy() {
return updateBy;
}
/**
* @param updateBy
*/
public void setUpdateBy(Long updateBy) {
this.updateBy = updateBy;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
} |
package rjm.romek.awscourse.model;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import org.hibernate.annotations.OnDelete;
import org.hibernate.annotations.OnDeleteAction;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import rjm.romek.awscourse.util.DescriptionFragment;
import rjm.romek.awscourse.util.DescriptionParser;
import rjm.romek.awscourse.verifier.TaskVerifier;
@Entity
@Data
@NoArgsConstructor
public class Task {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "task_id")
private Long taskId;
@ManyToOne
@OnDelete(action = OnDeleteAction.CASCADE)
private Chapter chapter;
@Column(length=512)
private String description;
private String page;
private Class<? extends TaskVerifier> verifier;
@OneToMany(mappedBy = "task", cascade = CascadeType.ALL, orphanRemoval = true)
@EqualsAndHashCode.Exclude
private Set<UserTask> userTasks = new HashSet<UserTask>();
public Task(Chapter chapter) {
this.chapter = chapter;
}
public Task(Chapter chapter, String description, Class<? extends TaskVerifier> verifier) {
this.chapter = chapter;
this.description = description;
this.verifier = verifier;
}
public Map<String, String> getParametersFromDescription() {
return DescriptionParser.extractParameters(description);
}
public List<DescriptionFragment> getDescriptionFragments() {
return DescriptionParser.parseDescription(description);
}
}
|
package Logic;
import java.math.BigInteger;
import java.util.Random;
import Backend.Const;
import Backend.Util;
public class PrivateKey extends Key {
public PublicKey publicKey;
public PrivateKey(BigInteger key, BigInteger modul) {
value = key;
this.modul = modul;
}
public static PrivateKey generateRandomKey() {
Random random = new Random();
// generate needed numbers
BigInteger factor1 = BigInteger.probablePrime(Const.KEY_BIT_LENGTH, random);
BigInteger factor2 = BigInteger.probablePrime(Const.KEY_BIT_LENGTH, random);
BigInteger modulN = factor1.multiply(factor2);
BigInteger phiN = factor1.subtract(BigInteger.ONE).multiply(factor2.subtract(BigInteger.ONE));
BigInteger e = new BigInteger(Const.KEY_BIT_LENGTH, random);
BigInteger d = BigInteger.ONE;
boolean arithEx;
do {
try {
arithEx = false;
e = new BigInteger(Const.KEY_BIT_LENGTH, random);
d = e.modInverse(phiN);
} catch (ArithmeticException ae) {
arithEx = true;
}
} while (e.subtract(phiN).signum() == 1 || e.equals(factor1.subtract(BigInteger.ONE)) || e.equals(factor2.subtract(BigInteger.ONE)) || arithEx);
// instantiate keys
PrivateKey re = new PrivateKey(e,modulN);
re.setPublicKey(new PublicKey(d, modulN));
return re;
}
public static PrivateKey generateSpecificKey(String decryptionKey) {
Random random = new Random();
// generate needed numbers
BigInteger factor1 = BigInteger.probablePrime(Const.KEY_BIT_LENGTH, random);
BigInteger factor2 = BigInteger.probablePrime(Const.KEY_BIT_LENGTH, random);
BigInteger modulN = factor1.multiply(factor2);
BigInteger phiN = factor1.subtract(BigInteger.ONE).multiply(factor2.subtract(BigInteger.ONE));
BigInteger e = Util.stringToBigInt(decryptionKey);
BigInteger d = e.modInverse(phiN);
PrivateKey priv = new PrivateKey(e, modulN);
priv.setPublicKey(new PublicKey(d, modulN));
return priv;
}
public String decrypt(String message) {
BigInteger mes = Util.stringToBigInt(message);
BigInteger mesDec = mes.modPow(getValue(), getModul());
return Util.bigIntToString(mesDec);
}
public String sign(String message) {
return decrypt(message);
}
public void setPublicKey(PublicKey pubKey) {
this.publicKey = pubKey;
}
} |
package com.redink.app.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.redink.app.entities.Authors;
import com.redink.app.exception.ResourceNotFoundException;
import com.redink.app.repository.AuthorRepository;
import com.redink.app.repository.PostRepository;
@RestController
@RequestMapping("/author")
public class AuthorController {
@Autowired
private AuthorRepository authorRepo;
@Autowired
private PostRepository repo;
@RequestMapping("/getall")
public List<Authors> getAll() {
return authorRepo.findAll();
}
@PostMapping("/save/{postId}")
public Authors saveAuthor(@PathVariable(value = "postId") int postId, @RequestBody Authors author) {
return repo.findById(postId).map(post -> {
author.setPost(post);
return authorRepo.save(author);
}).orElseThrow(() -> new ResourceNotFoundException("postId " + postId + " not found"));
}
}
|
package com.bit.tatab.login.dao;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.bit.tatab.login.vo.LoginVO;
public interface LoginDAO {
// 로그인 info db에 존재하는지 확인(검색)
public List<LoginVO> memberInfoFind(LoginVO loginVO);
// 로그인 info db에 추가
public void memberInfoInsert(LoginVO loginVO);
}
|
/**
* "Visual Paradigm: DO NOT MODIFY THIS FILE!"
*
* This is an automatic generated file. It will be regenerated every time
* you generate persistence class.
*
* Modifying its content may cause the program not work, or your work may lost.
*/
/**
* Licensee:
* License Type: Evaluation
*/
package crud;
import org.orm.*;
import org.hibernate.Query;
import org.hibernate.LockMode;
import java.util.List;
public class Utilisateur {
public Utilisateur() {
}
public static Utilisateur loadUtilisateurByORMID(int idUser) throws PersistentException {
try {
PersistentSession session = crud.GesMagPersistentManager.instance().getSession();
return loadUtilisateurByORMID(session, idUser);
}
catch (Exception e) {
e.printStackTrace();
throw new PersistentException(e);
}
}
public static Utilisateur getUtilisateurByORMID(int idUser) throws PersistentException {
try {
PersistentSession session = crud.GesMagPersistentManager.instance().getSession();
return getUtilisateurByORMID(session, idUser);
}
catch (Exception e) {
e.printStackTrace();
throw new PersistentException(e);
}
}
public static Utilisateur loadUtilisateurByORMID(int idUser, org.hibernate.LockMode lockMode) throws PersistentException {
try {
PersistentSession session = crud.GesMagPersistentManager.instance().getSession();
return loadUtilisateurByORMID(session, idUser, lockMode);
}
catch (Exception e) {
e.printStackTrace();
throw new PersistentException(e);
}
}
public static Utilisateur getUtilisateurByORMID(int idUser, org.hibernate.LockMode lockMode) throws PersistentException {
try {
PersistentSession session = crud.GesMagPersistentManager.instance().getSession();
return getUtilisateurByORMID(session, idUser, lockMode);
}
catch (Exception e) {
e.printStackTrace();
throw new PersistentException(e);
}
}
public static Utilisateur loadUtilisateurByORMID(PersistentSession session, int idUser) throws PersistentException {
try {
return (Utilisateur) session.load(crud.Utilisateur.class, new Integer(idUser));
}
catch (Exception e) {
e.printStackTrace();
throw new PersistentException(e);
}
}
public static Utilisateur getUtilisateurByORMID(PersistentSession session, int idUser) throws PersistentException {
try {
return (Utilisateur) session.get(crud.Utilisateur.class, new Integer(idUser));
}
catch (Exception e) {
e.printStackTrace();
throw new PersistentException(e);
}
}
public static Utilisateur loadUtilisateurByORMID(PersistentSession session, int idUser, org.hibernate.LockMode lockMode) throws PersistentException {
try {
return (Utilisateur) session.load(crud.Utilisateur.class, new Integer(idUser), lockMode);
}
catch (Exception e) {
e.printStackTrace();
throw new PersistentException(e);
}
}
public static Utilisateur getUtilisateurByORMID(PersistentSession session, int idUser, org.hibernate.LockMode lockMode) throws PersistentException {
try {
return (Utilisateur) session.get(crud.Utilisateur.class, new Integer(idUser), lockMode);
}
catch (Exception e) {
e.printStackTrace();
throw new PersistentException(e);
}
}
public static List queryUtilisateur(String condition, String orderBy) throws PersistentException {
try {
PersistentSession session = crud.GesMagPersistentManager.instance().getSession();
return queryUtilisateur(session, condition, orderBy);
}
catch (Exception e) {
e.printStackTrace();
throw new PersistentException(e);
}
}
public static List queryUtilisateur(String condition, String orderBy, org.hibernate.LockMode lockMode) throws PersistentException {
try {
PersistentSession session = crud.GesMagPersistentManager.instance().getSession();
return queryUtilisateur(session, condition, orderBy, lockMode);
}
catch (Exception e) {
e.printStackTrace();
throw new PersistentException(e);
}
}
public static Utilisateur[] listUtilisateurByQuery(String condition, String orderBy) throws PersistentException {
try {
PersistentSession session = crud.GesMagPersistentManager.instance().getSession();
return listUtilisateurByQuery(session, condition, orderBy);
}
catch (Exception e) {
e.printStackTrace();
throw new PersistentException(e);
}
}
public static Utilisateur[] listUtilisateurByQuery(String condition, String orderBy, org.hibernate.LockMode lockMode) throws PersistentException {
try {
PersistentSession session = crud.GesMagPersistentManager.instance().getSession();
return listUtilisateurByQuery(session, condition, orderBy, lockMode);
}
catch (Exception e) {
e.printStackTrace();
throw new PersistentException(e);
}
}
public static List queryUtilisateur(PersistentSession session, String condition, String orderBy) throws PersistentException {
StringBuffer sb = new StringBuffer("From crud.Utilisateur as Utilisateur");
if (condition != null)
sb.append(" Where ").append(condition);
if (orderBy != null)
sb.append(" Order By ").append(orderBy);
try {
Query query = session.createQuery(sb.toString());
return query.list();
}
catch (Exception e) {
e.printStackTrace();
throw new PersistentException(e);
}
}
public static List queryUtilisateur(PersistentSession session, String condition, String orderBy, org.hibernate.LockMode lockMode) throws PersistentException {
StringBuffer sb = new StringBuffer("From crud.Utilisateur as Utilisateur");
if (condition != null)
sb.append(" Where ").append(condition);
if (orderBy != null)
sb.append(" Order By ").append(orderBy);
try {
Query query = session.createQuery(sb.toString());
query.setLockMode("Utilisateur", lockMode);
return query.list();
}
catch (Exception e) {
e.printStackTrace();
throw new PersistentException(e);
}
}
public static Utilisateur[] listUtilisateurByQuery(PersistentSession session, String condition, String orderBy) throws PersistentException {
try {
List list = queryUtilisateur(session, condition, orderBy);
return (Utilisateur[]) list.toArray(new Utilisateur[list.size()]);
}
catch (Exception e) {
e.printStackTrace();
throw new PersistentException(e);
}
}
public static Utilisateur[] listUtilisateurByQuery(PersistentSession session, String condition, String orderBy, org.hibernate.LockMode lockMode) throws PersistentException {
try {
List list = queryUtilisateur(session, condition, orderBy, lockMode);
return (Utilisateur[]) list.toArray(new Utilisateur[list.size()]);
}
catch (Exception e) {
e.printStackTrace();
throw new PersistentException(e);
}
}
public static Utilisateur loadUtilisateurByQuery(String condition, String orderBy) throws PersistentException {
try {
PersistentSession session = crud.GesMagPersistentManager.instance().getSession();
return loadUtilisateurByQuery(session, condition, orderBy);
}
catch (Exception e) {
e.printStackTrace();
throw new PersistentException(e);
}
}
public static Utilisateur loadUtilisateurByQuery(String condition, String orderBy, org.hibernate.LockMode lockMode) throws PersistentException {
try {
PersistentSession session = crud.GesMagPersistentManager.instance().getSession();
return loadUtilisateurByQuery(session, condition, orderBy, lockMode);
}
catch (Exception e) {
e.printStackTrace();
throw new PersistentException(e);
}
}
public static Utilisateur loadUtilisateurByQuery(PersistentSession session, String condition, String orderBy) throws PersistentException {
Utilisateur[] utilisateurs = listUtilisateurByQuery(session, condition, orderBy);
if (utilisateurs != null && utilisateurs.length > 0)
return utilisateurs[0];
else
return null;
}
public static Utilisateur loadUtilisateurByQuery(PersistentSession session, String condition, String orderBy, org.hibernate.LockMode lockMode) throws PersistentException {
Utilisateur[] utilisateurs = listUtilisateurByQuery(session, condition, orderBy, lockMode);
if (utilisateurs != null && utilisateurs.length > 0)
return utilisateurs[0];
else
return null;
}
public static java.util.Iterator iterateUtilisateurByQuery(String condition, String orderBy) throws PersistentException {
try {
PersistentSession session = crud.GesMagPersistentManager.instance().getSession();
return iterateUtilisateurByQuery(session, condition, orderBy);
}
catch (Exception e) {
e.printStackTrace();
throw new PersistentException(e);
}
}
public static java.util.Iterator iterateUtilisateurByQuery(String condition, String orderBy, org.hibernate.LockMode lockMode) throws PersistentException {
try {
PersistentSession session = crud.GesMagPersistentManager.instance().getSession();
return iterateUtilisateurByQuery(session, condition, orderBy, lockMode);
}
catch (Exception e) {
e.printStackTrace();
throw new PersistentException(e);
}
}
public static java.util.Iterator iterateUtilisateurByQuery(PersistentSession session, String condition, String orderBy) throws PersistentException {
StringBuffer sb = new StringBuffer("From crud.Utilisateur as Utilisateur");
if (condition != null)
sb.append(" Where ").append(condition);
if (orderBy != null)
sb.append(" Order By ").append(orderBy);
try {
Query query = session.createQuery(sb.toString());
return query.iterate();
}
catch (Exception e) {
e.printStackTrace();
throw new PersistentException(e);
}
}
public static java.util.Iterator iterateUtilisateurByQuery(PersistentSession session, String condition, String orderBy, org.hibernate.LockMode lockMode) throws PersistentException {
StringBuffer sb = new StringBuffer("From crud.Utilisateur as Utilisateur");
if (condition != null)
sb.append(" Where ").append(condition);
if (orderBy != null)
sb.append(" Order By ").append(orderBy);
try {
Query query = session.createQuery(sb.toString());
query.setLockMode("Utilisateur", lockMode);
return query.iterate();
}
catch (Exception e) {
e.printStackTrace();
throw new PersistentException(e);
}
}
public static Utilisateur createUtilisateur() {
return new crud.Utilisateur();
}
public boolean save() throws PersistentException {
try {
crud.GesMagPersistentManager.instance().saveObject(this);
return true;
}
catch (Exception e) {
e.printStackTrace();
throw new PersistentException(e);
}
}
public boolean delete() throws PersistentException {
try {
crud.GesMagPersistentManager.instance().deleteObject(this);
return true;
}
catch (Exception e) {
e.printStackTrace();
throw new PersistentException(e);
}
}
public boolean refresh() throws PersistentException {
try {
crud.GesMagPersistentManager.instance().getSession().refresh(this);
return true;
}
catch (Exception e) {
e.printStackTrace();
throw new PersistentException(e);
}
}
public boolean evict() throws PersistentException {
try {
crud.GesMagPersistentManager.instance().getSession().evict(this);
return true;
}
catch (Exception e) {
e.printStackTrace();
throw new PersistentException(e);
}
}
public boolean deleteAndDissociate()throws PersistentException {
try {
if(getTypeusersidTypeUsers() != null) {
getTypeusersidTypeUsers().utilisateur.remove(this);
}
if(getAddressidAddress() != null) {
getAddressidAddress().utilisateur.remove(this);
}
crud.Vente[] lVentes = vente.toArray();
for(int i = 0; i < lVentes.length; i++) {
lVentes[i].setUtilisateuridUser(null);
}
crud.Vente[] lVente1s = vente1.toArray();
for(int i = 0; i < lVente1s.length; i++) {
lVente1s[i].setUsersoldeur(null);
}
return delete();
}
catch(Exception e) {
e.printStackTrace();
throw new PersistentException(e);
}
}
public boolean deleteAndDissociate(org.orm.PersistentSession session)throws PersistentException {
try {
if(getTypeusersidTypeUsers() != null) {
getTypeusersidTypeUsers().utilisateur.remove(this);
}
if(getAddressidAddress() != null) {
getAddressidAddress().utilisateur.remove(this);
}
crud.Vente[] lVentes = vente.toArray();
for(int i = 0; i < lVentes.length; i++) {
lVentes[i].setUtilisateuridUser(null);
}
crud.Vente[] lVente1s = vente1.toArray();
for(int i = 0; i < lVente1s.length; i++) {
lVente1s[i].setUsersoldeur(null);
}
try {
session.delete(this);
return true;
} catch (Exception e) {
return false;
}
}
catch(Exception e) {
e.printStackTrace();
throw new PersistentException(e);
}
}
private java.util.Set this_getSet (int key) {
if (key == crud.ORMConstants.KEY_UTILISATEUR_VENTE) {
return ORM_vente;
}
else if (key == crud.ORMConstants.KEY_UTILISATEUR_VENTE1) {
return ORM_vente1;
}
return null;
}
private void this_setOwner(Object owner, int key) {
if (key == crud.ORMConstants.KEY_UTILISATEUR_TYPEUSERSIDTYPEUSERS) {
this.typeusersidTypeUsers = (crud.Typeusers) owner;
}
else if (key == crud.ORMConstants.KEY_UTILISATEUR_ADDRESSIDADDRESS) {
this.addressidAddress = (crud.Address) owner;
}
}
org.orm.util.ORMAdapter _ormAdapter = new org.orm.util.AbstractORMAdapter() {
public java.util.Set getSet(int key) {
return this_getSet(key);
}
public void setOwner(Object owner, int key) {
this_setOwner(owner, key);
}
};
private int idUser;
private String nom;
private String prenom;
private String login;
private String motdepass;
private String description;
private crud.Typeusers typeusersidTypeUsers;
private crud.Address addressidAddress;
private java.util.Set ORM_vente = new java.util.HashSet();
private java.util.Set ORM_vente1 = new java.util.HashSet();
private void setIdUser(int value) {
this.idUser = value;
}
public int getIdUser() {
return idUser;
}
public int getORMID() {
return getIdUser();
}
public void setNom(String value) {
this.nom = value;
}
public String getNom() {
return nom;
}
public void setPrenom(String value) {
this.prenom = value;
}
public String getPrenom() {
return prenom;
}
public void setLogin(String value) {
this.login = value;
}
public String getLogin() {
return login;
}
public void setMotdepass(String value) {
this.motdepass = value;
}
public String getMotdepass() {
return motdepass;
}
public void setDescription(String value) {
this.description = value;
}
public String getDescription() {
return description;
}
public void setTypeusersidTypeUsers(crud.Typeusers value) {
if (typeusersidTypeUsers != null) {
typeusersidTypeUsers.utilisateur.remove(this);
}
if (value != null) {
value.utilisateur.add(this);
}
}
public crud.Typeusers getTypeusersidTypeUsers() {
return typeusersidTypeUsers;
}
/**
* This method is for internal use only.
*/
private void setORM_TypeusersidTypeUsers(crud.Typeusers value) {
this.typeusersidTypeUsers = value;
}
private crud.Typeusers getORM_TypeusersidTypeUsers() {
return typeusersidTypeUsers;
}
public void setAddressidAddress(crud.Address value) {
if (addressidAddress != null) {
addressidAddress.utilisateur.remove(this);
}
if (value != null) {
value.utilisateur.add(this);
}
}
public crud.Address getAddressidAddress() {
return addressidAddress;
}
/**
* This method is for internal use only.
*/
private void setORM_AddressidAddress(crud.Address value) {
this.addressidAddress = value;
}
private crud.Address getORM_AddressidAddress() {
return addressidAddress;
}
private void setORM_Vente(java.util.Set value) {
this.ORM_vente = value;
}
private java.util.Set getORM_Vente() {
return ORM_vente;
}
public final crud.VenteSetCollection vente = new crud.VenteSetCollection(this, _ormAdapter, crud.ORMConstants.KEY_UTILISATEUR_VENTE, crud.ORMConstants.KEY_VENTE_UTILISATEURIDUSER, crud.ORMConstants.KEY_MUL_ONE_TO_MANY);
private void setORM_Vente1(java.util.Set value) {
this.ORM_vente1 = value;
}
private java.util.Set getORM_Vente1() {
return ORM_vente1;
}
public final crud.VenteSetCollection vente1 = new crud.VenteSetCollection(this, _ormAdapter, crud.ORMConstants.KEY_UTILISATEUR_VENTE1, crud.ORMConstants.KEY_VENTE_USERSOLDEUR, crud.ORMConstants.KEY_MUL_ONE_TO_MANY);
public String toString() {
return String.valueOf(getIdUser());
}
}
|
import java.util.*;
import java.util.stream.*;
import java.io.*;
import java.math.*;
import java.awt.geom.*;
public class B {
public static final BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in));
public static final PrintWriter outWriter = new PrintWriter(System.out);
public static class Horse implements Comparable<Horse> {
public int cnt;
public char rep;
public int cnt() { return cnt; }
public char rep() { return rep; }
Horse(int cnt_, char rep_) { cnt=cnt_; rep=rep_; }
public Horse clone() { return new Horse(cnt,rep); }
public static Comparator<Horse> cmp = Comparator.comparing(Horse::cnt).thenComparing(Horse::rep);
public int compareTo(Horse o) { return cmp.compare(this, o); }
public boolean equals(Object oo) {
@SuppressWarnings("unchecked")
Horse o = (Horse)oo;
return cnt==o.cnt&&rep==o.rep;
}
public int hashCode() { return Objects.hash(cnt,rep); }
public String toString() { return ""+cnt+","+rep; }
}
public static boolean az(int... in) {
for (int i : in) {
if (i != 0) {
return false;
}
}
return true;
}
public static void add(StringBuilder out, Horse tmp) {
out.append(tmp.rep);
tmp.cnt--;
}
public static void add2(StringBuilder out, Horse a, Horse b, Horse c) {
Horse[] h = new Horse[]{a,b,c};
Arrays.sort(h);
a = h[0]; b = h[1]; c = h[2];
while (c.cnt > b.cnt && a.cnt > 0) {
add(out, c);
add(out, b);
if (c.cnt > 0 && a.cnt > 0) {
add(out, c);
add(out, a);
}
}
if (c.cnt > b.cnt) { throw new Asdf(); }
while (c.cnt > 0) {
add(out, c);
add(out, b);
if (a.cnt > 0) {
add(out, a);
}
}
}
public static class Asdf extends RuntimeException {
}
public static boolean okay(int pure, int mix) { return mix == 0 || mix+1 <= pure; }
public static String glue(char a, char b, int n) {
String out = a+"";
for (int i = 0; i < n; i++) {
out += b;
out += a;
}
return out;
}
public static String rep(String s, char a, char b, int n) {
return s.replace(a+"",glue(a,b,n));
}
public static Object solve() {
int n = nextInt(), r = nextInt(), o = nextInt(), y = nextInt(), g = nextInt(), b = nextInt(), v = nextInt();
StringBuilder out = new StringBuilder();
if (az(v,y,o,b) && g == r) { return glue('R','G',g).substring(1); }
if (az(g,r,o,b) && v == y) { return glue('Y','V',v).substring(1); }
if (az(v,y,o,b) && o == b) { return glue('B','O',o).substring(1); }
if (!okay(b, o) || !okay(y, v) || !okay(r,g)) {
return "IMPOSSIBLE";
}
b -= o; r -= g; y -= v;
try {
add2(out, new Horse(r, 'R'), new Horse(y, 'Y'), new Horse(b, 'B'));
} catch (Asdf a) {
return "IMPOSSIBLE";
}
String s = out.toString();
s = rep(s, 'R', 'G', g);
s = rep(s, 'Y', 'V', v);
s = rep(s, 'B', 'O', o);
return s;
}
public static void main(String[] args) {
int T = nextInt();
for (int i = 0; i < T; i++) {
outWriter.print("Case #"+(i+1)+": ");
Object tmp = solve();
if (tmp != null) { outWriter.println(tmp); }
}
outWriter.flush();
}
public static StringTokenizer tokenizer = null;
public static String nextLine() {
try { return buffer.readLine(); } catch (IOException e) { throw new UncheckedIOException(e); }
}
public static String next() {
while (tokenizer == null || !tokenizer.hasMoreElements()) { tokenizer = new StringTokenizer(nextLine()); }
return tokenizer.nextToken();
}
public static int nextInt() { return Integer.parseInt(next()); }
public static long nextLong() { return Long.parseLong(next()); }
public static double nextDouble() { return Double.parseDouble(next()); }
}
|
package ru.sprikut.sd.refactoring.servlet;
import org.junit.Assert;
import org.junit.Test;
import ru.sprikut.sd.refactoring.product.Product;
import java.io.IOException;
import java.util.List;
import static org.mockito.Mockito.when;
public class AddProductTest extends BaseTest {
@Test(expected = Exception.class)
public void emptyAddTest() throws IOException {
new AddProductServlet(database).doGet(request, response);
}
@Test
public void simpleAddTest() throws IOException {
when(request.getParameter("name")).thenReturn("my_name");
when(request.getParameter("price")).thenReturn("23");
new AddProductServlet(database).doGet(request, response);
compareStrings("OK", writer.toString());
List<Product> all = database.selectAll();
Assert.assertEquals(all.size(), 1);
Assert.assertEquals(all.get(0).getName(), "my_name");
Assert.assertEquals(all.get(0).getPrice(), 23);
}
} |
package com.bookstore.service;
import com.bookstore.domain.*;
public interface OrderService {
Order createOrder(ShoppingCart shoppingCart, ShippingAddress shippingAddress,
BillingAddress billingAddress, Payment payment, String shippingMethod, User user);
Order findById(Long id);
}
|
package com.lec.ex1_awt;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Ex05Frame extends Frame implements ActionListener { // ActionListener - listen to action events
//1. implements ActionListener
private Panel panel;
private TextField txtField;
private Button btnOk;
private Button btnExit;
private List list;
public Ex05Frame(String title) {
//layout셋팅, 컴포넌트 생성 후 add, setVisible, setSize
//setLayout(new BorderLayout()); //기본값이므로 생략 가능
panel = new Panel(new FlowLayout()); // Panel은 flowlayout이 기본값
txtField = new TextField(20);
btnOk = new Button("OK");
btnExit = new Button("EXIT");
list = new List(); //list하기 -Creates a new scrolling list
panel.add(new Label("write"));
panel.add(txtField);
panel.add(btnOk);
panel.add(btnExit);
add(panel, BorderLayout.NORTH);
add(list, BorderLayout.CENTER); //listup
setVisible(true);
setSize(new Dimension(400,200));
//2.이벤트 리스트 추가
//3.로직 추가
btnOk.addActionListener(this); //this.actionPerformed(btnOk이벤트)
btnExit.addActionListener(this);
}
public Ex05Frame() { //이거 안쓰면 매개변수 없는 게 호출됨. 근데 위에 보면 다 매개변수 있는 함수들.
//따라서 this("")하면 빈스트링 Ex05Frame 실행
this("");
} //*********************여기다 넣어도 되는지*******************************************************
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==btnOk) {
//txtField의 텍스트를 list로 추가하고 textField는 ""
list.add(txtField.getText());
txtField.setText("");
}else if(e.getSource()==btnExit) {
//종료
setVisible(false);
dispose();
System.exit(0);
}
}
public static void main(String[] args) {
new Ex05Frame(); //위에 main함수가 없다 . main함수있어야 실행가능 / 따라서 main함수 추가
}
}
|
package com.ev.srv.demopai.service.impl;
import com.ev.srv.demopai.service.ForecastmovementService;
import com.ev.srv.demopai.model.AggregationEvoMovement;
import com.ev.srv.demopai.model.AggregationForecastModel;
import com.evo.api.springboot.exception.ApiException;
import com.ev.srv.demopai.model.ForecastModel;
import com.ev.srv.demopai.model.GraphPoint;
import java.time.OffsetDateTime;
import com.ev.srv.demopai.model.RequestWrapperForecastModel;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
import java.util.List;
/**
* A delegate to be called by the {@link ForecastmovementController}}.
* Implement this interface with a {@link org.springframework.stereotype.Service} annotated class.
*/
@Service
@Slf4j
public class ForecastmovementServiceImpl implements ForecastmovementService{
@Override
public List<ForecastModel> createManualForecastMovement(RequestWrapperForecastModel body) throws ApiException{
// TODO Auto-generated method stub
return null;
}
@Override
public String deleteUpdatedForecast(String codigoEntidad,String usuarioBE,String acuerdoBE,String subacuerdo,String uuid) throws ApiException{
// TODO Auto-generated method stub
return null;
}
@Override
public AggregationEvoMovement getForecastRelatedMovements(String categoryid,String codigoEntidad,String usuarioBE,String acuerdoBE,String subacuerdo,Integer page,Integer maxItems) throws ApiException{
// TODO Auto-generated method stub
return null;
}
@Override
public AggregationForecastModel getForecastedIncomesExpensesAggregated(String acuerdoBE,String subacuerdo,String tipo,String categories) throws ApiException{
// TODO Auto-generated method stub
return null;
}
@Override
public List<GraphPoint> getForecastedIncomesExpensesMultiple(String codigoEntidad,String usuarioBE,String acuerdoBE,String subacuerdo,OffsetDateTime from,OffsetDateTime to,String type,String categoryId) throws ApiException{
// TODO Auto-generated method stub
return null;
}
@Override
public ForecastModel updateForecastMovement(RequestWrapperForecastModel body) throws ApiException{
// TODO Auto-generated method stub
return null;
}
}
|
package com.example.algorithm.id;
public class SnowFlakeGenerator{
private final long twepoch = 1288834974657L;
//workerIdBits + datacenterIdBits 为工作机器的ID
private final long workerIdBits = 5L;
private final long datacenterIdBits = 5L;
//负数是采用二进制的补码表示 补码 = 反码 + 1 = (原码 - 1)再取反码
//-1的二进制码为1111111111-1111111111-1111111111-1111111111-1111111111-1111111111-1111
//因此 -1的二进制码 进行左移workerIdBits位 结果为11...1100000 然后再与-1的二进制码已经异或
//异或的算法是相同为0 不同为1,这步操作等于是将上面的结果高位的1 全部变回0 这样就得到了11111也就是workerIdBits(<64时)个bit(<64时)能表示的最大二进制数
private final long maxWorkerId = -1L ^ (-1L << workerIdBits);
//与maxWorkerId相同,计算datacenterIdBits个位能表示的最大数
private final long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
private final long sequenceBits = 12L;
//workerId在64位二进制数中的偏移位数
private final long workerIdShift = sequenceBits;
//datacenterId在64位二进制数中的偏移位数
private final long datacenterIdShift = sequenceBits + workerIdBits;
//时间戳的偏移位数
private final long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
//序列只有sequenceBits个位数 因此这个表示的是序列的最大值
private final long sequenceMask = -1L ^ (-1L << sequenceBits);
private long workerId;
private long datacenterId;
private long sequence = 0L;
private long lastTimestamp = -1L;
public SnowFlakeGenerator(long workerId, long datacenterId) {
/*
* Twitter的SnowFlake算法生成id的结果是一个64bit大小的整数,它的结构为
* 0-0000000000-0000000000-0000000000-0000000000-0000000000-0000000000-000
* | | || || |
* | -—————————时间戳——————————| | -毫秒内序列-
* 符号位 ---机器ID--
* 1位,不用。二进制中最高位为1的都是负数,但是我们生成的id一般都使用整数,所以这个最高位固定是0
* 1~42位,41位用来记录时间戳(毫秒)。
* 41位可以表示2^41−1个数字,
* 如果只用来表示正整数(计算机中正数包含0),可以表示的数值范围是:0 至 241−1,减1是因为可表示的数值范围是从0开始算的,而不是1。
* 也就是说41位可以表示241−1个毫秒的值,转化成单位年则是(241−1)/(1000∗60∗60∗24∗365)=69年
* 43~53位,10位用来记录工作机器id。
* 可以部署在210=1024个节点,包括5位datacenterId和5位workerId
* 5位(bit)可以表示的最大正整数是25−1=31,即可以用0、1、2、3、....31这32个数字,来表示不同的datecenterId或workerId
* 54~64位,12位序列号,用来记录同毫秒内产生的不同id。
* 12位(bit)可以表示的最大正整数是212−1=4096,即可以用0、1、2、3、....4095这4096个数字,来表示同一机器同一时间截(毫秒)内产生的4096个ID序号
*/
if (workerId > maxWorkerId || workerId < 0) {
throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
}
if (datacenterId > maxDatacenterId || datacenterId < 0) {
throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId));
}
this.workerId = workerId;
this.datacenterId = datacenterId;
}
public synchronized long nextId() {
long timestamp = timeGen();
if (timestamp < lastTimestamp) {
throw new RuntimeException(String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
}
if (lastTimestamp == timestamp) {
//将序列值与最大序列值按照位取 & ,如果当前序列值超过了sequenceMask结果为0
//因为sequenceMask的二进制值为0000000000-0000000000-0000000000-0000000000-0000000000-0011111111-1111
//如果上一个序列为0000000000-0000000000-0000000000-0000000000-0000000000-0011111111-1111那么 + 1 =
//0000000000-0000000000-0000000000-0000000000-0000000000-0100000000-0000 & 0000000000-0000000000-0000000000-0000000000-0000000000-0011111111-1111
//结果为 0 ,这样就能控制序列永远在0~sequenceMask之间循环递增
sequence = (sequence + 1) & sequenceMask;
//当超出sequenceMask值后运算的sequence结果为0 说明当前毫秒内的序列用完了,等下个毫秒再取
if (sequence == 0) {
timestamp = tilNextMillis(lastTimestamp);
}
} else {
//如果是新的毫秒值 重新从0开始
sequence = 0L;
}
lastTimestamp = timestamp;
//这一步是作用是将毫秒值移位到对应的位置,datacenterId、workerId移位到相应位置然后与序列三者进行或运算 合并为一个二进制数字。实现算法目的
//|或运算为有1得1,这其中的值都限制在相应的长度,因此不属于自己的区间的对应位上的值都为0能达到合并成一个包含三者有效位的二进制数字
return ((timestamp - twepoch) << timestampLeftShift) | (datacenterId << datacenterIdShift) | (workerId << workerIdShift) | sequence;
}
protected long tilNextMillis(long lastTimestamp) {
long timestamp = timeGen();
while (timestamp <= lastTimestamp) {
timestamp = timeGen();
}
return timestamp;
}
protected long timeGen() {
return System.currentTimeMillis();
}
public static void main(String[] args) {
SnowFlakeGenerator idWorker = new SnowFlakeGenerator(0, 0);
for (int i = 0; i < 100; i++) {
long id = idWorker.nextId();
System.out.println(id);
}
}
}
|
package com.layla.modules;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.SystemClock;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.*;
import android.widget.*;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseUser;
import com.layla.*;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
public class Notebook extends AppCompatActivity
{
static List<String> notes = new ArrayList<>();
static ArrayAdapter arrayAdapter;
private ListView listView;
private ImageButton imageButton;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
retainNotes();
SystemClock.sleep(400);
setContentView(R.layout.activity_notebook);
imageButton = findViewById(R.id.imageButton);
listView = findViewById(R.id.listView);
setToolbar();
noteAddEdit();
deleteNote();
setAdapter();
}
public void retainNotes()
{
ParseQuery<ParseObject> query = new ParseQuery<>("Note");
query.whereEqualTo("sender", ParseUser.getCurrentUser().getUsername());
query.whereEqualTo("recipient", ParseUser.getCurrentUser().getString("doctor"));
query.orderByAscending("createdAt");
notes.clear();
query.findInBackground((objects, e) ->
{
if(e == null)
{
if(objects.size() > 0)
{
for(ParseObject message : objects)
{
String messageContent = message.getString("message");
notes.add(messageContent);
}
}
}
else
{
Log.e("LAYLA", e.getMessage());
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
public void setToolbar()
{
Toolbar myToolbar = findViewById(R.id.my_toolbar);
myToolbar.setTitle(getString(R.string.notebook_title));
setSupportActionBar(myToolbar);
myToolbar.setNavigationIcon(ContextCompat.getDrawable(this, R.drawable.ic_arrow_back_white_24dp));
myToolbar.setNavigationOnClickListener(v -> finish());
}
public void setAdapter()
{
arrayAdapter = new ArrayAdapter(getBaseContext(), android.R.layout.simple_list_item_1, notes);
listView.setAdapter(arrayAdapter);
}
public void noteAddEdit()
{
listView.setOnItemClickListener((adapterView, view, i, l) ->
{
Intent intent = new Intent(Notebook.this, NewNote.class);
intent.putExtra("noteId", i);
startActivity(intent);
});
imageButton.setOnClickListener(view ->
{
Intent intent = new Intent(Notebook.this, NewNote.class);
startActivity(intent);
});
}
public void deleteNote()
{
listView.setOnItemLongClickListener((adapterView, view, item, l) ->
{
//item can make mistake
new AlertDialog.Builder(Notebook.this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Are you sure?")
.setMessage("Do you want do delete this note?")
.setPositiveButton("Yes", (dialogInterface, i) ->
{
notes.remove(item);
arrayAdapter.notifyDataSetChanged();
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("com.projects.lukas.myapp", Context.MODE_PRIVATE);
HashSet<String> set = new HashSet<>(Notebook.notes);
sharedPreferences.edit().putStringSet("notes", set).apply();
})
.setNegativeButton("No", null)
.show();
return true;
});
}
}
|
package com.example.kuldeep.dailynote.Adapters;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.example.kuldeep.dailynote.Activities.NoteDescriptionActivity;
import com.example.kuldeep.dailynote.Constants.DailyNoteMacros;
import com.example.kuldeep.dailynote.Interface.Interface;
import com.example.kuldeep.dailynote.Models.DailyNoteDataModel;
import com.example.kuldeep.dailynote.R;
import java.util.ArrayList;
import butterknife.Bind;
import butterknife.ButterKnife;
/**
* Created by Kuldeep on 1/8/2016.
*/
public class DailyNotesRecyclerViewAdapter extends RecyclerView
.Adapter<DailyNotesRecyclerViewAdapter
.DataObjectHolder> {
private ArrayList<DailyNoteDataModel> mDailyNoteModelArrayList;
Activity mContext;
Interface.getDailyNotePosition mGetDailyNotePosition;
public static class DataObjectHolder extends RecyclerView.ViewHolder {
@Bind(R.id.SubjectTextView)
TextView mSubjectTextView;
@Bind(R.id.DateTimeTextView)
TextView mDateTimeTextView;
@Bind(R.id.DescriptionTextView)
TextView mDescriptionTextView;
@Bind(R.id.ParentLayout)
RelativeLayout mParentLayout;
public DataObjectHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
public DailyNotesRecyclerViewAdapter(Activity mContext, ArrayList<DailyNoteDataModel> pDailyNoteModelArrayList, Interface.getDailyNotePosition pDailyNotePosition) {
this.mDailyNoteModelArrayList = pDailyNoteModelArrayList;
this.mContext = mContext;
mGetDailyNotePosition=pDailyNotePosition;
}
@Override
public DataObjectHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_daily_note, parent, false);
DataObjectHolder dataObjectHolder = new DataObjectHolder(view);
return dataObjectHolder;
}
@Override
public void onBindViewHolder(final DataObjectHolder holder, final int position) {
holder.mSubjectTextView.setText(Html.fromHtml(mDailyNoteModelArrayList.get(position).getSubject()));
holder.mDateTimeTextView.setText(mDailyNoteModelArrayList.get(position).getDateTime());
holder.mDescriptionTextView.setText(mDailyNoteModelArrayList.get(position).getDescription());
holder.mParentLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mGetDailyNotePosition.getDailyNotePosition(position);
}
});
}
@Override
public int getItemCount() {
return mDailyNoteModelArrayList.size();
}
}
|
package Marketing.OrderEnity;
import Presentation.Protocol.IOManager;
/**
/**
* 订单状态:已交付
* @author 梁乔
* @date 2021/10/15 10:36
*/
public class DeliveredOrderState extends OrderState{
@Override
public boolean isProduced() {
return true;
}
@Override
public boolean isTransporting() {
return true;
}
@Override
public boolean isDelivered() {
return true;
}
@Override
public void handleProduction(Order order) {
IOManager.getInstance().errorMassage(
"订单号为"+order.getOrderId()+"的订单已经交付,无法再次生产!",
"訂單號為"+order.getOrderId()+"的訂單已經交付,無法再次生產!",
"The order with order ID"+order.getOrderId()+"has been delivered,can not be produced again!"
);
}
@Override
public void handleTransportation(Order order) {
IOManager.getInstance().errorMassage(
"订单号为"+order.getOrderId()+"的订单已经交付,无法再次运输!",
"訂單號為"+order.getOrderId()+"的訂單已經交付,無法再次運輸!",
"The order with order ID"+order.getOrderId()+"has been delivered,can not be transported again!"
);
}
@Override
public void handleDelivery(Order order) {
IOManager.getInstance().errorMassage(
"订单号为"+order.getOrderId()+"的订单已经交付,无法再次交付!",
"訂單號為"+order.getOrderId()+"的訂單已經交付,無法再次交付!",
"The order with order ID"+order.getOrderId()+"has been delivered,can not be delivered again!"
);
}
/**
* 获取订单状态的中文名称
* @return : java.lang.String
* @author 梁乔
* @date 21:10 2021-10-15
*/
@Override
public String getCNStateName(){
return "已交付";
}
/**
* 获取订单状态的繁体名称
* @return : java.lang.String
* @author 梁乔
* @date 21:11 2021-10-15
*/
@Override
public String getTWStateName(){
return "已交付";
}
/**
* 获取订单状态的英文名称
* @return : java.lang.String
* @author 梁乔
* @date 21:37 2021-10-15
*/
@Override
public String getENStateName(){
return "Delivered";
}
} |
package cn.gavinliu.notificationbox.ui.detail;
import java.util.List;
import cn.gavinliu.notificationbox.model.NotificationInfo;
import cn.gavinliu.notificationbox.ui.BasePresenter;
import cn.gavinliu.notificationbox.ui.BaseView;
/**
* Created by Gavin on 16-10-17.
*/
public interface DetailContract {
interface Presenter extends BasePresenter {
void startLoad(String packageName);
}
interface View extends BaseView<Presenter> {
void showProgress(boolean isShown);
void showEmpty();
void showNotifications(List<NotificationInfo> notifications);
}
}
|
package com.swa.qa.pages;
public class LoginPage {
public LoginPage() {
}
public void main (String [] args0) {
System.out.println("Minor change");
}
}
|
package com.app.sapient.grade.controller;
import org.junit.Assert;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import com.app.sapient.grade.dto.TeacherDto;
import com.app.sapient.grade.exception.TeacherNotFoundException;
import com.app.sapient.grade.service.TeacherService;
@ExtendWith(MockitoExtension.class)
class TeacherControllerTest {
@InjectMocks
private TeacherController teacherController;
@Mock
private TeacherService teacherService;
@Test
void testConfigureTeacherForSuccessCase() {
TeacherDto teacherDto = new TeacherDto();
teacherDto.setId(1L);
Mockito.when(teacherService.configureTeacher(Mockito.any(TeacherDto.class))).thenReturn(teacherDto);
ResponseEntity<TeacherDto> result = teacherController.configureTeacher(teacherDto);
Assert.assertEquals(HttpStatus.OK, result.getStatusCode());
Assert.assertEquals(Long.valueOf(1L), result.getBody().getId());
}
@Test
void testConfigureTeacherForException() {
TeacherDto teacherDto = new TeacherDto();
teacherDto.setId(1L);
Mockito.when(teacherService.configureTeacher(Mockito.any(TeacherDto.class))).thenThrow(new NullPointerException());
ResponseEntity<TeacherDto> result = teacherController.configureTeacher(teacherDto);
Assert.assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, result.getStatusCode());
}
@Test
void testGetTeacherByIdForBadRequest() {
Mockito.when(teacherService.getTeacherById(Mockito.eq(1L))).thenThrow(new TeacherNotFoundException());
ResponseEntity<TeacherDto> result = teacherController.getTeacherById(1L);
Assert.assertEquals(HttpStatus.BAD_REQUEST, result.getStatusCode());
}
@Test
void testGetTeacherByIdForException() {
Mockito.when(teacherService.getTeacherById(Mockito.eq(1L))).thenThrow(new NullPointerException());
ResponseEntity<TeacherDto> result = teacherController.getTeacherById(1L);
Assert.assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, result.getStatusCode());
}
@Test
void testGetTeacherByIdForSuccessCase() {
TeacherDto teacherDto = new TeacherDto();
teacherDto.setId(1L);
Mockito.when(teacherService.getTeacherById(Mockito.eq(1L))).thenReturn(teacherDto);
ResponseEntity<TeacherDto> result = teacherController.getTeacherById(1L);
Assert.assertEquals(HttpStatus.OK, result.getStatusCode());
Assert.assertEquals(Long.valueOf(1L), result.getBody().getId());
}
@Test
void testDeleteTeacherByIdForException() {
Mockito.doThrow(new NullPointerException()).when(teacherService).deleteTeacherById(1L);
ResponseEntity<Void> result = teacherController.deleteTeacherById(1L);
Assert.assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, result.getStatusCode());
}
@Test
void testDeleteTeacherByIdForSuccessCase() {
ResponseEntity<Void> result = teacherController.deleteTeacherById(1L);
Assert.assertEquals(HttpStatus.OK, result.getStatusCode());
Mockito.verify(teacherService, Mockito.times(1)).deleteTeacherById(1L);
}
}
|
package inheritance.overriding;
public class Overriding {
public static void main(String[] args) {
Person she = new Person("이소라",111);
she.printInfo();
//동적바인딩
Person i = new Faculty("강민경",2222,"인하공전",1);
i.printInfo(); // 동적바인딩
Person a = (Person) i;
a.printInfo(); // 동적바인딩 하위객체인 Faculty에 printinfo 를 가져온다 person형 i 변수에 faculty 객체를 대입했기때문.
// Person 으로바꿔도 동적바인딩으로인해 faculty에서 마지막 구현된 printinfo 메소드를 불러온다.
//동적바인딩
Person he = new Staff("하지영",989898,"동미대",8282,"이쁜이");
he.printInfo(); // 동적바인딩 Staff 객체대입해서 Person 형 he 변수가 printinfo 스태프메소드 구현
Faculty ft = (Faculty) he;
ft.printInfo(); // 마찬가지..이미 Staff 객체로 대입했기때문에 마지막 구현된 하위객체 Staff 의 메소드를불러옴.
Staff st = (Staff) he;
st.printInfo();
st.FacultyInfo(); // staff 로 형변환을 했으나, FacultyInfo의 printfinfo 정보자체가 Super로 지정되어 Faculty 의 정보를 불러오게되있음.
//24행 질문.!
}
}
|
package com.nhahv.examplereadfunstories.fragments;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.nhahv.examplereadfunstories.R;
import com.nhahv.examplereadfunstories.activities.MainActivity;
import com.nhahv.examplereadfunstories.models.ItemStore;
/**
* A simple {@link Fragment} subclass.
*/
public class StoreFragment extends Fragment {
// private List<ItemTop> mListStyleStore = new ArrayList<>();
// private ListView mListView;
// private StoreAdapter mAdapter;
public StoreFragment() {
}
public static StoreFragment getInstances(ItemStore path) {
StoreFragment storeFragment = new StoreFragment();
Bundle bundle = new Bundle();
bundle.putSerializable(MainActivity.PATH_STORE, path);
storeFragment.setArguments(bundle);
return storeFragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_store, container, false);
// mListView = (ListView) view.findViewById(R.id.list_view);
// mAdapter = new StoreAdapter(getActivity(), R.layout.item_store, mListStyleStore);
// mListView.setAdapter(mAdapter);
ItemStore string = (ItemStore) getArguments().getSerializable(MainActivity.PATH_STORE);
TextView mTxtStore = (TextView) view.findViewById(R.id.txt_store);
TextView mTxtNameStore = (TextView) view.findViewById(R.id.txt_name_store);
if (string != null) {
mTxtNameStore.setText(string.getTitle());
mTxtStore.setText(string.getContents());
}
return view;
}
}
|
package kr.ko.nexmain.server.MissingU.c2dm;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;
import javax.net.ssl.HttpsURLConnection;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import kr.ko.nexmain.server.MissingU.chat.service.ChatMainServiceImpl;
import kr.ko.nexmain.server.MissingU.common.Constants;
public class C2dmHelper {
private Logger log = LoggerFactory.getLogger(C2dmHelper.class);
public C2dmHelper() {
}
public boolean sendMsg(String regId,String authToken,String msg, List<List<String>> c2dmParamList) throws Exception{
//authToken = getAuthToken();
StringBuffer postDataBuilder = new StringBuffer();
String collapseKey = String.valueOf(Math.random() % 100 + 1);
postDataBuilder.append("registration_id="+regId); //등록ID
postDataBuilder.append("&collapse_key="+collapseKey);
postDataBuilder.append("&delay_while_idle=1");
postDataBuilder.append("&data.no=1");
postDataBuilder.append("&data.answerer=MissingU");
postDataBuilder.append("&data.msg="+URLEncoder.encode(msg, "UTF-8")); //태울 메시지
for(List<String> c2dmParamItem : c2dmParamList) {
postDataBuilder.append("&data.");
postDataBuilder.append(c2dmParamItem.get(0)).append("="); //key
postDataBuilder.append(c2dmParamItem.get(1)); //value
}
System.out.println(postDataBuilder.toString());
byte[] postData = postDataBuilder.toString().getBytes("UTF8");
URL url = new URL("https://android.apis.google.com/c2dm/send"); //Link 둘다 됨
//URL url = new URL("https://android.clients.google.com/c2dm/send");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setHostnameVerifier(new CustomizedHostnameVerifier());
//HttpsURLConnection.setDefaultHostnameVerifier(new CustomizedHostnameVerifier());
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
conn.setRequestProperty("Content-Length", Integer.toString(postData.length));
conn.setRequestProperty("Authorization", "GoogleLogin auth=" + authToken);
OutputStream out = conn.getOutputStream();
out.write(postData);
out.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpServletResponse.SC_UNAUTHORIZED ||
responseCode == HttpServletResponse.SC_FORBIDDEN) {
// The token is too old - return false to retry later, will fetch the token
// from DB. This happens if the password is changed or token expires. Either admin
// is updating the token, or Update-Client-Auth was received by another server,
// and next retry will get the good one from database.
System.out.println("Unauthorized - need token");
//serverConfig.invalidateCachedToken();
return false;
}
// Check for updated token header
/*
String updatedAuthToken = conn.getHeaderField(UPDATE_CLIENT_AUTH);
if (updatedAuthToken != null && !authToken.equals(updatedAuthToken)) {
System.out.println("Got updated auth token from datamessaging servers: " +
updatedAuthToken);
//serverConfig.updateToken(updatedAuthToken);
}
*/
String responseLine = new BufferedReader(new InputStreamReader(conn.getInputStream())).readLine();
// NOTE: You *MUST* use exponential backoff if you receive a 503 response code.
// Since App Engine's task queue mechanism automatically does this for tasks that
// return non-success error codes, this is not explicitly implemented here.
// If we weren't using App Engine, we'd need to manually implement this.
if (responseLine == null || responseLine.equals("")) {
System.out.println("Got " + responseCode + " response from Google AC2DM endpoint.");
//throw new IOException("Got empty response from Google AC2DM endpoint.");
}
String[] responseParts = responseLine.split("=", 2);
if (responseParts.length != 2) {
System.out.println("Invalid message from google: " + responseCode + " " + responseLine);
//throw new IOException("Invalid response from Google " + responseCode + " " + responseLine);
}
if (responseParts[0].equals("id")) {
System.out.println("Successfully sent data message to device: " + responseLine);
return true;
}
if (responseParts[0].equals("Error")) {
String err = responseParts[1];
System.out.println("Got error response from Google datamessaging endpoint: " + err);
// No retry.
// TODO(costin): show a nicer error to the user.
//throw new IOException(err);
} else {
// 500 or unparseable response - server error, needs to retry
System.out.println("Invalid response from google " + responseLine + " " + responseCode);
return false;
}
return true;
}
/**
* C2DM 메세지 발송을 위한 AuthToken 받아오는 메소드
* @return
* @throws Exception
*/
public String getAuthToken() throws Exception{
String authtoken = "";
StringBuffer postDataBuilder = new StringBuffer();
postDataBuilder.append("accountType=HOSTED_OR_GOOGLE"); //똑같이 써주셔야 합니다.
postDataBuilder.append("&Email=");
postDataBuilder.append(Constants.C2DM.C2DM_SENDER_ID); //개발자 구글 id
postDataBuilder.append("&Passwd=");
postDataBuilder.append(Constants.C2DM.C2DM_SENDER_PW); //개발자 구글 비빌번호
postDataBuilder.append("&service=ac2dm");
postDataBuilder.append("&source=test-1.0");
byte[] postData = postDataBuilder.toString().getBytes("UTF8");
URL url = new URL("https://www.google.com/accounts/ClientLogin");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", Integer.toString(postData.length));
OutputStream out = conn.getOutputStream();
out.write(postData);
out.close();
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String sidLine = br.readLine();
String lsidLine = br.readLine();
String authLine = br.readLine();
log.debug("sidLine----------->>>"+sidLine);
log.debug("lsidLine----------->>>"+lsidLine);
log.debug("authLine----------->>>"+authLine);
log.debug("AuthKey----------->>>"+authLine.substring(5, authLine.length()));
authtoken = authLine.substring(5, authLine.length());
return authtoken;
}
}
|
package kodlama.io.hrms.entities.concretes;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import kodlama.io.hrms.entities.abstracts.User;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Entity
@Table(name="employees")
@PrimaryKeyJoinColumn(name="user_id")
@AllArgsConstructor
@NoArgsConstructor
public class Employee extends User {
/*
* @Id
*
* @GeneratedValue(strategy = GenerationType.IDENTITY)
*
* @Column(name="user_id") private int userId;
*/
@Column(name="first_name")
private String firstName;
@Column(name="last_name")
private String LastName;
}
|
/*
* 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 Authentication;
import Controller.SkeletonView;
import Services.PasswordEncryptionService;
/**
*
* @author HACKER
*/
import java.awt.Color;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.Random;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
/**
*
* @author HACKER
*/
public class LogInScreen extends JFrame {
private static JLabel passwordLabel;
private static JLabel emailAddressLabel;
private static JTextField emailField;
private static JPasswordField passwordField;
private static JButton logInButton;
private static JLabel backgroundImage;
public LogInScreen() {
setSize(400, 340);
setLocation(300, 100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setBackground(Color.white);
setLayout(null);
setTitle("Spam-Detect Soft");
setResizable(false);
passwordField = new JPasswordField();
emailAddressLabel = new JLabel("Email Address:");
emailField = new JTextField();
passwordLabel = new JLabel("Password:");
logInButton = new JButton("Sign in");
backgroundImage = new JLabel(new ImageIcon(getClass().getResource("/appimages/Hospital.jpg")));
emailAddressLabel.setBounds(60, 30, 200, 25);
emailField.setBounds(60, 60, 200, 25);
passwordLabel.setBounds(60, 85, 150, 25);
passwordField.setBounds(60, 120, 200, 25);
logInButton.setBounds(100, 170, 150, 30);
backgroundImage.setBounds(0, 0, 400, 340);
passwordLabel.setForeground(Color.WHITE);
emailAddressLabel.setForeground(Color.WHITE);
logInButton.setBackground(Color.decode("#1e90ff"));
logInButton.setForeground(Color.WHITE);
add(emailAddressLabel);
add(emailField);
add(passwordLabel);
add(passwordField);
add(logInButton);
add(backgroundImage);
logInButton.addActionListener(e -> {
//auth
int auth_sucess = authenticateUser(
PasswordEncryptionService.getCipherText(String.valueOf(passwordField.getPassword())),
emailField.getText());
switch (auth_sucess) {
case 1:
DatabaseAccessObjects.SessionLogsDaos.registerASession(
LocalDate.now().toString(),
Integer.toString(Math.abs((new Random(LocalTime.now().getSecond()).nextInt()))),
emailField.getText());
setVisible(false);
break;
case 0:
break;
default:
break;
}
});
repaint();
setVisible(true);
}
/**
* Authenticate user...
*
* @param enteredPasswordHashed
* @param emailAddress
*/
public final int authenticateUser(String enteredPasswordHashed, String emailAddress) {
String password = "";
//obtain user password cipher
try (Connection connection = DriverManager.getConnection("jdbc:mysql://"
+ "localhost:3306/hospitalManagmentSystem", "root", "")) {
PreparedStatement preparedStatement = connection.prepareStatement(""
+ "SELECT password FROM users WHERE emailAddress IN(?);");
preparedStatement.setString(1, emailAddress);
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
password = resultSet.getString(1);
}
//compare password ciphers
if (enteredPasswordHashed.equals(password)) {
// authentication succefull...
JOptionPane.showMessageDialog(this, "Log in succefull!", "", JOptionPane.ERROR_MESSAGE);
this.setVisible(false);
new SkeletonView();
return 1;
} else if (!enteredPasswordHashed.equals(password)) {
//authetication failed
JOptionPane.showMessageDialog(this, "WRONG PASSWORD !", "Alpha Payroll System", JOptionPane.ERROR_MESSAGE);
/* frame.setVisible(false);
new PayrollSystem();*/
//temp
// authentication succefull...
return 0;
} else {
this.setVisible(false);
new SkeletonView();
JOptionPane.showMessageDialog(this, "An unexpected error occurred", "Alpha payroll System", JOptionPane.ERROR_MESSAGE);
return 0;
}
} catch (SQLException e) {
JOptionPane.showMessageDialog(this, ":Could't connect to database\n Click on the red- wamp server icon to activate the server" + e.getMessage(),
"Alpha Payroll System", JOptionPane.ERROR_MESSAGE);
return 0;
}
}
}
|
package com.yzpc.action;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.interceptor.ServletRequestAware;
import com.opensymphony.xwork2.ActionSupport;
public class MessageAction extends ActionSupport implements ServletRequestAware{
private HttpServletRequest request;
@Override
public void setServletRequest(HttpServletRequest request) {
// TODO Auto-generated method stub
this.request = request;
}
@Override
public String execute ()throws Exception
{
request.setAttribute("message", "hello,according to xxxAware realize ");
return super.execute();
}
}
|
package de.lise.terradoc.core.report.elements;
import java.io.StringWriter;
public class ParagraphElement extends TextElement {
public ParagraphElement(String text) {
super(text);
}
@Override
public void appendHtml(StringWriter writer) {
writer.append("<p>");
super.appendHtml(writer);
writer.append("</p>");
}
}
|
package com.ericlam.mc.minigames.core.event.section;
import com.ericlam.mc.minigames.core.game.GameState;
import com.ericlam.mc.minigames.core.game.InGameState;
import com.ericlam.mc.minigames.core.manager.PlayerManager;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* 遊戲等候投票事件。他是最初始的遊戲事件, 在遊戲被激活并可以進入的時候觸發。
*/
public final class GameVotingEvent extends GameSectionEvent {
public GameVotingEvent(@Nonnull PlayerManager playerManager, @Nullable InGameState inGameState, GameState gameState) {
super(playerManager, inGameState, gameState);
}
}
|
/**
*/
package com.rockwellcollins.atc.limp.impl;
import com.rockwellcollins.atc.limp.LimpPackage;
import com.rockwellcollins.atc.limp.StringType;
import org.eclipse.emf.ecore.EClass;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>String Type</b></em>'.
* <!-- end-user-doc -->
*
* @generated
*/
public class StringTypeImpl extends TypeImpl implements StringType
{
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected StringTypeImpl()
{
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass()
{
return LimpPackage.Literals.STRING_TYPE;
}
} //StringTypeImpl
|
package vue;
import java.awt.*;
import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
public class RendererGrasCentrer extends DefaultTableCellRenderer {
private static final long serialVersionUID = 1L;
@Override
public Component getTableCellRendererComponent( JTable table, Object value, boolean isSelected, boolean hasFocus,
int row, int column ) {
super.getTableCellRendererComponent( table, value, isSelected, hasFocus, row, column );
setFont( getFont().deriveFont( Font.BOLD ) );
setHorizontalAlignment( CENTER );
return this;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.