text
stringlengths
10
2.72M
package com.lenovohit.ssm.treat.model; import java.math.BigDecimal; import javax.persistence.Entity; import javax.persistence.Table; import com.lenovohit.core.model.BaseIdModel; /** * 缴费明细 * @author xiaweiyi * */ @Entity @Table(name="SSM_FEE") public class Fee extends BaseIdModel{ private static final long serialVersionUID = 1098286956401539056L; private String orderId; private String zh;/*组号*/ private String mc;/*名称*/ private BigDecimal dj = new BigDecimal(0); private BigDecimal sl = new BigDecimal(0);/*数量*/ private BigDecimal cs = new BigDecimal(0);/* 次数*/ private String kzjb;/*控制级别*/ private String yzsj;/*医嘱 时间*/ private String ysid;/*医生编号*/ private String kzjbmc;/*控制级别名称*/ private String ysxm;/*医生姓名*/ private String ksmc;/*科室名称*/ private String ksid;/*科室id*/ private String flmmc;/*分类码名称*/ private BigDecimal amt;/*金额*/ public BigDecimal getAmt() { return amt; } public void setAmt(BigDecimal amt) { this.amt = amt; } public String getOrderId() { return orderId; } public void setOrderId(String orderId) { this.orderId = orderId; } public String getZh() { return zh; } public void setZh(String zh) { this.zh = zh; } public String getMc() { return mc; } public void setMc(String mc) { this.mc = mc; } public BigDecimal getDj() { return dj; } public void setDj(BigDecimal dj) { this.dj = dj; } public BigDecimal getSl() { return sl; } public void setSl(BigDecimal sl) { this.sl = sl; } public BigDecimal getCs() { return cs; } public void setCs(BigDecimal cs) { this.cs = cs; } public String getKzjb() { return kzjb; } public void setKzjb(String kzjb) { this.kzjb = kzjb; } public String getYzsj() { return yzsj; } public void setYzsj(String yzsj) { this.yzsj = yzsj; } public String getYsid() { return ysid; } public void setYsid(String ysid) { this.ysid = ysid; } public String getKzjbmc() { return kzjbmc; } public void setKzjbmc(String kzjbmc) { this.kzjbmc = kzjbmc; } public String getYsxm() { return ysxm; } public void setYsxm(String ysxm) { this.ysxm = ysxm; } public String getKsmc() { return ksmc; } public void setKsmc(String ksmc) { this.ksmc = ksmc; } public String getKsid() { return ksid; } public void setKsid(String ksid) { this.ksid = ksid; } public String getFlmmc() { return flmmc; } public void setFlmmc(String flmmc) { this.flmmc = flmmc; } }
package be.odisee.se4.hetnest; public class SecurityConfig { }
/* * Tic Tac Toe Game Class * * Controls they whole game of tic tac toe for one player or two. If two players, * second player pretends to be computer. All computer ai is built into the class * and can be run completely independnt of the gui using the console output if programmed * to do so. */ import java.util.Random; // random number generator used for easy mode random square choosing public class TicTacToe extends game // subclass of game class { //instance variables private final int user = 5; private final int comp = 6; private int board[][]; private int compMove; private int difficulty = 1; private int winningLine = 0; private boolean aiDone = false; Random randomizer = new Random(); public TicTacToe() // constructor creates and initilizes board array to control board { board = new int[3][3]; initialize(); } public void aiWin() // used if computer is going for the win { for(int row = 0;row < 3;row++) // loops through all three rows checking for possible win { if((board[row][0] + board[row][1] + board[row][2]) == (comp * 2) && aiDone == false) // if current row could be a win based on for loop above { for(int i = 0;i < 3;i++) // checks for specific square that is blank { if(board[row][i] == 0) // if blank, set square to computer number and determine individual square value that changed. { board[row][i] = comp; compMove = (row * 3) + i + 1; } } aiDone = true; // now says computer has made a move } // end if loop } // end for loop for(int col = 0;col < 3;col++) // loops through all three columns checking for possible win { if((board[0][col] + board[1][col] + board[2][col]) == (comp * 2) && aiDone == false) // if current column could be a win based on for loop above { for(int i = 0;i < 3;i++) // checks for specific square that is blank { if(board[i][col] == 0) // if blank, set square to computer number and determine individual square value that changed. { board[i][col] = comp; compMove = (i * 3) + col + 1; } } aiDone = true; // now says computer has made a move } // end if loop } // end for loop if((board[0][0] + board[1][1] + board[2][2]) == (comp * 2) && aiDone == false) // if diagnol is win { for(int i = 0;i < 3;i++) // checks for specific square that is blank { if(board[i][i] == 0)// if blank, set square to computer number and determine individual square value that changed. { board[i][i] = comp; compMove = ((i + i) * 2) + 1; aiDone = true; // now says computer has made a move } // end if loop } //end for loop } // end if loop if((board[0][2] + board[1][1] + board[2][0]) == (comp * 2) && aiDone == false) // if diagnol is win { for(int i = 0;i < 3;i++) // checks for specific square that is blank { if(board[i][2 - i] == 0) // if blank, set square to computer number and determine individual square value that changed. { board[i][2 - i] = comp; compMove = (i * 3) + (2 - i) + 1; aiDone = true; // now says computer has made a move } // end if loop } // for loop } // end if loop } // end aiWin method public void aiFork() // used to block if user is trying a fork { if(board[0][0] == user && board[2][1] == user && board[2][0] == 0 && !aiDone) // checks for a specific fork attempt and blocks it, sets square to computer number and determine individual square value that changed. { board[2][0] = comp; compMove = 7; aiDone = true; // now says computer has made a move } if(board[0][0] == user && board[1][2] == user && board[0][2] == 0 && !aiDone) // checks for a specific fork attempt and blocks it, sets square to computer number and determine individual square value that changed. { board[0][2] = comp; compMove = 3; aiDone = true; // now says computer has made a move } if(board[2][0] == user && board[0][1] == user && board[0][0] == 0 && !aiDone) // checks for a specific fork attempt and blocks it, sets square to computer number and determine individual square value that changed. { board[0][0] = comp; compMove = 1; aiDone = true; // now says computer has made a move } if(board[2][0] == user && board[1][2] == user && board[2][2] == 0 && !aiDone) // checks for a specific fork attempt and blocks it, sets square to computer number and determine individual square value that changed. { board[2][2] = comp; compMove = 9; aiDone = true; // now says computer has made a move } if(board[0][2] == user && board[1][0] == user && board[0][0] == 0 && !aiDone) // checks for a specific fork attempt and blocks it, sets square to computer number and determine individual square value that changed. { board[0][0] = comp; compMove = 1; aiDone = true; // now says computer has made a move } if(board[0][2] == user && board[2][1] == user && board[2][2] == 0 && !aiDone) // checks for a specific fork attempt and blocks it, sets square to computer number and determine individual square value that changed. { board[2][2] = comp; compMove = 9; aiDone = true; // now says computer has made a move } if(board[2][2] == user && board[0][1] == user && board[0][2] == 0 && !aiDone) // checks for a specific fork attempt and blocks it, sets square to computer number and determine individual square value that changed. { board[0][2] = comp; compMove = 3; aiDone = true; // now says computer has made a move } if(board[2][2] == user && board[1][0] == user && board[2][0] == 0 && !aiDone) // checks for a specific fork attempt and blocks it, sets square to computer number and determine individual square value that changed. { board[2][0] = comp; compMove = 7; aiDone = true; // now says computer has made a move } } // end aiFork loop public void aiBlock() // checks if user is about to win and blocks it. { for(int row = 0;row < 3;row++) // loops through all rows checking for a block { if((board[row][0] + board[row][1] + board[row][2]) == (user * 2) && aiDone == false) // if current row needs to be blocked { for(int i = 0;i < 3;i++) // checks for individual square that needs to be blocked { if(board[row][i] == 0) // if blank, set square to computer number and determine individual square value that changed. { board[row][i] = comp; compMove = (row * 3) + i + 1; } } // end for loop aiDone = true; // now says computer has made a move } // end if loop } // end for loop for(int col = 0;col < 3;col++) // loops through all columns checking for a block { if((board[0][col] + board[1][col] + board[2][col]) == (user * 2) && aiDone == false) // if current column needs to be blocked { for(int i = 0;i < 3;i++) // checks for individual square that needs to be blocked { if(board[i][col] == 0) // if blank, set square to computer number and determine individual square value that changed. { board[i][col] = comp; compMove = (i * 3) + col + 1; } } // end for loop aiDone = true; // now says computer has made a move } // end if loop } // end for loop if((board[0][0] + board[1][1] + board[2][2]) == (user * 2) && aiDone == false) // if current diaganol needs to be blocked { if(board[0][0] == 0) // if blank, set square to computer number and determine individual square value that changed. { board[0][0] = comp; compMove = 1; } if(board[1][1] == 0) // if blank, set square to computer number and determine individual square value that changed. { board[1][1] = comp; compMove = 5; } if(board[2][2] == 0) // if blank, set square to computer number and determine individual square value that changed. { board[2][2] = comp; compMove = 9; } aiDone = true; // now says computer has made a move } // end if loop if((board[0][2] + board[1][1] + board[2][0]) == (user * 2) && aiDone == false) // if current row needs to be blocked { if(board[0][2] == 0) // if blank, set square to computer number and determine individual square value that changed. { board[0][2] = comp; compMove = 3; } if(board[1][1] == 0) // if blank, set square to computer number and determine individual square value that changed. { board[1][1] = comp; compMove = 5; } if(board[2][0] == 0) // if blank, set square to computer number and determine individual square value that changed. { board[2][0] = comp; compMove = 7; } aiDone = true; // now says computer has made a move } // end if loop } // end aiBlock loop public void aiCenter() // checks if center square is blank { if(board[1][1] == 0 && aiDone == false) // if center blank, computer moves there and determines individual square value that changed { board[1][1] = comp; compMove = 5; aiDone = true; // now says computer has made a move } } // end aiCenter public void aiOpposite() // checks if opposite square is blank { if(board[0][0] == user && aiDone == false) // checks for specific opposite open square { if(board[0][1] == 0 && aiDone == false) // if opposite is blank, computer moves there and determines individual square value that changed { board[0][1] = comp; compMove = 2; aiDone = true; // now says computer has made a move } if(board[1][0] == 0 && aiDone == false) // if opposite is blank, computer moves there and determines individual square value that changed { board[1][0] = comp; compMove = 4; aiDone = true; // now says computer has made a move } } // end if loop if(board[0][2] == user && aiDone == false) // checks for specific opposite open square { if(board[0][1] == 0 && aiDone == false) // if opposite is blank, computer moves there and determines individual square value that changed { board[0][1] = comp; compMove = 2; aiDone = true; // now says computer has made a move } if(board[1][2] == 0 && aiDone == false) // if opposite is blank, computer moves there and determines individual square value that changed { board[1][2] = comp; compMove = 6; aiDone = true; // now says computer has made a move } } // end if loop if(board[2][0] == user && aiDone == false) // checks for specific opposite open square { if(board[1][0] == 0 && aiDone == false) // if opposite is blank, computer moves there and determines individual square value that changed { board[1][0] = comp; compMove = 4; aiDone = true; // now says computer has made a move } if(board[2][1] == 0 && aiDone == false) // if opposite is blank, computer moves there and determines individual square value that changed { board[2][1] = comp; compMove = 8; aiDone = true; // now says computer has made a move } } // end if loop if(board[2][2] == user && aiDone == false) // checks for specific opposite open square { if(board[2][1] == 0 && aiDone == false) // if opposite is blank, computer moves there and determines individual square value that changed { board[2][1] = comp; compMove = 8; aiDone = true; // now says computer has made a move } if(board[1][2] == 0 && aiDone == false) // if opposite is blank, computer moves there and determines individual square value that changed { board[1][2] = comp; compMove = 6; aiDone = true; // now says computer has made a move } } // end if loop } // end aiOpposite method public void aiEmptyCorner() // checks for empty corner { if(board[0][0] == 0 && aiDone == false) // if corner is blank, computer moves there and determines individual square value that changed { board[0][0] = comp; compMove = 1; aiDone = true; // now says computer has made a move } if(board[0][2] == 0 && aiDone == false) // if corner is blank, computer moves there and determines individual square value that changed { board[0][2] = comp; compMove = 3; aiDone = true; // now says computer has made a move } if(board[2][0] == 0 && aiDone == false) // if corner is blank, computer moves there and determines individual square value that changed { board[2][0] = comp; compMove = 7; aiDone = true; // now says computer has made a move } if(board[2][2] == 0 && aiDone == false) // if corner is blank, computer moves there and determines individual square value that changed { board[2][2] = comp; compMove = 9; aiDone = true; // now says computer has made a move } } // end aiEmpty Corner method public void aiRandom() // randomly selects move { int random = 0; boolean valid = false; // used determine if valid move while(!valid) // while random number isn't an open square { random = randomizer.nextInt(9) + 1; // random number 1 to 9 switch(random) // depends on random number { case 1: if(board[0][0] == 0 && aiDone == false) // if number selected and square is blank, computer moves there and determines individual square value that changed { board[0][0] = comp; compMove = 1; valid = true; // switch to valid move taken aiDone = true; // now says computer has made a move } break; case 2: if(board[0][1] == 0 && aiDone == false) // if number selected and square is blank, computer moves there and determines individual square value that changed { board[0][1] = comp; compMove = 2; valid = true; // switch to valid move taken aiDone = true; // now says computer has made a move } break; case 3: if(board[0][2] == 0 && aiDone == false) // if number selected and square is blank, computer moves there and determines individual square value that changed { board[0][2] = comp; compMove = 3; valid = true; // switch to valid move taken aiDone = true; // now says computer has made a move } break; case 4: if(board[1][0] == 0 && aiDone == false) // if number selected and square is blank, computer moves there and determines individual square value that changed { board[1][0] = comp; compMove = 4; valid = true; // switch to valid move taken aiDone = true; // now says computer has made a move } break; case 5: if(board[1][1] == 0 && aiDone == false) // if number selected and square is blank, computer moves there and determines individual square value that changed { board[1][1] = comp; compMove = 5; valid = true; // switch to valid move taken aiDone = true; // now says computer has made a move } break; case 6: if(board[1][2] == 0 && aiDone == false) // if number selected and square is blank, computer moves there and determines individual square value that changed { board[1][2] = comp; compMove = 6; valid = true; // switch to valid move taken aiDone = true; // now says computer has made a move } break; case 7: if(board[2][0] == 0 && aiDone == false) // if number selected and square is blank, computer moves there and determines individual square value that changed { board[2][0] = comp; compMove = 7; valid = true; // switch to valid move taken aiDone = true; // now says computer has made a move } break; case 8: if(board[2][1] == 0 && aiDone == false) // if number selected and square is blank, computer moves there and determines individual square value that changed { board[2][1] = comp; compMove = 8; valid = true; // switch to valid move taken aiDone = true; // now says computer has made a move } break; case 9: if(board[2][2] == 0 && aiDone == false) // if number selected and square is blank, computer moves there and determines individual square value that changed { board[2][2] = comp; compMove = 9; valid = true; // switch to valid move taken aiDone = true; // now says computer has made a move } break; } // end switch } // end while not valid move loop } // end aiRandom method public void initialize() // initializes values of board to 0 { for (int row = 0;row < 3;row++) { for (int col = 0;col < 3;col++) { board[row][col] = 0; } } // end for loop aiDone = false; // resets aiDone value } // end initialize method public void display() // method used if game was played on console. Displays pretend board. Used for initial testing only { for (int row = 0;row < 3;row++) { System.out.println(board[row][0] + "|" + board[row][1] + "|" + board[row][2]); } System.out.print("\n"); } // end display method public void userInput(int space) // takes as a parameter the user selected square and changes appropriate game square in class { switch (space) // switch for value entered and sets to user value { case 1: board[0][0] = user; break; case 2: board[0][1] = user; break; case 3: board[0][2] = user; break; case 4: board[1][0] = user; break; case 5: board[1][1] = user; break; case 6: board[1][2] = user; break; case 7: board[2][0] = user; break; case 8: board[2][1] = user; break; case 9: board[2][2] = user; break; } // end switch } // end userInput method public void userInput2(int space2) // takes as a parameter the user # 2 selected square and changes appropriate game square in class { switch (space2) // switch for value entered and sets to user value { case 1: board[0][0] = comp; break; case 2: board[0][1] = comp; break; case 3: board[0][2] = comp; break; case 4: board[1][0] = comp; break; case 5: board[1][1] = comp; break; case 6: board[1][2] = comp; break; case 7: board[2][0] = comp; break; case 8: board[2][1] = comp; break; case 9: board[2][2] = comp; break; } // end switch } // end aiUserInput2 method public int aiInput() // method to tell computer to make move based on difficutly { aiDone = false; compMove = 0; // value returned based on move selected by computer /* difficulty easy order: aiWin, aiCenter, aiRandom difficutly hard order: aiWin, aiBlock,aiCenter,aiOpposite,aiEmptyCorner, aiRandom difficulty harder order: aiWin, aiBlock, aiFork,aiCenter,aiOpposite,aiEmptyCorner, aiRandom */ aiWin(); if(!aiDone && difficulty > 1) aiBlock(); if(!aiDone && difficulty == 3) aiFork(); if(!aiDone && difficulty > 0) aiCenter(); if(!aiDone && difficulty > 1) aiOpposite(); if(!aiDone && difficulty > 1) aiEmptyCorner(); if(!aiDone) aiRandom(); return compMove; } public void difficulty(int diff) // method to set game difficulty level { difficulty = diff; } public int checkForWinner() // method to check for winner and returns 1 if user won, 2 if computer won, or 3 if tie { for(int row = 0;row < 3;row++) // loops through rows to determine if comp won { if((board[row][0] + board[row][1] + board[row][2]) == (comp * 3)) // if comp won on current row { winningLine = row + 1; // determine winning line number for gui return 2; // return computer won or if two player, player 2 won } } // end for loop for(int col = 0;col < 3;col++) // loops through columns to determine if comp won { if((board[0][col] + board[1][col] + board[2][col]) == (comp * 3)) // if comp won on current column { winningLine = col + 4; // determine winning line number for gui return 2; // return computer won or if two player, player 2 won } } // end for loop if((board[0][0] + board[1][1] + board[2][2]) == (comp * 3)) // if comp won on diaganol { winningLine = 7; // determine winning line number for gui return 2; // return computer won or if two player, player 2 won } if((board[0][2] + board[1][1] + board[2][0]) == (comp * 3)) // if comp won on diaganol { winningLine = 8; // determine winning line number for gui return 2; // return computer won or if two player, player 2 won } for(int row = 0;row < 3;row++) // loops through rows to determine if user won { if((board[row][0] + board[row][1] + board[row][2]) == (user * 3)) // if user won on current row { winningLine = row + 1; // determine winning line number for gui return 1; // return player 1 won } } // end for loop for(int col = 0;col < 3;col++) // loops through columns to determine if user won { if((board[0][col] + board[1][col] + board[2][col]) == (user * 3)) // if user won on current column { winningLine = col + 4; // determine winning line number for gui return 1; // return player 1 won } } // end for looop if((board[0][0] + board[1][1] + board[2][2]) == (user * 3)) // if user won on diaganol { winningLine = 7; // determine winning line number for gui return 1; // return player 1 won } if((board[0][2] + board[1][1] + board[2][0]) == (user * 3)) // if user won on diaganol { winningLine = 8; // determine winning line number for gui return 1; // return player 1 won } // checks if all squares taken and returns 3 for tie if(board[0][0] != 0 && board[0][1] != 0 && board[0][2] != 0 && board[1][0] != 0 && board[1][1] != 0 && board[1][2] != 0 && board[2][0] != 0 && board[2][1] != 0 && board[2][2] != 0) { return 3; } return 0; // returns 0 if no win or tie found } // end checkForWinner method public int winningLine() // returns winning line number for gui { return winningLine; } public void setWinningLine(int winningLine) // set winning line number { this.winningLine = winningLine; } }
package br.mg.puc.sica.evento.evento.service; import br.mg.puc.sica.evento.evento.Enum.Categoria; import br.mg.puc.sica.evento.evento.model.Envolvidos; import br.mg.puc.sica.evento.evento.model.Evento; import br.mg.puc.sica.evento.evento.model.Zona; import br.mg.puc.sica.evento.evento.model.request.EnvolvidoRequest; import br.mg.puc.sica.evento.evento.model.request.EnvolvidoUpdateRequest; import br.mg.puc.sica.evento.evento.repositoy.EnvolvidoRepository; import br.mg.puc.sica.evento.evento.repositoy.EventoRepository; import br.mg.puc.sica.evento.evento.repositoy.ZonaRepository; import java.util.List; import java.util.Optional; import org.apache.commons.lang3.EnumUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; import org.springframework.web.server.ResponseStatusException; @Service public class EnvolvidoService { @Autowired EnvolvidoRepository envolvidoRepository; @Autowired ZonaService zonaService; public List<Envolvidos> getEnvolvidos() { return envolvidoRepository.findAll(); } public void adicionarEnvolvido(EnvolvidoRequest envolvidoRequest) { Zona zona = zonaService.recuperarZona(envolvidoRequest.getIdZona()); Categoria categoria = validarRetornarCategoria(envolvidoRequest.getCategoria()); Envolvidos envolvidos = Envolvidos.builder() .email(envolvidoRequest.getEmail()) .zona(zona) .categoria(categoria) .build(); envolvidoRepository.save(envolvidos); } public void deleteEnvolvido(Long idEnvolvido) { Envolvidos envolvido = recuperarEnvolvido(idEnvolvido); envolvidoRepository.delete(envolvido); } public void updateEnvolvido(Long idEnvolvido, EnvolvidoUpdateRequest envolvidoUpdateRequest) { Envolvidos envolvido = recuperarEnvolvido(idEnvolvido); Zona zona = zonaService.recuperarZona(envolvidoUpdateRequest.getIdZona()); Categoria categoria = validarRetornarCategoria(envolvidoUpdateRequest.getCategoria()); envolvido.setCategoria(categoria); envolvido.setEmail(envolvidoUpdateRequest.getEmail()); envolvido.setZona(zona); envolvidoRepository.save(envolvido); } private Envolvidos recuperarEnvolvido(Long idEnvolvido) { Optional<Envolvidos> envolvido = envolvidoRepository.findById(idEnvolvido); if (!envolvido.isPresent()) { throw new ResponseStatusException( HttpStatus.NOT_FOUND, "Envolvido não encontrado"); } return envolvido.get(); } private Categoria validarRetornarCategoria(String categoria) { if (!EnumUtils.isValidEnum(Categoria.class, categoria)) { throw new ResponseStatusException( HttpStatus.BAD_REQUEST, "Categoria inválida"); } return Categoria.valueOf(categoria); } }
package kr.ac.kopo.day09; public class StringMain05 { public static void main(String[] args) { long start = System.currentTimeMillis(); String str = ""; for(int i = 0; i < 100000; i++) { str += i; } long end = System.currentTimeMillis(); System.out.println("소요시간 : " + (end - start) / 1000.0 + "초"); // 요거 3.9초 걸림. 고작 10만번인데 왤케 오래걸려??.. // 왜냐면.. String은 불변. 새로운 공간 생성하고 주소값 가리키고 이 과정을 10만번하니까 겁나 오래 걸리고 공간 낭비도 극심해. // 이건 너무 비효율적이고 별로야. // 이래서 StringBuffer나 StringBuilder가 사용되어야하는 것이야!!! start = System.currentTimeMillis(); StringBuffer sb = new StringBuffer(); for(int i = 0; i < 100000; i++) { sb.append(i); //이건 대입 코드 필요없어. 자체가 알아서 변하니까. } end = System.currentTimeMillis(); System.out.println("소요시간 : " + (end - start) / 1000.0 + "초"); System.out.println(str); // 미친듯한 속도차이. // 이건 공간 10만개 생성x, 1개 생성 } }
/* * 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 Services; import Entities.Produit; import Utils.Connexion; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author ASUS */ public class GestionProduit { private Connection con = Connexion.getInstance().getCnx(); public void ajouterProduit(Produit P) { Statement st; try { st = con.createStatement(); String req = "insert into Produit values('" + P.getRef_produit() + "','" + P.getNom_produit() + "','" + P.getMarque() + "','" + P.getCategorie() + "'," + P.getQuantité_stock() + " , " + P.getQuantité_magasin() + " , " + P.getPrix_vente() + " , " + P.getPrix_achat() + ")"; st.executeUpdate(req); } catch (SQLException ex) { Logger.getLogger(GestionProduit.class.getName()).log(Level.SEVERE, null, ex); } } public void afficherProduit() { PreparedStatement pt; try { pt = con.prepareStatement("select * from Produit"); ResultSet rs = pt.executeQuery(); while (rs.next()) { System.out.println("Produit [reference : " + rs.getInt(1) + " , nom produit :" + rs.getString(2) + " , marque : " + rs.getString(3) + " , categorie : " + rs.getString(4) + " , quantité stock : " + rs.getInt(5) + " , quantité magasin" + rs.getInt(6) + ", prix vente :" + rs.getInt(7) + " , prix achat :" + rs.getInt(8) + "]"); } } catch (SQLException ex) { Logger.getLogger(GestionProduit.class.getName()).log(Level.SEVERE, null, ex); } } public void supprimerProduit(int ref) { PreparedStatement pt; try { pt = con.prepareStatement("delete from Produit where ref_produit = ?"); pt.setInt(1, ref); pt.executeUpdate(); } catch (SQLException ex) { Logger.getLogger(GestionProduit.class.getName()).log(Level.SEVERE, null, ex); } } public void modifierProduit(Produit p){ PreparedStatement pt; try { pt = con.prepareStatement("update produit set nom_produit = ? , marque = ? , categorie = ? , quantité_stock = ? , quantité_magasin = ? , prix_vente = ? , prix_achat = ? where ref_produit = ?"); pt.setString(1,p.getNom_produit()); pt.setString(2,p.getMarque()); pt.setString(3,p.getCategorie()); pt.setInt(4,p.getQuantité_stock()); pt.setInt(5,p.getQuantité_magasin()); pt.setFloat(6,p.getPrix_vente()); pt.setFloat(7,p.getPrix_achat()); pt.setInt(8,p.getRef_produit()); pt.executeUpdate(); } catch (SQLException ex) { Logger.getLogger(GestionProduit.class.getName()).log(Level.SEVERE, null, ex); } } }
package com.example.android.quantitanti; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Typeface; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.lifecycle.Observer; import androidx.lifecycle.ViewModelProviders; import androidx.preference.PreferenceManager; import androidx.recyclerview.widget.ItemTouchHelper; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.example.android.quantitanti.adapters.DailyCostAdapter; import com.example.android.quantitanti.database.CostDatabase; import com.example.android.quantitanti.database.CostEntry; import com.example.android.quantitanti.factories.DailyExpensesViewModelFactory; import com.example.android.quantitanti.helpers.Helper; import com.example.android.quantitanti.models.DailyExpensesViewModel; import com.example.android.quantitanti.sharedpreferences.SettingsActivity; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.jakewharton.threetenabp.AndroidThreeTen; import org.threeten.bp.LocalDate; import java.math.BigInteger; import java.util.List; import java.util.Map; import java.util.TreeMap; import static com.example.android.quantitanti.database.CostEntry.CATEGORY_1; import static com.example.android.quantitanti.database.CostEntry.CATEGORY_2; import static com.example.android.quantitanti.database.CostEntry.CATEGORY_3; import static com.example.android.quantitanti.database.CostEntry.CATEGORY_4; import static com.example.android.quantitanti.database.CostEntry.CATEGORY_5; import static com.example.android.quantitanti.database.CostEntry.CATEGORY_6; import static com.example.android.quantitanti.database.CostEntry.CATEGORY_7; import static com.example.android.quantitanti.database.CostEntry.CATEGORY_8; import static com.example.android.quantitanti.database.CostEntry.CATEGORY_9; import static java.lang.String.valueOf; public class DailyExpensesActivity extends AppCompatActivity implements DailyCostAdapter.DailyItemClickListener, SharedPreferences.OnSharedPreferenceChangeListener { // Constant for logging private static final String TAG = CostListActivity.class.getSimpleName(); // Member variables for the adapter and RecyclerView private RecyclerView mRecyclerView; private DailyCostAdapter mAdapter; private CostDatabase mDb; //constants for sp currency public static String currency1; public static String currency2; // Extra for the cost ID to be received after rotation public static final String INSTANCE_COST_ID = "instanceCostId"; // Constant for default cost id to be used when not in update mode private static final int DEFAULT_COST_ID = -1; private int mCostId = DEFAULT_COST_ID; // Constant for default cost id to be used when not in update mode private static final String DEFAULT_COST_DATE = "2020-01-01"; private String mCostDate = DEFAULT_COST_DATE; // Extra for the cost date to be received in the intent public static final String EXTRA_COST_DATE = "extraCostDate"; //calender TextView tv_weekDay; TextView tv_dateNo; TextView tv_toolbar_mont_year; //sum category costs TextView tv_category_costs; TextView tv_total_cost; int totalCost; String totalCostString; int category1Cost; int category2Cost; int category3Cost; int category4Cost; int category5Cost; int category6Cost; int category7Cost; int category8Cost; int category9Cost; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); AndroidThreeTen.init(this); setContentView(R.layout.activity_daily_expenses); mDb = CostDatabase.getInstance(getApplicationContext()); Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar_de); setSupportActionBar(myToolbar); setTitle("Selected"); getSupportActionBar().setDisplayHomeAsUpEnabled(true); // set calender on Toolbar LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View calender = inflater.inflate(R.layout.calender_view, null); myToolbar.addView(calender); // set TextView on Toolbar LayoutInflater inflater2 = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View monthYear = inflater2.inflate(R.layout.tv_toolbar_montyear, null); myToolbar.addView(monthYear); mRecyclerView = findViewById(R.id.recyclerViewDailyCost); mRecyclerView.setLayoutManager(new LinearLayoutManager(this)); mAdapter = new DailyCostAdapter(this, this); mRecyclerView.setAdapter(mAdapter); //receiving intent when onItemClickListener in CostListActivity Intent intent = getIntent(); if (intent != null && intent.hasExtra(EXTRA_COST_DATE)) { if (mCostDate == DEFAULT_COST_DATE) { mCostDate = intent.getStringExtra(EXTRA_COST_DATE); calenderDateSetting(); DailyExpensesViewModelFactory factory = new DailyExpensesViewModelFactory(mDb, mCostDate); final DailyExpensesViewModel viewModel = ViewModelProviders.of(this, factory).get(DailyExpensesViewModel.class); viewModel.getCosts().observe(this, new Observer<List<CostEntry>>() { @Override public void onChanged(List<CostEntry> costEntries) { mAdapter.setmDailyCosts(costEntries); } }); } } /** * Add a touch helper to the RecyclerView to recognize when a user swipes to delete an item. * An ItemTouchHelper enables touch behavior (like swipe and move) on each ViewHolder, * and uses callbacks to signal when a user is performing these actions. */ new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) { @Override public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) { return false; } // Called when a user swipes left or right on a ViewHolder @Override public void onSwiped(@NonNull final RecyclerView.ViewHolder viewHolder, int direction) { // Here is where you'll implement swipe to delete AlertDialog.Builder builder = new AlertDialog.Builder(DailyExpensesActivity.this, R.style.AlertDialogStyle); builder.setCancelable(false); builder.setIcon(R.drawable.okvir_za_datum_warning); builder.setTitle(getString(R.string.warning)); builder.setMessage(getString(R.string.are_you_sure)); builder.setPositiveButton(getString(R.string.yes), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // Get the position of the item to be deleted AppExecutors.getInstance().diskIO().execute(new Runnable() { @Override public void run() { int position = viewHolder.getAdapterPosition(); List<CostEntry> costEntries = mAdapter.getDailyCosts(); //costEntries -> all costs from RecyclerView on certain date mDb.costDao().deleteCost(costEntries.get(position)); sumCategoriesAndTotal(); } }); } }); builder.setNegativeButton(getString(R.string.no), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // User cancelled the dialog, // so we will refresh the adapter to prevent hiding the item from UI mAdapter.notifyItemChanged(viewHolder.getAdapterPosition()); } }); builder.create(); builder.show(); } }).attachToRecyclerView(mRecyclerView); /** * Set the Floating Action Button (FAB) to its corresponding View. * Attach an OnClickListener to it, so that when it's clicked, a new intent will be created * to launch the AddCostActivity. */ FloatingActionButton fab = findViewById(R.id.fabDaily); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(DailyExpensesActivity.this, AddCostActivity.class); intent.putExtra(EXTRA_COST_DATE, mCostDate); startActivity(intent); } }); if (savedInstanceState != null && savedInstanceState.containsKey(AddCostActivity.INSTANCE_COST_ID)) { mCostId = savedInstanceState.getInt(AddCostActivity.INSTANCE_COST_ID, DEFAULT_COST_ID); } initViews(); setupSharedPreferences(); } private void initViews() { tv_category_costs = findViewById(R.id.tv_category_costs); tv_total_cost = findViewById(R.id.tv_total_cost); } private void calenderDateSetting() { //getting date for setting a calender String week_day = Helper.fromUperCaseToFirstCapitalizedLetter (LocalDate.parse(mCostDate).getDayOfWeek().toString()); String date_No = valueOf(LocalDate.parse(mCostDate).getDayOfMonth()); String month = Helper.fromUperCaseToFirstCapitalizedLetter (LocalDate.parse(mCostDate).getMonth().toString()); String year = valueOf(LocalDate.parse(mCostDate).getYear()); tv_weekDay = findViewById(R.id.tv_weekDay); tv_dateNo = findViewById(R.id.tv_dateNo); tv_toolbar_mont_year = findViewById(R.id.tv_toolbar_month_year); tv_weekDay.setText(week_day); tv_dateNo.setText(date_No); tv_toolbar_mont_year.setText(month + ", " + year); tv_toolbar_mont_year.setTypeface(null, Typeface.BOLD); } @Override public void onDailyItemClickListener(int itemId) { // Launch AddCostActivity adding the itemId as an extra in the intent Intent intent = new Intent(DailyExpensesActivity.this, AddCostActivity.class); intent.putExtra(AddCostActivity.EXTRA_COST_ID, itemId); startActivity(intent); } @Override protected void onStart() { super.onStart(); sumCategoriesAndTotal(); } private void sumCategoriesAndTotal() { AppExecutors.getInstance().diskIO().execute(new Runnable() { @Override public void run() { totalCost = mDb.costDao().loadTotalCost(mCostDate); totalCostString = Helper.fromIntToDecimalString(totalCost); final Map<String, Integer> categoryCosts = new TreeMap<String, Integer>(); category1Cost = mDb.costDao().loadSumCategoryCost(mCostDate, CATEGORY_1); if (category1Cost > 0) { categoryCosts.put(CATEGORY_1, category1Cost); } category2Cost = mDb.costDao().loadSumCategoryCost(mCostDate, CATEGORY_2); if (category2Cost > 0) { categoryCosts.put(CATEGORY_2, category2Cost); } category3Cost = mDb.costDao().loadSumCategoryCost(mCostDate, CATEGORY_3); if (category3Cost > 0) { categoryCosts.put(CATEGORY_3, category3Cost); } category4Cost = mDb.costDao().loadSumCategoryCost(mCostDate, CATEGORY_4); if (category4Cost > 0) { categoryCosts.put(CATEGORY_4, category4Cost); } category5Cost = mDb.costDao().loadSumCategoryCost(mCostDate, CATEGORY_5); if (category5Cost != 0) { categoryCosts.put(CATEGORY_5, category5Cost); } category6Cost = mDb.costDao().loadSumCategoryCost(mCostDate, CATEGORY_6); if (category6Cost > 0) { categoryCosts.put(CATEGORY_6, category6Cost); } category7Cost = mDb.costDao().loadSumCategoryCost(mCostDate, CATEGORY_7); if (category7Cost > 0) { categoryCosts.put(CATEGORY_7, category7Cost); } category8Cost = mDb.costDao().loadSumCategoryCost(mCostDate, CATEGORY_8); if (category8Cost > 0) { categoryCosts.put(CATEGORY_8, category8Cost); } category9Cost = mDb.costDao().loadSumCategoryCost(mCostDate, CATEGORY_9); if (category9Cost > 0) { categoryCosts.put(CATEGORY_9, category9Cost); } runOnUiThread(new Runnable() { @Override public void run() { // update categoryCosts tv_category_costs.setText(""); Map.Entry<String, Integer> lastEntry = ((TreeMap<String, Integer>) categoryCosts).lastEntry(); for (Map.Entry<String, Integer> entry : categoryCosts.entrySet()) { if ((entry.getKey() + "=" + entry.getValue()).equals(lastEntry.toString())) { tv_category_costs.append(entry.getKey() + ": " + currency1 + Helper.fromIntToDecimalString(entry.getValue()) + currency2); } else { tv_category_costs.append(entry.getKey() + ": " + currency1 + Helper.fromIntToDecimalString(entry.getValue()) + currency2 + "\n"); } } // update total cost if (totalCost < 0) { tv_total_cost.setText("TOTAL > " + currency1 + "21 474 836.47 " + currency2); } else { tv_total_cost.setText("TOTAL: " + currency1 + totalCostString + currency2); } } }); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_daily_cost, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_settings) { Intent startSettingsActivity = new Intent(this, SettingsActivity.class); startActivity(startSettingsActivity); return true; } return super.onOptionsItemSelected(item); } private void setupSharedPreferences() { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); setCurrencyFromPreferences(sharedPreferences); // Register the listener sharedPreferences.registerOnSharedPreferenceChangeListener(this); } private void setCurrencyFromPreferences(SharedPreferences sharedPreferences) { String currency = sharedPreferences.getString(getString(R.string.pref_currency_key), getString(R.string.pref_currency_value_kuna)); if (currency.equals(getString(R.string.pref_currency_value_kuna))) { currency1 = ""; currency2 = " kn"; } else if (currency.equals(getString(R.string.pref_currency_value_euro))) { currency1 = ""; currency2 = " €"; } else if (currency.equals(getString(R.string.pref_currency_value_pound))) { currency1 = "£"; currency2 = ""; } else if (currency.equals(getString(R.string.pref_currency_value_dollar))) { currency1 = "$"; currency2 = ""; } } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if (key.equals(getString(R.string.pref_currency_key))) { setCurrencyFromPreferences(sharedPreferences); mAdapter.notifyDataSetChanged(); } } @Override protected void onDestroy() { super.onDestroy(); // Unregister VisualizerActivity as an OnPreferenceChangedListener to avoid any memory leaks. PreferenceManager.getDefaultSharedPreferences(this) .unregisterOnSharedPreferenceChangeListener(this); } }
package com.DropDown; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class NewTours_Register_Country_getCountryNames { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver","C:\\Users\\new\\eclipse-workspace\\BrowserAutomation\\DriverFiles\\chromedriver.exe"); WebDriver driver = null; driver=new ChromeDriver(); String url="http://newtours.demoaut.com/mercuryregister.php"; driver.get(url); driver.manage().window().maximize(); WebElement register=driver.findElement(By.linkText("REGISTER")); register.click(); List<WebElement>Country=driver.findElements(By.tagName("option")); int Countrycount=Country.size(); System.out.println("The number of Countries in Country DropDown are:"+Countrycount); for(int k=0;k<Country.size();k++) { Country.get(k).click(); if(Country.get(k).isSelected()){ System.out.println("Element is active"); } else { System.out.println("Element is inactive"); } String CountryName=Country.get(k).getText(); System.out.println(k+" "+"The Name of the Country is:"+CountryName); } driver.close(); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.messaginghub.pooled.jms; import java.util.Map; import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.api.core.TransportConfiguration; import org.apache.activemq.artemis.core.config.Configuration; import org.apache.activemq.artemis.core.config.impl.ConfigurationImpl; import org.apache.activemq.artemis.core.remoting.impl.invm.InVMAcceptorFactory; import org.apache.activemq.artemis.core.remoting.impl.invm.TransportConstants; import org.apache.activemq.artemis.core.server.embedded.EmbeddedActiveMQ; import org.apache.activemq.artemis.core.settings.impl.AddressSettings; import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.TestInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ArtemisJmsPoolTestSupport { protected static final Logger LOG = LoggerFactory.getLogger(ArtemisJmsPoolTestSupport.class); private static final String SERVER_NAME = "embedded-server"; protected String testName; protected ActiveMQConnectionFactory artemisJmsConnectionFactory; protected JmsPoolConnectionFactory cf; protected Configuration configuration; protected EmbeddedActiveMQ server; @BeforeEach public void setUp(TestInfo info) throws Exception { LOG.info("========== started test: " + info.getDisplayName() + " =========="); testName = info.getDisplayName(); configuration = new ConfigurationImpl().setName(SERVER_NAME) .setPersistenceEnabled(false) .setSecurityEnabled(false) .addAcceptorConfiguration(new TransportConfiguration(InVMAcceptorFactory.class.getName())) .addAddressesSetting("#", new AddressSettings().setDeadLetterAddress(SimpleString.toSimpleString("dla")).setExpiryAddress(SimpleString.toSimpleString("expiry"))); server = new EmbeddedActiveMQ().setConfiguration(configuration); server.start(); artemisJmsConnectionFactory = new ActiveMQConnectionFactory(getVmURL()); cf = new JmsPoolConnectionFactory(); cf.setConnectionFactory(artemisJmsConnectionFactory); cf.setMaxConnections(1); } private String getVmURL() { String vmURL = "vm://0"; for (TransportConfiguration transportConfiguration : configuration.getAcceptorConfigurations()) { Map<String, Object> params = transportConfiguration.getParams(); if (params != null && params.containsKey(TransportConstants.SERVER_ID_PROP_NAME)) { vmURL = "vm://" + params.get(TransportConstants.SERVER_ID_PROP_NAME); } } return vmURL; } @AfterEach public void tearDown() throws Exception { if (cf != null) { cf.stop(); } server.stop(); LOG.info("========== completed test: " + getTestName() + " =========="); } public String getTestName() { return testName; } }
package nachos.threads; import nachos.machine.Machine; public class AlarmTest { public void alarmTest(){ KThread k1 = new KThread(new sleepRunnable(4000)); k1.setName("첫번째 쓰레드"); KThread k2 = new KThread(new sleepRunnable(3000)); k2.setName("두번째 쓰레드"); KThread k3 = new KThread(new sleepRunnable(2000)); k3.setName("세번째 쓰레드"); KThread k4 = new KThread(new sleepRunnable(1000)); k4.setName("네번째 쓰레드"); KThread k5 = new KThread(new sleepRunnable(40000)); k5.setName("다섯번째 쓰레드"); KThread k6 = new KThread(new sleepRunnable(3000)); k6.setName("여섯번째 쓰레드"); KThread k7 = new KThread(new sleepRunnable(2000)); k7.setName("일곱번째 쓰레드"); KThread k8 = new KThread(new sleepRunnable(1000)); k8.setName("여덟번째 쓰레드"); k1.fork(); k2.fork(); k3.fork(); k4.fork(); k5.fork(); k6.fork(); k7.fork(); k8.fork(); k5.join(); } private class sleepRunnable implements Runnable{ private long waitTime; public sleepRunnable(long t){ waitTime = t; } @Override public void run() { // TODO Auto-generated method stub System.out.println(waitTime+"+"+Machine.timer().getTime()+ " 을 기다립니다."); ThreadedKernel.alarm.waitUntil(waitTime); System.out.println(KThread.currentThread().getName() +"가 "+waitTime+"을 기다리고 깨어났습니다."+"("+Machine.timer().getTime()+")"); } } }
package com.niksoftware.snapseed.controllers; import android.content.Context; import android.graphics.Bitmap; import android.view.View; import com.niksoftware.snapseed.controllers.adapters.ColorStyleItemListAdapter; import com.niksoftware.snapseed.controllers.adapters.StyleItemListAdapter; import com.niksoftware.snapseed.core.filterparameters.FilterParameter; import com.niksoftware.snapseed.util.TrackerData; import com.niksoftware.snapseed.views.BaseFilterButton; import com.niksoftware.snapseed.views.ItemSelectorView; import com.niksoftware.snapseed.views.ItemSelectorView.OnClickListener; import com.niksoftware.snapseed.views.ItemSelectorView.OnVisibilityChangeListener; import java.util.List; public class BlackAndWhiteController extends EmptyFilterController { private OnClickListener _colorFilterClickListener; private ColorStyleItemListAdapter _colorFilterListAdapter; private BaseFilterButton _colorFilterStyleButton; private ItemSelectorView _itemSelectorView; private BaseFilterButton _presetButton; private OnClickListener _presetClickListener; private StyleItemListAdapter _presetListAdapter; public void init(ControllerContext controllerContext) { super.init(controllerContext); addParameterHandler(); Context context = getContext(); FilterParameter filter = getFilterParameter(); this._colorFilterListAdapter = new ColorStyleItemListAdapter(filter); this._colorFilterClickListener = new OnClickListener() { public boolean onItemClick(Integer itemId) { if (BlackAndWhiteController.this.changeParameter(BlackAndWhiteController.this.getFilterParameter(), 241, itemId.intValue())) { TrackerData.getInstance().usingParameter(241, false); BlackAndWhiteController.this._colorFilterListAdapter.setActiveItemId(itemId); BlackAndWhiteController.this._itemSelectorView.refreshSelectorItems(BlackAndWhiteController.this._colorFilterListAdapter, true); } return true; } public boolean onContextButtonClick() { return false; } }; this._presetListAdapter = new StyleItemListAdapter(context, filter, 3, getTilesProvider().getStyleSourceImage()); this._presetClickListener = new OnClickListener() { public boolean onItemClick(Integer itemId) { if (BlackAndWhiteController.this.changeParameter(BlackAndWhiteController.this.getFilterParameter(), 3, itemId.intValue())) { TrackerData.getInstance().usingParameter(3, false); BlackAndWhiteController.this._presetListAdapter.setActiveItemId(itemId); BlackAndWhiteController.this._itemSelectorView.refreshSelectorItems(BlackAndWhiteController.this._presetListAdapter, true); } return true; } public boolean onContextButtonClick() { return false; } }; this._itemSelectorView = getItemSelectorView(); this._itemSelectorView.setOnVisibilityChangeListener(new OnVisibilityChangeListener() { public void onVisibilityChanged(boolean isVisible) { if (!isVisible) { BlackAndWhiteController.this._presetButton.setSelected(false); BlackAndWhiteController.this._colorFilterStyleButton.setSelected(false); } } }); } public void cleanup() { getEditingToolbar().itemSelectorWillHide(); this._itemSelectorView.setVisible(false, false); this._itemSelectorView.cleanup(); this._itemSelectorView = null; super.cleanup(); } public int getFilterType() { return 7; } public int[] getGlobalAdjustmentParameters() { return new int[]{0, 1, 14}; } public boolean showsParameterView() { return true; } public boolean initLeftFilterButton(BaseFilterButton button) { if (button == null) { this._presetButton = null; return false; } this._presetButton = button; this._presetButton.setStateImages((int) R.drawable.icon_tb_presets_default, (int) R.drawable.icon_tb_presets_active, 0); this._presetButton.setText(getButtonTitle(R.string.presets)); this._presetButton.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { BlackAndWhiteController.this._presetButton.setSelected(true); BlackAndWhiteController.this._presetListAdapter.setActiveItemId(Integer.valueOf(BlackAndWhiteController.this.getFilterParameter().getParameterValueOld(3))); BlackAndWhiteController.this._itemSelectorView.reloadSelector(BlackAndWhiteController.this._presetListAdapter, BlackAndWhiteController.this._presetClickListener); BlackAndWhiteController.this._itemSelectorView.setVisible(true, true); BlackAndWhiteController.this.previewImages(3); } }); return true; } public boolean initRightFilterButton(BaseFilterButton button) { if (button == null) { this._colorFilterStyleButton = null; return false; } this._colorFilterStyleButton = button; this._colorFilterStyleButton.setStateImages((int) R.drawable.icon_tb_colorfilter_default, (int) R.drawable.icon_tb_colorfilter_active, 0); this._colorFilterStyleButton.setText(getButtonTitle(R.string.colorFilter)); this._colorFilterStyleButton.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { BlackAndWhiteController.this._colorFilterStyleButton.setSelected(true); BlackAndWhiteController.this._colorFilterListAdapter.setActiveItemId(Integer.valueOf(BlackAndWhiteController.this.getFilterParameter().getParameterValueOld(241))); BlackAndWhiteController.this._itemSelectorView.reloadSelector(BlackAndWhiteController.this._colorFilterListAdapter, BlackAndWhiteController.this._colorFilterClickListener); BlackAndWhiteController.this._itemSelectorView.setVisible(true, true); } }); return true; } public BaseFilterButton getLeftFilterButton() { return this._presetButton; } public BaseFilterButton getRightFilterButton() { return this._colorFilterStyleButton; } public void setPreviewImage(List<Bitmap> images, int parameter) { if (this._presetListAdapter.updateStylePreviews(images)) { this._itemSelectorView.refreshSelectorItems(this._presetListAdapter, false); } } }
package com.needii.dashboard.controller; import java.text.ParseException; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.PostConstruct; import javax.servlet.ServletContext; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.google.api.client.util.ArrayMap; import com.ibm.icu.text.SimpleDateFormat; import com.needii.dashboard.components.CompomentList; import com.needii.dashboard.components.Messages; import com.needii.dashboard.helper.ResponseStatusEnum; import com.needii.dashboard.model.Article; import com.needii.dashboard.model.Banner; import com.needii.dashboard.model.BannerData; import com.needii.dashboard.model.BaseResponse; import com.needii.dashboard.model.FileBucket; import com.needii.dashboard.model.Landing; import com.needii.dashboard.model.LandingData; import com.needii.dashboard.model.Product; import com.needii.dashboard.model.ProductData; import com.needii.dashboard.model.Supplier; import com.needii.dashboard.model.form.BannerForm; import com.needii.dashboard.model.form.SearchForm; import com.needii.dashboard.service.ArticleService; import com.needii.dashboard.service.BannerService; import com.needii.dashboard.service.LandingService; import com.needii.dashboard.service.LanguageService; import com.needii.dashboard.service.ProductService; import com.needii.dashboard.service.SupplierService; import com.needii.dashboard.utils.Constants; import com.needii.dashboard.utils.Option; import com.needii.dashboard.utils.Pagination; import com.needii.dashboard.utils.UtilsMedia; import com.needii.dashboard.validator.BannerFormValidator; import com.needii.dashboard.validator.FileValidator; @Controller @RequestMapping(value = "/banners" ) @PreAuthorize("hasAuthority('SUPPLIER_MANAGER') or hasAuthority('SUPERADMIN') or hasAuthority('ADMIN')") public class BannerController extends BaseController{ @Autowired ServletContext context; @Autowired private BannerService bannerService; @Autowired private SupplierService supplierService; @Autowired private ProductService productService; @Autowired private LandingService landingService; @Autowired private ArticleService articleService; @Autowired private LanguageService languageService; @Autowired CompomentList compomentList; @Autowired private FileValidator fileValidator; @Autowired private BannerFormValidator bannerFormValidator; @Autowired Messages messages; @PostConstruct public void initialize() { super.initialize(); } @ModelAttribute("statusList") public Map<Integer, String> status() { return compomentList.status(); } @ModelAttribute("contentTypeBanner") public Map<Integer, String> contentTypeBanner() { Map<Integer,String> map = compomentList.contentTypeBanner(); Map<Integer, String> newMap = new HashMap<>(); newMap.put(0, ""); newMap.putAll(map); return newMap; } @RequestMapping(value = {""}, method = RequestMethod.GET) public String index(Model model, @RequestParam(name = "name", required = false) String name, @RequestParam(name = "status", required = false) Integer status, @RequestParam(name = "bannerType", required = false, defaultValue="0") Integer bannerType, @RequestParam(name = "page", required = false) Integer page ) { if (page == null) page = 1; Pagination pagination = new Pagination(page, this.numberPage); Option option = new Option(); option.setPagination(pagination); Map<String, Object> queryString = new HashMap<>(); queryString.put("name", name); if(status != null && status >= 0) { queryString.put("status", status); } if(bannerType != null && bannerType > 0) { queryString.put("bannerType", bannerType); } option.setQueryString(queryString); SearchForm formSearch = new SearchForm(); formSearch.setName(name); formSearch.setStatus(status); formSearch.setBannerType(bannerType); List<Banner> items = bannerService.findAll(option); model.addAttribute("totalRecord", bannerService.count(option).intValue()); model.addAttribute("limit", this.numberPage); model.addAttribute("currentPage", page); model.addAttribute("formSearch", formSearch); model.addAttribute("items", items); model.addAttribute("languages", languageService.findAll()); return "banners"; } @RequestMapping(value = {"/{id}/create"}, method = RequestMethod.GET) public String create(Model model) { model.addAttribute("bannerForm", new BannerForm()); return "bannerCreate"; } @RequestMapping(value = {"/{id}/create"}, method = RequestMethod.POST) public String store(@ModelAttribute("file") FileBucket image, @ModelAttribute("bannerForm") @Validated BannerForm bannerForm, BindingResult result, Model model, final RedirectAttributes redirectAttributes){ image.setFiled("bannerDataForm.images"); fileValidator.validate(image, result); bannerFormValidator.validate(bannerForm, result); if (result.hasErrors()) { model.addAttribute("bannerForm", bannerForm); return "bannerCreate"; } Banner banner = new Banner(); banner.setContentId(bannerForm.getContentId()); banner.setContentType(bannerForm.getContentType()); if(bannerForm.getContentType() == 1){ banner.setContentId(bannerForm.getSupplierId()); } banner.setOrder(0); banner.setStatus(bannerForm.getStatus()); if (!bannerForm.getFromStringDate().isEmpty() && !bannerForm.getToStringDate().isEmpty()){ SimpleDateFormat formatter = new SimpleDateFormat(Constants.dateFormat); Date startTime = null; Date endTime = null; try { startTime = formatter.parse(bannerForm.getFromStringDate()); endTime = formatter.parse(bannerForm.getToStringDate()); } catch (ParseException e) { e.printStackTrace(); } banner.setFromDate(startTime); banner.setToDate(endTime); } BannerData bannerData = new BannerData(); bannerData.setName(bannerForm.getBannerDataForm().getName()); bannerData.setDescription(""); bannerData.setLanguageId(Constants.DEFAULT_VIETNAMESE_LANGUAGE_ID); bannerData.setBanner(banner); if (!image.isEmpty()) { String webappRoot = context.getRealPath(Constants.SAVE_BANNER_PATH); Map<String, String> resultUpload = UtilsMedia.uploadImage(image.getFile(), webappRoot); bannerData.setImages(Constants.SAVE_BANNER_PATH + resultUpload.get("fileName")); } Set<BannerData> bannerDatas = new HashSet<>(); bannerDatas.add(bannerData); banner.setBannerData(bannerDatas); bannerService.create(banner); redirectAttributes.addFlashAttribute( "success_message", messages.get("General.message.create_success", new Object[]{"banner"})); return "redirect:/banners"; } @RequestMapping(value = {"/{id}/edit"}, method = RequestMethod.GET) public String edit(@PathVariable long id, Model model) { Banner banner = bannerService.findOne(id); if (banner == null) { return "404"; } Supplier supplier = null; ArrayMap<Long, String> objects = new ArrayMap<>(); if (banner.getContentType() == 1){ supplier = supplierService.findOne(banner.getContentId()); if(supplier != null){ objects.add(supplier.getId(), supplier.getFullName()); } } if (banner.getContentType() == 2){ Landing landing = landingService.findOne(banner.getContentId()); if(landing != null) { supplier = landing.getSupplier(); objects.add(landing.getId(), landing.getData().getName()); } } if (banner.getContentType() == 3){ Product product = productService.findOne(banner.getContentId()); if(product != null) { supplier = product.getSupplier(); objects.add(product.getId(), product.getData().getName()); } } if (banner.getContentType() == 4){ objects.add(0L, "popup"); } model.addAttribute("bannerForm", new BannerForm(banner)); model.addAttribute("objects", objects); model.addAttribute("supplier", supplier); return "bannerEdit"; } @RequestMapping(value = {"/{id}/edit"}, method = RequestMethod.POST) public String update(@PathVariable long id, @ModelAttribute("file") FileBucket image, @ModelAttribute("bannerForm") @Validated BannerForm bannerForm, BindingResult result, Model model, final RedirectAttributes redirectAttributes) { Banner banner = bannerService.findOne(id); if (banner == null) { return "404"; } bannerFormValidator.validate(bannerForm, result); System.out.println("Print Log"); System.out.println(result.getAllErrors()); if (result.hasErrors()) { Supplier supplier = null; ArrayMap<Long, String> objects = new ArrayMap<>(); if (banner.getContentType() == 1){ supplier = supplierService.findOne(banner.getContentId()); if(supplier != null){ objects.add(supplier.getId(), supplier.getFullName()); } } if (banner.getContentType() == 2){ Landing landing = landingService.findOne(banner.getContentId()); if(landing != null) { supplier = landing.getSupplier(); objects.add(landing.getId(), landing.getData().getName()); } } if (banner.getContentType() == 3){ Product product = productService.findOne(banner.getContentId()); if(product != null) { supplier = product.getSupplier(); objects.add(product.getId(), product.getData().getName()); } } if (banner.getContentType() == 4){ objects.add(0L, "popup"); } bannerForm.setContentType(banner.getContentType()); bannerForm.setImages(banner.getData().getImages()); model.addAttribute("bannerForm", bannerForm); model.addAttribute("objects", objects); model.addAttribute("supplier", supplier); return "bannerEdit"; } banner.setContentId(bannerForm.getContentId()); if(bannerForm.getContentType() == 1){ banner.setContentId(bannerForm.getSupplierId()); } banner.setContentType(banner.getContentType()); banner.setOrder(0); banner.setStatus(bannerForm.getStatus()); if (!bannerForm.getFromStringDate().isEmpty() && !bannerForm.getToStringDate().isEmpty()){ SimpleDateFormat formatter = new SimpleDateFormat(Constants.dateFormat); Date startTime = null; Date endTime = null; try { startTime = formatter.parse(bannerForm.getFromStringDate()); endTime = formatter.parse(bannerForm.getToStringDate()); } catch (ParseException e) { e.printStackTrace(); } banner.setFromDate(startTime); banner.setToDate(endTime); } BannerData bannerData = banner.getData(); bannerData.setName(bannerForm.getBannerDataForm().getName()); bannerData.setDescription(""); bannerData.setLanguageId(Constants.DEFAULT_VIETNAMESE_LANGUAGE_ID); bannerData.setBanner(banner); if (!image.isEmpty()) { String webappRoot = context.getRealPath(Constants.SAVE_BANNER_PATH); Map<String, String> resultUpload = UtilsMedia.uploadImage(image.getFile(), webappRoot); bannerData.setImages(Constants.SAVE_BANNER_PATH + resultUpload.get("fileName")); } Set<BannerData> bannerDatas = new HashSet<>(); bannerDatas.add(bannerData); banner.setBannerData(bannerDatas); bannerService.update(banner); redirectAttributes.addFlashAttribute( "success_message", messages.get("General.message.edit_success", new Object[]{"banner"})); return "redirect:/banners"; } @RequestMapping(value = { "/get-list" }, method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE }) public ResponseEntity<BaseResponse> getSuppliers( @RequestParam(name = "name", required=false, defaultValue = "") String name, @RequestParam(name = "content_id", required=false) Integer contentId, @RequestParam(name = "supplier_id", required=false) Long supplierId){ BaseResponse response = new BaseResponse(); response.setStatus(ResponseStatusEnum.SUCCESS); response.setMessage(ResponseStatusEnum.SUCCESS); response.setData(null); if (supplierId == null && contentId != 1) { response.setStatus(ResponseStatusEnum.NOT_FOUND); response.setMessage(ResponseStatusEnum.NOT_FOUND); }else { try { List<Object> objects = new ArrayList<Object>(); Pageable pageable = new PageRequest(0, 10); if (contentId == 1) { List<Supplier> suppliers = supplierService.findByFullName(name, pageable); for (Supplier supplier : suppliers) { Object data = new Object() { @SuppressWarnings("unused") public final long id = supplier.getId(); @SuppressWarnings("unused") public final String text = supplier.getFullName(); }; objects.add(data); } } if (contentId == 2) { List<LandingData> landings = landingService.findByName(name, 1, supplierId, pageable); for (LandingData landing : landings) { Object data = new Object() { @SuppressWarnings("unused") public final long id = landing.getId(); @SuppressWarnings("unused") public final String text = landing.getName(); }; objects.add(data); } } if (contentId == 3) { List<ProductData> products = productService.findByName(name, 1, supplierId, pageable); for (ProductData product : products) { Object data = new Object() { @SuppressWarnings("unused") public final long id = product.getProduct().getId(); @SuppressWarnings("unused") public final String text = product.getName(); }; objects.add(data); } } if (contentId == 4) { List<Article> articles = articleService.findByTitle(name, supplierId, pageable); for (Article article : articles) { Object data = new Object() { @SuppressWarnings("unused") public final long id = article.getId(); @SuppressWarnings("unused") public final String text = article.getTitle(); }; objects.add(data); } } response.setResults(objects); } catch (Exception ex) { response.setStatus(ResponseStatusEnum.FAIL); response.setMessageError(ex.getMessage()); ex.printStackTrace(); } } return new ResponseEntity<>(response, HttpStatus.OK); } @RequestMapping(value = { "{id}/delete" }, method = RequestMethod.POST) public String delete(@PathVariable long id, final RedirectAttributes redirectAttributes) { Banner banner = bannerService.findOne(id); if(banner == null) { return "404"; } banner.setIsDeleted(true); bannerService.update(banner); redirectAttributes.addFlashAttribute( "success_message", messages.get("General.message.delete_success", new Object[]{"banner"})); return "redirect:/banners"; } @RequestMapping(value = { "/change-status/{id}" }, method = RequestMethod.POST, produces = {MediaType.APPLICATION_JSON_VALUE}) public ResponseEntity<BaseResponse> changeStatus(@PathVariable("id") Long id) { Banner banner = bannerService.findOne(id); BaseResponse response = new BaseResponse(); response.setStatus(ResponseStatusEnum.SUCCESS); response.setMessage(ResponseStatusEnum.SUCCESS); response.setData(null); try { if (banner == null) { response.setStatus(ResponseStatusEnum.NOT_FOUND); response.setMessage(ResponseStatusEnum.NOT_FOUND); } else { banner.setStatus(banner.getStatus() == 1 ? 0 : 1); bannerService.update(banner); response.setStatus(ResponseStatusEnum.SUCCESS); response.setMessage(ResponseStatusEnum.SUCCESS); } } catch (Exception ex) { response.setStatus(ResponseStatusEnum.FAIL); response.setMessageError(ex.getMessage()); ex.printStackTrace(); } return new ResponseEntity<>(response, HttpStatus.OK); } }
package com.durgesh.schoolassist; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.parse.ParseException; import com.parse.ParseObject; import com.parse.ParseQuery; public class StudentActivity extends AppCompatActivity { Bundle bundle; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_student); bundle = getIntent().getExtras(); getSupportActionBar().setDisplayHomeAsUpEnabled(true); Button button = findViewById(R.id.take_quiz); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ParseQuery<ParseObject> query = ParseQuery.getQuery("Answers"); query.whereEqualTo("username", bundle.getString("user")); try { if (query.count()>0) { Toast.makeText(getApplicationContext(),"You Have Already Given Test",Toast.LENGTH_LONG).show(); } else { startActivity(new Intent(StudentActivity.this,TakeQuizActivity.class).putExtra("user",bundle.getString("user"))); } } catch (ParseException e) { e.printStackTrace(); } } }); } @Override public boolean onSupportNavigateUp() { // getSupportActionBar().setDisplayHomeAsUpEnabled(true); onBackPressed(); return true; } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.logout,menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id==R.id.log_out) { startActivity(new Intent(StudentActivity.this,MainActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)); finish(); } return super.onOptionsItemSelected(item); } }
class u1 { public static void main(String[] args){ System.out.println("u1第一次修改2021年6月10日 15:27:31") } }
package org.qw3rtrun.aub.engine.opengl; public class FragmentShader extends Shader { public FragmentShader(String glsl) { super(ShaderTypeEnum.FRAGMENT, glsl); } }
package pattern.factory; public class TestaEmissor { public static void main(String[] args) { EmissorCreator emissorCreator = new EmissorCreator(); Emissor emissor = emissorCreator.create(EmissorCreator.SMS); emissor.envia("Enviandor por sms"); Emissor emissor2 = emissorCreator.create(EmissorCreator.EMAIL); emissor2.envia("Enviandor por email"); } }
package com.lenovohit.hcp.base.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; @Entity @Table(name = "B_TREE_VALUE") public class Tree extends HcpBaseModel { private static final long serialVersionUID = -1770624887063184496L; private String parentId; private String dictType; private String key; private String value; private Integer sortId; private Boolean defaulted = false;// '是否默认' private String spellCode;// '拼音|超过10位无检索意义' private String wbCode;// '五笔' private String userCode;// '自定义码' private Boolean stop;// '停用标志|1停0-启' private String comment; private Boolean leaf; public String getParentId() { return parentId; } public void setParentId(String parentId) { this.parentId = parentId; } public String getDictType() { return dictType; } public void setDictType(String dictType) { this.dictType = dictType; } @Column(name = "DICT_KEY") public String getKey() { return key; } public void setKey(String key) { this.key = key; } @Column(name = "DICT_VALUE") public String getValue() { return value; } public void setValue(String value) { this.value = value; } public Integer getSortId() { return sortId; } public void setSortId(Integer sortId) { this.sortId = sortId; } @Column(name = "ISDEFAULT") public Boolean getDefaulted() { return defaulted; } public void setDefaulted(Boolean defaulted) { this.defaulted = defaulted; } public String getSpellCode() { return spellCode; } public void setSpellCode(String spellCode) { this.spellCode = spellCode; } public String getWbCode() { return wbCode; } public void setWbCode(String wbCode) { this.wbCode = wbCode; } public String getUserCode() { return userCode; } public void setUserCode(String userCode) { this.userCode = userCode; } @Column(name = "STOP_FLAG") public Boolean isStop() { return stop; } public void setStop(Boolean stop) { this.stop = stop; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } @Column(name = "IS_LEAF") public Boolean isLeaf() { return leaf; } public void setLeaf(Boolean leaf) { this.leaf = leaf; } }
package LeetCode; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.PriorityQueue; public class ReorderDataInLogFiles { /* * O(3Nlog(N)) -> O(Nlog(N)) * */ public static void main(String[] args) { ReorderDataInLogFiles solution = new ReorderDataInLogFiles(); String[] ans = solution.reorderLogFiles(new String[] {"a1 9 2 3 1","g1 act car","zo4 4 7","ab1 off key dog","a8 act zoo","a2 act car"}); for (String log : ans) System.out.println(log); } // O(Nlog(N) public String[] reorderLogFiles(String[] logs) { PriorityQueue<String> q = new PriorityQueue<>(logs.length, new Comparator<String>() { @Override public int compare(String o1, String o2) { int subStringIndex1 = o1.indexOf(" "); int subStringIndex2 = o2.indexOf(" "); if (o1.substring(subStringIndex1+1).compareTo(o2.substring(subStringIndex2+1)) == 0) { return o1.compareTo(o2); } else return o1.substring(subStringIndex1+1).compareTo(o2.substring(subStringIndex2+1)); } }); List<String> digits = new ArrayList<>(); //O(N) for (String log : logs) { if (log.charAt(log.length()-1) < 'a') digits.add(log); else q.offer(log); } String[] result = new String[logs.length]; int resultPointer = 0; //O(N) while (!q.isEmpty()) result[resultPointer++] = q.poll(); for (String digit : digits) result[resultPointer++] = digit; return result; } }
package com.zzh.cloud.feign; import com.zzh.cloud.entity.User; import com.zzh.config.FeignConfig; import feign.Param; import feign.RequestLine; import org.springframework.cloud.netflix.feign.FeignClient; /** * @author zhaozh * @version 1.0 * @date 2018-1-3 17:57 **/ @FeignClient(name = "user-provider-reg", configuration = FeignConfig.class, fallback = FeignClientFallback.class) public interface UserFeignClient { /** * 这里的注解 RequestLine、Param 是 Feign 的配置新的注解, * 参考链接:https://github.com/OpenFeign/feign * * @param id * @return */ @RequestLine("GET /user/{id}") public User findById(@Param("id") Long id); }
package ru.mcfr.oxygen.updater.utils; import org.apache.log4j.Logger; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.Enumeration; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipOutputStream; /** * Created by IntelliJ IDEA. * User: ws * Date: 28.04.11 * Time: 16:12 * To change this template use File | Settings | File Templates. */ public class Zipper { private static Logger logger = Logger.getLogger(Zipper.class); public static String unzip(File zipSrc, String destination) { try { ZipEntry entry; ZipFile zipfile = new ZipFile(zipSrc); Enumeration e = zipfile.entries(); (new File(destination)).mkdirs(); while (e.hasMoreElements()) { entry = (ZipEntry) e.nextElement(); if (entry.isDirectory()) (new File(destination + File.separator + entry.getName())).mkdirs();//unzip folder else { File entryFile = new File(destination + File.separator + entry.getName()); entryFile.getParentFile().mkdirs(); entryFile.createNewFile(); Streamer.bufferedStreamCopy(zipfile.getInputStream(entry), new FileOutputStream(entryFile)); } } return zipfile.entries().nextElement().getName(); //return true; } catch (IOException e) { e.printStackTrace(); logger.error(e.getLocalizedMessage()); return ""; } } private static void rsAddInZip(ZipOutputStream zos, File baseDir,File entryDir){ try { for (File entry : entryDir.listFiles()) { System.out.println(entry.getAbsolutePath()); if (entry.isFile()){ ZipEntry zipEntry = new ZipEntry(FileCommander.getRelativePath(baseDir, entry)); zipEntry.setComment("packed by me"); zos.putNextEntry(zipEntry); Streamer.bufferedStreamCopy_noCloseOut(new FileInputStream(entry),zos); zos.closeEntry(); } rsAddInZip(zos, baseDir, entry); } } catch (Exception e) { logger.error(e.getLocalizedMessage()); } } public static boolean zip(File src, String destination){ try { File destFile = new File(destination); if (!destFile.exists()){ destFile.getParentFile().mkdirs(); destFile.createNewFile(); } ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(destFile)); rsAddInZip(zos, src.getParentFile(),src); //zos.closeEntry(); zos.finish(); zos.close(); } catch (IOException e){ logger.error(e.getLocalizedMessage()); return false; } return true; } }
class ourexception extends Exception{ /* create our own checked exception(or custom checked exception) class(like SQLException class) by extending the Exception class*/ ourexception(String message){ super(message); } } public class throwourexception { public static void main(String[] args) { int x=10; int y=20; try{ int z=y/x; if(z>1){ throw new ourexception("z is greater than 1"); } } catch(ourexception e){ System.out.println("error is caught"); System.out.println(e); System.out.println(e.getMessage()); } System.out.println("rest of code"); } } /* or */ /* public class TestThrow1{ static void validate(int age){ if(age<18) throw new ArithmeticException("not valid"); else System.out.println("welcome to vote"); } public static void main(String args[]){ validate(13); System.out.println("rest of the code..."); } } */
package br.com.fiap.dao.impl; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.TypedQuery; import br.com.fiap.dao.TransporteDAO; import br.com.fiap.entity.Transporte; public class TransporteDAOImpl extends DAOImpl<Transporte,Integer> implements TransporteDAO{ public TransporteDAOImpl(EntityManager entityManager) { super(entityManager); } @Override public List<Transporte> buscarPorEmpresa(String empresa) { TypedQuery<Transporte> query = em.createNamedQuery("Transporte.porEmpresa", Transporte.class); query.setParameter("e", "%"+ empresa + "%"); return query.getResultList(); } }
package com.tongchuang.huangshan.common.enums; import lombok.Getter; @Getter public enum ResultEnum { UNKNOW_ERROR("-1","未知异常"), SUCCESS("200", "成功"), PARAM_ERROR("301", "参数错误"), PARAM_FILE_IS_NOT_NULL("301001","上传文件不能为空"), PARAM_FILE_NAME_IS_NOT_NULL("301002","上传文件名不能为空"), VEHICLE_INFO_IS_NULL("310001","车辆未录入环保台账,请联系销售部门或物流部门录入台账。如果车辆已到达现场可直接在门岗录入台账。"), VEHICLE_INFO_IS_LIMITED("310002","重污染限制,车辆不允许进入"), VEHICLE_CAR_NUMBER_IS_NOT_NUL("310003","车牌号不能为空"), VEHICLE_INFO_IS_EXIST("310004","车牌信息已存在"), OCR_IS_ERROR("310005","ocr识别失败"), DEPARTMENT_IS_STOP("401001","部门停用,不允许新增"), DICT_TYPE_IS_USE("401002","数据字典已分配,不能删除"), USER_ACCOUNT_IS_ERROR("402001","获取用户账户异常"), USER_INFO_IS_ERROR("402002","获取用户信息异常"), USER_IS_NOT_PERMITS("402003","用户没有权限"), USER_ROLE_IS_USE("402004","用户角色已分配,不能删除"), POST_IS_USE("403001","岗位已分配,不能删除"), IS_ERROR("500","系统异常") ; private String code; private String message; ResultEnum(String code, String message) { this.code = code; this.message = message; } }
package com.arthur.leetcode; /** * @program: leetcode * @description: 买卖股票的最佳时机 II ——二刷 * @title: No122_2 * @Author hengmingji * https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii/solution/best-time-to-buy-and-sell-stock-ii-zhuan-hua-fa-ji/ * 等价于每天都买卖 * @Date: 2021/12/25 15:32 * @Version 1.0 */ public class No122_2 { public int maxProfit(int[] prices) { int temp; int ans = 0; for (int i = 1; i < prices.length; i++) { temp = prices[i] - prices[i - 1]; if(temp > 0) { ans += temp; } } return ans; } }
/** * * @author Matthew Clayton * @version January 3, 2015 * @assign.ment Shopping Cart * @descrip.tion This class creates item objects for use in the ShoppingCartV2MC * class each containing cost and name data. * * */ public class ItemV2MC { String name; double cost; public ItemV2MC(String unitName, double unitCost) { name = unitName; cost = unitCost; } public double getPrice() { return cost; } public String getName() { return name; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Bean; /** * * @author mengqwang */ public class Reserve { private int memberID; public int getMemberID() { return memberID; } public void setMemberID(int memberID) { this.memberID = memberID; } public int getSectionID() { return sectionID; } public void setSectionID(int sectionID) { this.sectionID = sectionID; } public int getSeat() { return seat; } public void setSeat(int seat) { this.seat = seat; } private int sectionID; private int seat; }
package Account_Module.Transaction; import Account_Module.Wallet.WalletUtils; import DB_Module.block.Block; import DB_Module.block.Blockchain; import com.google.common.collect.Maps; import lombok.Synchronized; import org.apache.commons.codec.binary.Hex; import org.apache.commons.lang3.ArrayUtils; import DB_Module.RocksDBUtils; import Account_Module.util.SerializeUtils; import java.util.Map; /** * 未被花费的交易输出池 * * @author dingkonghua * @date 2018/07/27 */ public class UTXOSet { private Blockchain blockchain; public UTXOSet(){} public UTXOSet(Blockchain blockchain){ this.blockchain = blockchain; } /** * 从磁盘上寻找某个地址的能够花费的交易输出(未花费的交易输出) * * @param pubKeyHash 钱包公钥Hash * @param amount 需要花费的金额 */ public SpendableOutputResult findSpendableOutputsByType(byte[] pubKeyHash, int amount , String type) { //保存当前发送者用于转账的utxo,key为交易id,value为指向上一笔的交易输出索引集合 Map<String, int[]> unspentOuts = Maps.newHashMap(); int accumulated = 0; //从内存缓存utxo池中获取所有的utxo,key为交易id,value为所有的交易输出数据 Map<String, byte[]> utxosMap = RocksDBUtils.getInstance().getUtxosMap(); for (Map.Entry<String, byte[]> entry : utxosMap.entrySet()) { String txId = entry.getKey(); //获取一个交易中的输出集合 TXOutput[] txOutputs = (TXOutput[]) SerializeUtils.deserialize(entry.getValue()); //遍历交易输出集合 for (int outId = 0; outId < txOutputs.length; outId++) { TXOutput txOutput = txOutputs[outId]; //判断交易输出的类型,只有符合的交易输出才会被统计,但是CoinBase交易也可以作为转账交易 if(type.equals(txOutput.getTxOutputType()) || AccountConstant.TRANSACTION_TYPE_COINBASE.equals(txOutput.getTxOutputType())){ //判断该交易输出的公钥是否是当前交易的发送者公钥,是的话表示这个交易输出是当前发送者未花费的交易输出 if (txOutput.isLockedWithKey(pubKeyHash) && accumulated < amount) { accumulated += txOutput.getValue(); int[] outIds = unspentOuts.get(txId); if (outIds == null) { outIds = new int[]{outId}; } else { outIds = ArrayUtils.add(outIds, outId); } unspentOuts.put(txId, outIds); if (accumulated >= amount) { break; } } } } if (accumulated >= amount) { break; } } return new SpendableOutputResult(accumulated, unspentOuts); } /** * 查找钱包地址对应的所有UTXO * @param pubKeyHash 钱包公钥Hash * @return */ public TXOutput[] findUTXOs(byte[] pubKeyHash) { TXOutput[] utxos = {}; Map<String, byte[]> chainstateBucket = RocksDBUtils.getInstance().getUtxosMap(); if (chainstateBucket.isEmpty()) { return utxos; } for (byte[] value : chainstateBucket.values()) { TXOutput[] txOutputs = (TXOutput[]) SerializeUtils.deserialize(value); for (TXOutput txOutput : txOutputs) { if (txOutput.isLockedWithKey(pubKeyHash)) { utxos = ArrayUtils.add(utxos, txOutput); } } } return utxos; } /** * 重建 UTXO 池索引,先从内存中清除未花费的交易输出池 , 然后从区块数据中将未花费的交易输出重新写入文件 */ @Synchronized public void reIndex() { System.out.println("Start to reIndex UTXO set !"); RocksDBUtils.getInstance().cleanChainStateBucket(); //获取所有未花费的交易输出 Map<String, TXOutput[]> allUTXOs = blockchain.findAllUTXOs(); for (Map.Entry<String, TXOutput[]> entry : allUTXOs.entrySet()) { RocksDBUtils.getInstance().putUTXOs(entry.getKey(), entry.getValue()); } System.out.println("ReIndex UTXO set finished ! "); } /** * 更新UTXO池 * 当一个新的区块产生时,需要去做两件事情: * 1)从UTXO池中移除花费掉了的交易输出; * 2)保存新的未花费交易输出; * * @param tipBlock 最新的区块 */ @Synchronized public static void updateUtxoAndStore(Block tipBlock) { if (tipBlock == null) { System.out.println("Fail to updateUtxoAndStore UTXO set ! tipBlock is null !"); throw new RuntimeException("Fail to updateUtxoAndStore UTXO set ! "); } for (Transaction transaction : tipBlock.getTransactions()) { // 根据交易输入排查出剩余未被使用的交易输出 if (!transaction.isCoinbase()) { //遍历该笔交易中所有的交易输入,与未花费的交易输出做对比(比对成功表示交易输出已经被花费) , 剔除掉已经花费的交易输出 for (TXInput txInput : transaction.getInputs()) { // 余下未被使用的交易输出 TXOutput[] remainderUTXOs = {}; String txId = Hex.encodeHexString(txInput.getTxId()); //获取这笔交易对应的上一笔交易输出 TXOutput[] txOutputs = RocksDBUtils.getInstance().getUTXOs(txId); if (txOutputs == null) { continue; } //从一个交易输出的集合中剔除掉交易输入所包含的索引 for (int outIndex = 0; outIndex < txOutputs.length; outIndex++) { if (outIndex != txInput.getTxOutputIndex()) { remainderUTXOs = ArrayUtils.add(remainderUTXOs, txOutputs[outIndex]); } } // 没有剩余则删除,否则更新 if (remainderUTXOs.length == 0) { RocksDBUtils.getInstance().deleteUTXOs(txId); } else { RocksDBUtils.getInstance().putUTXOs(txId, remainderUTXOs); } } } // CoinBase交易直接将交易输出保存到DB中 TXOutput[] txOutputs = transaction.getOutputs(); String txId = Hex.encodeHexString(transaction.getTxId()); RocksDBUtils.getInstance().putUTXOs(txId, txOutputs); } } /** * 更新UTXO内存缓存池 * 当一个新的本地交易产生时,需要从UTXO缓存池中移除花费掉了的交易输出 * todo 问题:此方法是在10秒之内未出块时连续对一个账户出现多笔交易时才有用,但是这样做引出了另外一个问题,那就是该账户的下一比交易进行签名是从区块链中是找不到交易输入对应的上一笔交易输出的,因此此时上一笔交易还有入块 * todo 对于上面的问题,可以考虑在查询一笔交易中交易输入对应的上一笔交易时可以加入当链中没有时可以从交易池中获取 , 该方法仅仅是一个解决方案但是没有经过实践...... */ @Synchronized public static void updateMemoryTempUtxo(Transaction transaction) { if (transaction == null) { System.out.println("失败更新内存utxo缓存,交易transaction为null !"); } // 根据交易输入排查出剩余未被使用的交易输出 //遍历该笔交易中所有的交易输入,与未花费的交易输出做对比(比对成功表示交易输出已经被花费) , 从内存缓存utxo池中剔除掉已经花费的交易输出 for (TXInput txInput : transaction.getInputs()) { // 余下未被使用的交易输出 TXOutput[] remainderUTXOs = {}; String txId = Hex.encodeHexString(txInput.getTxId()); //获取这笔交易中每一笔交易输入对应的上一笔交易的所有交易输出集合 TXOutput[] txOutputs = RocksDBUtils.getInstance().getUTXOs(txId); System.out.println("2222:"+txInput.getTxOutputIndex()); if (txOutputs == null) { continue; } //判断这笔交易输入对应的上一笔交易输出集合中消费掉的是哪些交易输出 for (int outIndex = 0; outIndex < txOutputs.length; outIndex++) { System.out.println("3333:"+outIndex); if (outIndex != txInput.getTxOutputIndex()) { //记录下未被消费的交易输出 remainderUTXOs = ArrayUtils.add(remainderUTXOs, txOutputs[outIndex]); } } // 这笔交易输出对应的上一笔的所有交易输出集合若是没有剩余则从内存中删除,否则从内存中更新 if (remainderUTXOs.length == 0) { System.out.println("000000000000000000"); RocksDBUtils.getInstance().deleteUTXOsFromMemory(txId); } else { System.out.println("11111111111111111"); RocksDBUtils.getInstance().putUTXOsInMemory(txId, remainderUTXOs); } } //把交易中新的utxo临时加入到内存缓存utxo池中 String txId = Hex.encodeHexString(transaction.getTxId()); RocksDBUtils.getInstance().putUTXOsInMemory(txId,transaction.getOutputs()); System.out.println("44444:"+transaction.getOutputs().length); for(int i = 0 ; i < transaction.getOutputs().length; i ++){ String addressByPublicHashKey = WalletUtils.getInstance().getAddressByPublicHashKey(transaction.getOutputs()[i].getPubKeyHash()); System.out.println("55555:"+addressByPublicHashKey+"----金额:"+transaction.getOutputs()[i].getValue()+"----输出交易类型:"+transaction.getOutputs()[i].getTxOutputType()); } } }
package dev.bltucker.conway.grid; import dev.bltucker.conway.cells.Cell; import dev.bltucker.conway.cells.State; import junit.framework.Assert; import org.junit.Test; public class GameGridTest { @Test public void gridInitializationTest(){ GameGrid grid = new GameGrid(100,100); boolean initialized = grid.getWidth() == 100 && grid.getHeight() == 100; Assert.assertTrue(initialized); } @Test public void addCellToGrid(){ GameGrid grid = new GameGrid(100, 100); grid.createCell(1, 3); Cell cell = grid.getCell(1, 3); Assert.assertTrue(cell.getState().equals(State.LIVE)); Assert.assertEquals(0, cell.getLiveNeighborCount()); } @Test public void addCellsNextToEachOther(){ GameGrid grid = new GameGrid(10,10); grid.createCell(3, 2); grid.createCell(3, 3); grid.createCell(3, 4); Assert.assertTrue(true); Assert.assertEquals(1, grid.getCell(3,2).getLiveNeighborCount()); Assert.assertEquals(2, grid.getCell(3, 3).getLiveNeighborCount()); Assert.assertEquals(1, grid.getCell(3, 4).getLiveNeighborCount()); } @Test(expected = IllegalArgumentException.class) public void addCellOutsideOfGridRows(){ GameGrid grid = new GameGrid(100,100); Cell cell = new Cell(); grid.createCell(101, 0); } @Test(expected = IllegalArgumentException.class) public void addCellOutsideOfGridColumns(){ GameGrid grid = new GameGrid(100,100); Cell cell = new Cell(); grid.createCell(0, 101); } @Test public void killCell(){ GameGrid grid = new GameGrid(10,10); grid.createCell(1, 1); Cell cell = grid.getCell(1, 1); Assert.assertEquals(State.LIVE, cell.getState()); grid.killCell(1, 1); Assert.assertEquals(State.DEAD, cell.getState()); } }
package pl.basistam.service; import javax.jws.WebMethod; import javax.jws.WebService; import java.time.LocalDate; import java.time.Month; @WebService public class Holidays { public Holidays() { } @WebMethod public int getDaysLastToHolidays() { LocalDate currentDate = LocalDate.now(); LocalDate holidayStart = LocalDate.of(getYearOfNextHolidays(), 7, 1); return holidayStart.getDayOfYear() - currentDate.getDayOfYear(); } private int getYearOfNextHolidays() { LocalDate currentDate = LocalDate.now(); return (currentDate.getMonthValue() > Month.JULY.getValue() || currentDate.getMonthValue() == Month.JULY.getValue() && currentDate.getDayOfMonth() > 1) ? currentDate.getYear() + 1 : currentDate.getYear(); } }
package ru.spbau.bocharov.concurrency; import java.util.function.Supplier; public interface ThreadPool { <T> LightFuture<T> add(Supplier<T> task); void shutdown() throws InterruptedException; }
import java.util.Random; public class Pet { private int age = generateDefaultAge(); private Color color; private Shelter shelter; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Color getColor() { return color; } public void setColor(Color color) { this.color = color; } public Shelter getShelter() { return shelter; } public void setShelter(Shelter shelter) { this.shelter=shelter; } private int generateDefaultAge(){ Random random=new Random(1); int a=random.nextInt(10); return a; }public String getInfo(){ return getAge()+getShelter().getName(); } }
package com.wangcheng.thread; /** * description: * * @author WangCheng * create in 2019/3/5 10:34 */ public class VolatileTest { private volatile int[] arr; public static void main(String[] args) { String[] strArr; } }
package com.bofsoft.sdk.widget.browser; import android.content.Context; import android.graphics.Bitmap; import android.webkit.WebView; import java.util.HashMap; import java.util.Map; public class NSUrlInterface { /** * 调用前缀 */ private static String headStr = "call:"; private Context con; public NSUrlInterface(Context con) { this.con = con; } public Context getContext() { return this.con; } public boolean onLoadding(WebView view, String url) { if (isInnerInterface(url)) { String method = getMethod(url); if (method.equals("toast")) toast(url); else if (method.equals("setTitle")) setTitle(url); return true; } return false; } public void onStarted(WebView view, String url, Bitmap favicon) { } public void onFilished(WebView view, String url) { } /** * 是否内部接口 Call:method?param1=xx&param2=xx * * @param url * @return */ public boolean isInnerInterface(String url) { if (url == null) return false; return url.startsWith(headStr); } /** * 获取调用方法 * * @param url * @return */ public String getMethod(String url) { String method = url.substring(headStr.length()); if (method.indexOf("?") == -1) return method; return method.substring(0, method.indexOf("?")); } /** * 获取参数 * * @param url * @return */ public Map<String, Object> getParam(String url) { Map<String, Object> param = new HashMap<String, Object>(); if (url.indexOf("?") == -1 || url.endsWith("?")) return param; String ps = url.substring(url.indexOf("?") + 1, url.length()); String[] pss = ps.split("&"); for (String p : pss) { String[] params = p.split("="); param.put(params[0], params[1]); } return param; } /** * Toast * * @param text */ public void toast(String url) { Map<String, Object> param = getParam(url); NSInterface.getInstence().toast(con, (String) param.get("text")); } /** * 设置标题 * * @param title */ public void setTitle(String url) { Map<String, Object> param = getParam(url); NSInterface.getInstence().setTitle(con, (String) param.get("title")); } }
package ca.brocku.cosc3p97.bigbuzzerquiz.models; public class Timer implements Runnable { long sleepTime; TimeoutListener listener; public Timer(long sleepTime, TimeoutListener listener) { this.sleepTime = sleepTime; this.listener = listener; } @Override public void run() { try { Thread.currentThread(); Thread.sleep(sleepTime); listener.onTimeout(); } catch (InterruptedException e) { e.printStackTrace(); } } }
package com.xantrix.webapp.service; import com.xantrix.webapp.entities.Utenti; public interface UtentiService { Utenti SelByIdFidelity(String idFidelity); void Salva(Utenti utente); void Aggiorna(Utenti utente); void Elimina(Utenti utente); }
/** * */ package coucheControler; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; /** * @author Mamadou bobo * */ public final class ConnexionBD { private static Connection connection ; static { try { Class.forName("com.mysql.jdbc.Driver"); connection = DriverManager.getConnection ("jdbc:mysql://localhost:3306/school_project1.0", "root", "Barry"); System.out.println("Hello World !!! la Connextion est etablie !!!"); // Statement stat = connection.createStatement(); //ResultSet result = stat.executeQuery("select *from Categorie"); //System.out.println("\n---------Manipulaption de la tables Categorie ---------\n"); /* while(result.next()) { System.out.println("Le num categorie : "+result.getString("ID_Categorie") +" Le nom Categorie : " + result.getString("Nom_Categorie")); } */ } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static Connection getConnection() { return connection; } public static void setConnection(Connection connection) { ConnexionBD.connection = connection; } /*private Connection con; private static Connection connect; private void ConnexionBD() { String url=null; try { Class.forName("com.mysql.jdbc.Drive"); System.out.println("Chargement du Driver ok"); }catch (Exception e) { System.out.println(e.toString()); } url="jdbc:mysql://localhost:3306/school_project"; try { connect=DriverManager.getConnection(url , "root" , "Barry"); System.out.println("Connexion bdd ok!!"); }catch(SQLException ex) { System.out.println(ex.toString()); } } public Connection getcon() { return con; } public static Connection getConnexion() { if(connect==null) { new ConnexionBD(); System.out.println("Connexion bdd ok!!"); } return connect; }*/ }
package com.sshfortress.common.base; import java.util.List; import java.util.Map; public interface BaseMapper<K, T> { /*根据参数查询单表的分页 */ public List<T> queryByParamsListPager(Map<String,Object> map); /*根据参数查询单表的全部 */ public List<T> list(T paramT); /*根据主键删除单表的数据 */ int deleteByPrimaryKey(K paramLong); /*添加表数据*/ int insert(T t); int insertSelective(T t); T selectByPrimaryKey(K k); /*更新数据通过主键*/ int updateByPrimaryKeySelective(T t); int updateByPrimaryKey(T t); }
package com.weiziplus.springboot.common.models; import lombok.Data; /** * @author wanglongwei * @data 2019/5/13 15:04 */ @Data public class SysLog { private Long id; private Long userId; private String description; private String createTime; }
package com.pointinside.android.api.location; import android.content.Context; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; public class CompassEngine implements SensorEventListener { private boolean mCompassEnabled; private CompassEngineListener mListener; private SensorManager mSensorManager; public CompassEngine(Context paramContext) { this.mSensorManager = ((SensorManager)paramContext.getSystemService("sensor")); } public void disableCompass() { this.mSensorManager.unregisterListener(this); this.mCompassEnabled = false; } public boolean enableCompass() { if (!this.mCompassEnabled) { Sensor localSensor = this.mSensorManager.getDefaultSensor(3); if (localSensor != null) { this.mSensorManager.registerListener(this, localSensor, 2); this.mCompassEnabled = true; } } return this.mCompassEnabled; } public boolean isCompassEnabled() { return this.mCompassEnabled; } public final void onAccuracyChanged(Sensor paramSensor, int paramInt) {} public final void onSensorChanged(SensorEvent paramSensorEvent) { if (this.mListener != null) { this.mListener.onCompassChanged(paramSensorEvent.values[0]); } } public void setCompassListener(CompassEngineListener paramCompassEngineListener) { this.mListener = paramCompassEngineListener; } public static abstract interface CompassEngineListener { public abstract void onCompassChanged(float paramFloat); } } /* Location: D:\xinghai\dex2jar\classes-dex2jar.jar * Qualified Name: com.pointinside.android.api.location.CompassEngine * JD-Core Version: 0.7.0.1 */
import java.awt.BorderLayout; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JTextField; import java.awt.Color; import javax.swing.JButton; import java.awt.event.ActionListener; import java.io.RandomAccessFile; import java.lang.invoke.SwitchPoint; import java.util.ArrayList; import java.util.List; import java.util.Scanner; import java.awt.event.ActionEvent; public class InterfazInicial extends JFrame { private static Scanner scs; private List<Entidad> listaEntidades = new ArrayList<>(); RandomAccessFile fichero = null, entidades = null, atributos = null; private void mostrarEntidad(Entidad entidad) { System.out.println("Indice: " + entidad.getIndice()); System.out.println("Nombre: " + entidad.getNombre()); System.out.println("Cantidad de atributos: " + entidad.getCantidad()); System.out.println("Atributos:"); int i = 1; for (Atributo atributo : entidad.getAtributos()) { System.out.println("\tNo. " + i); System.out.println("\tNombre: " + atributo.getNombre()); System.out.println("\tTipo de dato: " + atributo.getNombreTipoDato()); if (atributo.isRequiereLongitud()) { System.out.println("\tLongitud: " + atributo.getLongitud()); } i++; } } /** * */ private static final long serialVersionUID = 1L; private JPanel contentPane; private static Scanner sc; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { InterfazInicial frame = new InterfazInicial(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public InterfazInicial() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 278, 187); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JLabel lblNewLabel = new JLabel(" B I E N V E N I D O "); lblNewLabel.setForeground(Color.RED); lblNewLabel.setBounds(10, 11, 296, 22); contentPane.add(lblNewLabel); JButton btnNewButton = new JButton("AGREGAR NUEVA ENTIDAD"); btnNewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String datos = JOptionPane.showInputDialog(null, "¡Hola, Bienvenido al programa!" + "Ingrese su selección, por favor" + " " + " \n1..... Crear nueva entidad " + "\n2..... agregar registros " + "\n3..... modificar registros" + "\n4..... eliminar registros " + "\n0..... Salir"); int opcion; switch(opcion = 1) { case 1: agregarEntidad(); break; case 2: JOptionPane.showInputDialog(null, "Ingrese la entidad a la que desea agregar registros "); break; case 3: JOptionPane.showInputDialog(null, "Ingrese la entidad a modificar "); break; case 4: JOptionPane.showInputDialog(null, "Entidad a eliminar"); break; case 0: if (opcion == 0) { JOptionPane.showMessageDialog(null, "Gracias por usar nuestra aplicación, que le vaya bien"); } break; } } private boolean agregarEntidad() { boolean resultado = false; try { Entidad entidad = new Entidad(); entidad.setIndice(listaEntidades.size() + 1); JOptionPane.showInputDialog("Ingrese el nombre de la entidad"); String strNombre = ""; int longitud = 0; do { strNombre = sc.nextLine(); longitud = strNombre.length(); if (longitud < 2 || longitud > 30) { System.out.println("La longitud del nombre no es valida [3 - 30]"); } else { if (strNombre.contains(" ")) { System.out .println("El nombre no puede contener espacios, sustituya por guion bajo (underscore)"); longitud = 0; } } } while (longitud < 2 || longitud > 30); entidad.setNombre(strNombre); System.out.println("Atributos de la entidad"); int bndDetener = 0; do { Atributo atributo = new Atributo(); atributo.setIndice(entidad.getIndice()); longitud = 0; System.out.println("Escriba el nombre del atributo no. " + (entidad.getCantidad() + 1)); do { strNombre = sc.nextLine(); longitud = strNombre.length(); if (longitud < 2 || longitud > 30) { System.out.println("La longitud del nombre no es valida [3 - 30]"); } else { if (strNombre.contains(" ")) { System.out.println( "El nombre no puede contener espacios, sustituya por guion bajo (underscore)"); longitud = 0; } } } while (longitud < 2 || longitud > 30); atributo.setNombre(strNombre); System.out.println("Seleccione el tipo de dato"); JOptionPane.showInputDialog(TipoDato.INT.getValue() + " .......... " + TipoDato.INT.name()); JOptionPane.showInputDialog(TipoDato.LONG.getValue() + " .......... " + TipoDato.LONG.name()); JOptionPane.showInputDialog(TipoDato.STRING.getValue() + " .......... " + TipoDato.STRING.name()); JOptionPane.showInputDialog(TipoDato.DOUBLE.getValue() + " .......... " + TipoDato.DOUBLE.name()); JOptionPane.showInputDialog(TipoDato.FLOAT.getValue() + " .......... " + TipoDato.FLOAT.name()); JOptionPane.showInputDialog(TipoDato.DATE.getValue() + " .......... " + TipoDato.DATE.name()); JOptionPane.showInputDialog(TipoDato.CHAR.getValue() + " .......... " + TipoDato.CHAR.name()); atributo.setValorTipoDato(sc.nextInt()); if (atributo.isRequiereLongitud()) { System.out.println("Ingrese la longitud"); atributo.setLongitud(sc.nextInt()); } else { atributo.setLongitud(0); } atributo.setNombreTipoDato(); entidad.setAtributo(atributo); System.out.println("Desea agregar otro atributo presione cualquier numero, de lo contrario 0"); bndDetener = sc.nextInt(); } while (bndDetener != 0); System.out.println("Los datos a registrar son: "); mostrarEntidad(entidad); System.out.println("Presione 1 para guardar 0 para cancelar"); longitud = sc.nextInt(); if (longitud == 1) { // primero guardar atributos // establecer la posicion inicial donde se va a guardar entidad.setPosicion(atributos.length()); atributos.seek(atributos.length());// calcular la longitud el archivo for (Atributo atributo : entidad.getAtributos()) { atributos.writeInt(atributo.getIndice()); atributos.write(atributo.getBytesNombre()); atributos.writeInt(atributo.getValorTipoDato()); atributos.writeInt(atributo.getLongitud()); atributos.write("\n".getBytes()); // cambio de linea para que el siguiente registro se agregue abajo } // guardar la entidad entidades.writeInt(entidad.getIndice()); entidades.write(entidad.getBytesNombre()); entidades.writeInt(entidad.getCantidad()); entidades.writeInt(entidad.getBytes()); entidades.writeLong(entidad.getPosicion()); entidades.write("\n".getBytes()); // cambio de linea para que el siguiente registro se agregue abajo listaEntidades.add(entidad); resultado = true; } else { System.out.println("No se guardo la entidad debido a que el usuario decidio cancelarlo"); resultado = false; } // https://www.experts-exchange.com/questions/22988755/Some-system-pause-equivalent-in-java.html System.out.println("Presione una tecla para continuar..."); System.in.read(); } catch (Exception e) { resultado = false; e.printStackTrace(); } return resultado; } }); btnNewButton.setForeground(Color.BLUE); btnNewButton.setBounds(10, 51, 197, 22); contentPane.add(btnNewButton); JButton btnNewButton_1 = new JButton("AGREGAR REGISTROS"); btnNewButton_1.setForeground(Color.BLUE); btnNewButton_1.setBounds(10, 98, 174, 23); contentPane.add(btnNewButton_1); } }
package com.git.cloud.reports.service; import com.git.cloud.common.support.Pagination; import com.git.cloud.common.support.PaginationParam; import com.git.cloud.reports.model.po.CreateReportParamPo; public interface IReportService { //public String save(CreateReportParamPo crpo); public CreateReportParamPo showReport(String id); public Pagination<CreateReportParamPo> getReportPagination( PaginationParam paginationParam); public void deleteReportList(String id); public CreateReportParamPo selectReport(String id); public CreateReportParamPo selectReportByName(String reportName); public String save(String[] params, String type, String reportId); }
package Demo; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Properties; /** * Created by dell on 2016-12-22. * 读取 配置文件 db.properties */ @WebServlet(name = "ServletPropertiesDemo",urlPatterns = "/ServletPropertiesDemo") public class ServletPropertiesDemo extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { demo1(); } catch (Exception e) { e.printStackTrace(); } } /** 方式1 */ private void demo1() throws Exception{ // 用 ServletContext 读取资源文件 //InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties "); InputStream in = this.getServletContext().getResourceAsStream("/web/db.properties "); Properties prop = new Properties(); prop.load(in); String url = prop.getProperty("url"); String user = prop.getProperty("user"); String password = prop.getProperty("password"); System.out.println(url); } /** 方式2 */ private void demo2() throws Exception{ String path = this.getServletContext().getRealPath("/web/db.properties"); FileInputStream in = new FileInputStream(path); Properties prop = new Properties(); prop.load(in); String url = prop.getProperty("url"); String user = prop.getProperty("user"); String password = prop.getProperty("password"); System.out.println(url); } }
package com.rallytac.engageandroid.legba.fragment; import android.annotation.SuppressLint; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.content.res.Configuration; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AlertDialog; import androidx.core.content.FileProvider; import androidx.databinding.DataBindingUtil; import androidx.fragment.app.Fragment; import androidx.lifecycle.ViewModelProvider; import androidx.navigation.fragment.NavHostFragment; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.LinearLayoutManager; import com.rallytac.engage.engine.Engine; import com.rallytac.engageandroid.DatabaseGroup; import com.rallytac.engageandroid.DatabaseMission; import com.rallytac.engageandroid.EngageApplication; import com.rallytac.engageandroid.R; import com.rallytac.engageandroid.ShareHelper; import com.rallytac.engageandroid.ShareableData; import com.rallytac.engageandroid.Utils; import com.rallytac.engageandroid.databinding.FragmentMissionsListBinding; import com.rallytac.engageandroid.legba.HostActivity; import com.rallytac.engageandroid.legba.data.DataManager; import com.rallytac.engageandroid.legba.data.dto.Mission; import com.rallytac.engageandroid.legba.util.MappingUtils; import com.rallytac.engageandroid.legba.viewmodel.MissionsListViewModel; import com.rallytac.engageandroid.legba.viewmodel.ViewModelFactory; import org.jetbrains.annotations.NotNull; import org.json.JSONArray; import org.json.JSONObject; import java.io.File; import java.io.FileOutputStream; import java.util.List; import java.util.Objects; import timber.log.Timber; public class MissionsListFragment extends Fragment { private FragmentMissionsListBinding binding; private MissionsListViewModel vm; private final int PICK_MISSION_FILE_REQUEST_CODE = 44; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); ViewModelFactory vmFactory = new ViewModelFactory((EngageApplication) getActivity().getApplication()); vm = new ViewModelProvider(this, vmFactory).get(MissionsListViewModel.class); } @Override public View onCreateView(@NotNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { binding = DataBindingUtil.inflate(inflater, R.layout.fragment_missions_list, container, false); setupToolbar(); DataManager.getInstance().leaveMissionActiveMission(); binding.missionsListRecyclerView.setHasFixedSize(true); int orientation = getResources().getConfiguration().orientation; if (orientation == Configuration.ORIENTATION_PORTRAIT) { binding.missionsListRecyclerView.setLayoutManager(new LinearLayoutManager(getContext())); } else if (orientation == Configuration.ORIENTATION_LANDSCAPE) { binding.missionsListRecyclerView.setLayoutManager(new GridLayoutManager(getContext(), 2)); } return binding.getRoot(); } private void setupToolbar() { setHasOptionsMenu(true); requireActivity().findViewById(R.id.toolbar_title_text).setVisibility(View.VISIBLE); ((TextView) requireActivity().findViewById(R.id.toolbar_title_text)).setText(getString(R.string.nav_drawer_my_missions)); HostActivity hostActivity = (HostActivity) requireActivity(); ActionBar actionBar = hostActivity.getSupportActionBar(); Objects.requireNonNull(actionBar).setHomeAsUpIndicator(R.drawable.ic_hamburguer_icon); } @Override public void onStart() { super.onStart(); List<Mission> missions = vm.getMissions(); missions.forEach(mission -> Timber.i("Missions -> %s channelsGrooups -> %s", mission.getId(), mission.getChannelsGroups())); MissionsRecyclerViewAdapter adapter = new MissionsRecyclerViewAdapter(new MissionsRecyclerViewAdapter.AdapterDiffCallback(), this, vm); binding.missionsListRecyclerView.setAdapter(adapter); adapter.setMissions(missions); } @Override public void onResume() { super.onResume(); if(getActivity() != null){//Locks portrait mode getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } } @Override public void onPause() { super.onPause(); if(getActivity() != null){ //Unlocks rotation getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR); } } @Override public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.missions_list_fragment_menu, menu); } @SuppressLint("NonConstantResourceId") @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { int itemId = item.getItemId(); switch (itemId) { case R.id.create_manually_action: NavHostFragment.findNavController(this) .navigate(MissionsListFragmentDirections.actionMissionsFragmentToMissionEditActivity(null)); return true; case R.id.load_from_json_action: startLoadMissionFromLocalFile(); return true; case R.id.export_to_json_action: showExportToJsonDialogDialog(); return true; } return super.onOptionsItemSelected(item); } private void startLoadMissionFromLocalFile() { try { Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("*/*"); intent.addCategory(Intent.CATEGORY_OPENABLE); startActivityForResult(Intent.createChooser(intent, getString(R.string.select_a_file)), PICK_MISSION_FILE_REQUEST_CODE); } catch (Exception e) { e.printStackTrace(); } } @Override public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { Timber.i("OnActivityResult"); if (data != null && requestCode == PICK_MISSION_FILE_REQUEST_CODE) { Uri fileUri = data.getData(); vm.saveNewMission(fileUri, getContext()); //Missions list will refresh automatically on the next lifecycle callback (onCreate) } } private String selectedMissionName = ""; private void showExportToJsonDialogDialog() { String[] missionNames = vm.getMissions() .stream() .map(Mission::getName) .toArray(String[]::new); int checkedItem = 0; selectedMissionName = missionNames[checkedItem]; new AlertDialog.Builder(getActivity()) .setTitle("Choose a mission to export") .setSingleChoiceItems(missionNames, checkedItem, (dialogInterface, i) -> { selectedMissionName = missionNames[i]; }) .setPositiveButton("Share", (dialog, id) -> { //I'm asuming that mission names are unique vm.getMissions() .stream() .filter(mission -> mission.getName().equals(selectedMissionName)) .findFirst() .ifPresent(this::shareMission); dialog.dismiss(); }) .setNegativeButton(R.string.cancel, (dialog, id) -> dialog.dismiss()) .show(); } public void shareMission(Mission mission) { try { String extraText; ShareableData data = new ShareableData(); extraText = String.format(getString(R.string.fmt_load_this_json_file_to_join_the_mission), mission.getName()); String newName = mission.getName().replace(" ", "-"); String fileName = String.format("mission-%s", newName); File fd = File.createTempFile(fileName, ".json", Environment.getExternalStorageDirectory());//NON-NLS FileOutputStream fos = new FileOutputStream(fd); fos.write(MappingUtils.makeTemplate(mission).getBytes()); fos.close(); Uri u = FileProvider.getUriForFile(getContext(), getString(R.string.file_content_provider), fd); fd.deleteOnExit(); data.addUri(u); data.setText(String.format(getString(R.string.share_mission_email_subject), getString(R.string.app_name), mission.getName())); data.setHtml(extraText); data.setSubject(getString(R.string.app_name) + " : " + mission.getName()); Intent intent = ShareHelper.buildShareIntent(getActivity(), data, getString(R.string.share_mission_upload_header)); List<ResolveInfo> resInfoList = this.getActivity().getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY); for (ResolveInfo resolveInfo : resInfoList) { String packageName = resolveInfo.activityInfo.packageName; this.getActivity().grantUriPermission(packageName, u, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION); } startActivity(intent); } catch (Exception e) { e.printStackTrace(); Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show(); } } }
package com.superhero.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.superhero.model.SuperHero; @Repository public interface HeroRepository extends JpaRepository<SuperHero, Long> { }
package com.artauction.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.artauction.domain.GoodsVO; import com.artauction.domain.ImageVO; import com.artauction.domain.UserVO; import com.artauction.mapper.DealMapper; import com.artauction.mapper.RegisterMapper; import lombok.AllArgsConstructor; import lombok.Setter; @AllArgsConstructor @Service public class DealServiceImpl implements DealService { @Setter(onMethod_ = @Autowired) private DealMapper mapper; @Override public GoodsVO findByGno(int gno) { return mapper.findByGno(gno); } @Override public String getStartTime(int gno) { return mapper.getStartTime(gno); } @Override public String getEndTime(int gno) { return mapper.getEndTime(gno); } @Override public int getBiddingCount(int gno) { return mapper.getBiddingCount(gno); } @Override public UserVO getSalerInfo(int gno) { return mapper.getSalerInfo(gno); } @Override public UserVO getBuyerInfo(int gno) { return mapper.getBuyerInfo(gno); } @Override public ImageVO findThumbImageByGno(int gno) { return mapper.findThumbImageByGno(gno); } @Override public List<ImageVO> findImageByGno(int gno) { return mapper.findImageByGno(gno); } @Override public int cntImg(int gno) { return mapper.cntImg(gno); } @Override public void updateFlag(GoodsVO gVo) { mapper.updateFlag(gVo); } }
package com.jaureguialzo.turnoclase; import androidx.test.espresso.ViewInteraction; import androidx.test.ext.junit.runners.AndroidJUnit4; import androidx.test.filters.LargeTest; import androidx.test.rule.ActivityTestRule; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import tools.fastlane.screengrab.FalconScreenshotStrategy; import tools.fastlane.screengrab.Screengrab; import tools.fastlane.screengrab.UiAutomatorScreenshotStrategy; import tools.fastlane.screengrab.cleanstatusbar.CleanStatusBar; import tools.fastlane.screengrab.locale.LocaleTestRule; import static androidx.test.espresso.Espresso.onView; import static androidx.test.espresso.action.ViewActions.click; import static androidx.test.espresso.assertion.ViewAssertions.matches; import static androidx.test.espresso.matcher.ViewMatchers.isDisplayed; import static androidx.test.espresso.matcher.ViewMatchers.withId; import static androidx.test.espresso.matcher.ViewMatchers.withText; import static org.hamcrest.Matchers.allOf; @LargeTest @RunWith(AndroidJUnit4.class) public class MainActivityTest { @Rule public ActivityTestRule<MainActivity> mActivityTestRule = new ActivityTestRule<>(MainActivity.class); @ClassRule public static final LocaleTestRule localeTestRule = new LocaleTestRule(); @Test public void mainActivityTest() { CleanStatusBar.enableWithDefaults(); Screengrab.setDefaultScreenshotStrategy(new UiAutomatorScreenshotStrategy()); ViewInteraction editText = onView(allOf(withId(R.id.campoAula), withText("BE131"), isDisplayed())); editText.check(matches(withText("BE131"))); Screengrab.screenshot("01-PantallaLogin"); ViewInteraction appCompatButton = onView(allOf(withId(R.id.botonSiguiente), isDisplayed())); appCompatButton.perform(click()); ViewInteraction textView = onView(allOf(withId(R.id.etiquetaAula), isDisplayed())); textView.check(matches(withText("BE131"))); ViewInteraction botonActualizar = onView(allOf(withId(R.id.botonActualizar), isDisplayed())); botonActualizar.perform(click()); ViewInteraction etiquetaNumero = onView(allOf(withId(R.id.etiquetaMensaje), withText("2"), isDisplayed())); etiquetaNumero.check(matches(withText("2"))); Screengrab.screenshot("02-Faltan2"); botonActualizar.perform(click()); etiquetaNumero = onView(allOf(withId(R.id.etiquetaMensaje), withText("1"), isDisplayed())); etiquetaNumero.check(matches(withText("1"))); Screengrab.screenshot("03-Faltan1"); botonActualizar.perform(click()); Screengrab.screenshot("04-EsTuTurno"); botonActualizar.perform(click()); Screengrab.screenshot("05-Terminado"); CleanStatusBar.disable(); } }
package pro.likada.model; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.annotations.DynamicInsert; import org.hibernate.annotations.DynamicUpdate; import javax.persistence.*; import javax.validation.constraints.NotNull; import java.io.Serializable; import java.util.Date; /** * Created by bumur on 29.01.2017. */ @Entity @DynamicInsert @DynamicUpdate @Table(name="DOCUMENTS") @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) public class Document implements Serializable{ @Id @GeneratedValue(strategy= GenerationType.IDENTITY) private Long id; @NotNull @Column(name = "DOCUMENT_NAME", nullable = false) private String document_name; @Temporal(TemporalType.TIMESTAMP) @Column(name="DATE_CREATED", nullable = false) private Date date_created; @Column(name = "DESCRIPTION") private String description; @Column(name = "DOCUMENT_PATH") private String document_path; @NotNull @Column(name = "DOCUMENT_SIZE", nullable = false) private Long document_size; @NotNull @Column(name = "DOCUMENT_EXTENSION", nullable = false) private String document_extension; @NotNull @Column(name = "PARENT_ID", nullable = false) private Long parent_id; @Column(name = "PARENT_TYPE") private String parent_type; @OneToOne @JoinColumn(name = "CREATOR_USER_ID") private User creator_user_id; @ManyToOne @JoinColumn(name = "DOCUMENT_TYPE_ID") private DocumentType document_type; @Override public String toString() { return "DOCUMENT [id=" + id + ", DOCUMENT_NAME=" + document_name + ", DATE_CREATED=" + date_created + ", DESCRIPTION=" + description+ ", DOCUMENT_PATH=" + document_path+ ", DOCUMENT_SIZE=" + document_size+", DOCUMENT_EXTENSION=" + document_extension+", PARENT_ID="+parent_id+", PARENT_TYPE="+parent_type+", DOCUMENT_TYPE_ID="+document_type; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getDocument_name() { return document_name; } public void setDocument_name(String document_name) { this.document_name = document_name; } public Date getDate_created() { return date_created; } public void setDate_created(Date date_created) { this.date_created = date_created; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getDocument_path() { return document_path; } public void setDocument_path(String document_path) { this.document_path = document_path; } public Long getDocument_size() { return document_size; } public void setDocument_size(Long document_size) { this.document_size = document_size; } public String getDocument_extension() { return document_extension; } public void setDocument_extension(String document_extension) { this.document_extension = document_extension; } public Long getParent_id() { return parent_id; } public void setParent_id(Long parent_id) { this.parent_id = parent_id; } public String getParent_type() { return parent_type; } public void setParent_type(String parent_type) { this.parent_type = parent_type; } public User getCreator_user_id() { return creator_user_id; } public void setCreator_user_id(User creator_user_id) { this.creator_user_id = creator_user_id; } public DocumentType getDocument_type() { return document_type; } public void setDocument_type(DocumentType document_type) { this.document_type = document_type; } }
package com.xwolf.eop.system.controller; import com.alibaba.fastjson.JSONObject; import com.google.code.kaptcha.impl.DefaultKaptcha; import com.xwolf.eop.system.service.IUserService; import com.xwolf.eop.util.HttpUtil; import lombok.extern.slf4j.Slf4j; import org.apache.shiro.SecurityUtils; import org.apache.shiro.subject.Subject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import javax.imageio.ImageIO; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.awt.image.BufferedImage; /** * @author xwolf * @date 2016-12-13 12:40 * @since V1.0.0 */ @Controller @Slf4j public class LoginController { @Autowired private DefaultKaptcha defaultKaptcha; @Autowired private IUserService userService; /** * 用户登录页面 * @return */ @RequestMapping(value = "toLogin",method = RequestMethod.GET) public String toLogin(@RequestHeader("User-Agent")String ua,HttpServletRequest request){ log.info("userAgent:{},请求IP:{}",ua,HttpUtil.getIP(request)); return "system/login"; } /** * 生成验证码 * * @throws Exception */ @RequestMapping(value = "/checkCode", method = RequestMethod.GET) public void captcha(HttpServletRequest request, HttpServletResponse response) throws Exception { response.setDateHeader("Expires", 0); response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate"); response.addHeader("Cache-Control", "post-check=0, pre-check=0"); response.setHeader("Pragma", "no-cache"); response.setContentType("image/jpeg"); String capText = defaultKaptcha.createText(); // 将验证码放入session中 HttpUtil.setCheckCode(request,capText); log.info("生成的验证码为:{}",capText); BufferedImage bi = defaultKaptcha.createImage(capText); ServletOutputStream out = response.getOutputStream(); ImageIO.write(bi, "jpg", out); try { out.flush(); } finally { out.close(); } } /** * 登录 * @return */ @RequestMapping(value = "login",method = RequestMethod.POST) @ResponseBody public JSONObject login(HttpServletRequest request){ return userService.login(request); } /** * 退出登陆 * @return */ @RequestMapping(value = "logout",method ={RequestMethod.POST,RequestMethod.GET}) public String logout(HttpServletRequest request){ HttpUtil.removeAllSessionAttr(request); Subject subject = SecurityUtils.getSubject(); subject.logout(); return "system/login"; } }
package me.ewriter.chapter12.adapter; /** * Created by Zubin on 2016/11/11. * 会呱呱叫的行为 */ public interface Quackable { public void quack(); }
package semana_4; import java.util.Random; import java.util.Scanner; public class Vector { public static void main(String [] args) { int array_size=5; int vector[] = new int[array_size]; int contador=0; //La clase random para generar los numeros aleatorios Random random=new Random(); while(contador<array_size) { int temp = random.nextInt(100)+1; int i; // comprovamos si ese valor ya existe en el array for (i=0;i<array_size-1;i++) { if (temp==vector[i]) { break; } } // si no se encuentra, lo aņadimos al array if (temp!=vector[i]) { vector[contador++]=temp; } } //ordenamos el vector int aux = 0; boolean bandera = false; do { bandera = false; for (int i = 0;i<vector.length-1;i++) { if(vector[i]>vector[i+1]) { aux = vector[i]; vector[i] = vector[i+1] ; vector[i+1] = aux; bandera = true; } } }while (bandera == true); System.out.println("\n vector ordenado de mayor a menor sin repetidos"); int p = 0; while (p<vector.length) { System.out.println(vector[p]); p++; } System.out.println(""); System.out.println("vector ordenado sin multiplos de 7 sin repetidos"); int k = 0; while (k<vector.length) { for (k = 0;k<vector.length;k++) { if (vector[k]%7 != 0 ) { System.out.println(vector [k]); k++; } } } } }
package amazoninf.ner; import com.fasterxml.jackson.annotation.JsonProperty; public class NerDto { public NerDto() { } String param; String tagsNer; public NerDto(String param) { this.param = param; } @JsonProperty("retorno1") public String getRetorno1() { return "valor retorno 1"; } @JsonProperty("retorno2") public String getRetorno2() { return "valor retorno 2"; } @JsonProperty("tagsNer") public String getRetornoParametro() { return tagsNer; } public final void setTagsNer(String tagsNer) { this.tagsNer = tagsNer; } }
package com.jbico.myspringsecurity.module.dao.hibernate; import org.hibernate.Query; import org.hibernate.Session; import org.springframework.stereotype.Repository; import com.jbico.myspringsecurity.common.domain.User; import com.jbico.myspringsecurity.module.dao.UserDAO; @Repository public class UserDAOHibernateImpl extends GenericDAOHibernate<User, String> implements UserDAO { @Override public User findUserByEmail(String email) { Session session = sessionFactory.getCurrentSession(); String queryStr = "from " + getPersistentClassName() + " as user where user.email = :email"; Query query = session.createQuery(queryStr); query.setString("email", email); return (User) query.uniqueResult(); } @Override public long countByAuthToken(String authToken) { Session session = sessionFactory.getCurrentSession(); String queryStr = "select count(user) from " + getPersistentClassName() + " as user where :authToken in elements(user.tokens)"; Query query = session.createQuery(queryStr); query.setString("authToken", authToken); return (Long) query.uniqueResult(); } }
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.apache.log4j.Logger; /** * Created by shukad on 09/12/15. */ public class InvoiceConnector { private static Logger logger = Logger.getLogger(InvoiceConnector.class); static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; static final String DB_NAME = "payment_b2b_production"; //static final String DB_NAME = "apl_invoice_register_fki_prod"; static final String USER = "inv_reg_rw"; static final String PASS = "AEkPbi36"; static List<String> hosts = new LinkedList<String>(){{ add("10.85.118.24"); add("10.85.133.91"); //add("127.0.0.1"); } }; private static int accessCount = 0; private Connection connection; private Transformer transformer = new Transformer(); public InvoiceConnector(){ initializeConnection(); } public Transformer getTransformer(){ return this.transformer; } public void initializeConnection() { try { int no = accessCount % hosts.size(); accessCount++; String dbUrl = "jdbc:mysql://" + hosts.get(no) + "/" + DB_NAME; Class.forName(JDBC_DRIVER); connection = DriverManager.getConnection(dbUrl, USER, PASS); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } public void shutdown() { if(connection != null){ try { connection.close(); } catch (SQLException e) { logger.error("Error: " + e.getMessage()); } } } public List<HashMap> getInvoices(String ids){ List<HashMap> results = new LinkedList<HashMap>(); ResultSet rs = null; try { String query = "select * from core_invoices where id in (" + ids + ")"; logger.info(query); Statement statement = connection.createStatement(); statement.execute(query); rs = statement.getResultSet(); ResultSetMetaData md = rs.getMetaData(); int columns = md.getColumnCount(); while (rs.next()) { HashMap row = new HashMap(); for (int i = 1; i <= columns; ++i) { if(rs.getObject(i) != null){ String columnName = md.getColumnName(i); if(transformer.needTransformation(columnName)){ Map result = transformer.transform(columnName, rs.getObject(i)); row.put(columnName, result.get(columnName)); }else{ row.put(columnName, rs.getObject(i)); } } } row.remove("partition_key"); results.add(row); } }catch (SQLException se){ logger.error("Error: " + se.getMessage()); } finally { if (rs != null) { try { rs.close(); } catch (SQLException e) { logger.error("Error: " + e.getMessage()); } } } return results; } public HashMap<String, List> getInvoiceItems(String ids){ HashMap<String, List> results = new HashMap<String, List>(); ResultSet rs = null; try { String query = "select * from core_invoice_items where core_invoice_id in (" + ids + ") and linked_core_invoice_item_id is null"; logger.info(query); Statement statement = connection.createStatement(); statement.execute(query); rs = statement.getResultSet(); ResultSetMetaData md = rs.getMetaData(); int columns = md.getColumnCount(); while (rs.next()) { HashMap row = new HashMap(); List<HashMap> valueList = null; String parentId = rs.getString("core_invoice_id"); for (int i = 1; i <= columns; ++i) { if(rs.getObject(i) != null && !transformer.needsToIgnore(md.getColumnName(i))) { String columnName = md.getColumnName(i); if (transformer.needTransformation(columnName)) { Map result = transformer.transform(columnName, rs.getObject(i)); row.put(columnName, result.get(columnName)); } else { row.put(columnName, rs.getObject(i)); } } } if(results.containsKey(parentId)){ valueList = results.get(parentId); }else{ valueList = new LinkedList<HashMap>(); } row.remove("invoice_item_attributes"); row.remove("type"); valueList.add(row); results.put(parentId, valueList); } }catch (SQLException se){ logger.error("Error: " + se.getMessage()); } finally { if (rs != null) { try { rs.close(); } catch (SQLException e) { logger.error("Error: " + e.getMessage()); } } } return results; } public HashMap<String, List> getInvoiceSubItems(String ids){ HashMap<String, List> results = new HashMap<String, List>(); ResultSet rs = null; try { String query = "select * from core_invoice_items where core_invoice_id in (" + ids + ") and linked_core_invoice_item_id is not null"; logger.info(query); Statement statement = connection.createStatement(); statement.execute(query); rs = statement.getResultSet(); ResultSetMetaData md = rs.getMetaData(); int columns = md.getColumnCount(); while (rs.next()) { HashMap row = new HashMap(); List<HashMap> valueList = null; String parentId = rs.getString("linked_core_invoice_item_id"); for (int i = 1; i <= columns; ++i) { if(rs.getObject(i) != null && !transformer.needsToIgnore(md.getColumnName(i))) { String columnName = md.getColumnName(i); if (transformer.needTransformation(columnName)) { Map result = transformer.transform(columnName, rs.getObject(i)); row.put(columnName, result.get(columnName)); } else { row.put(columnName, rs.getObject(i)); } } } if(results.containsKey(parentId)){ valueList = results.get(parentId); }else{ valueList = new LinkedList<HashMap>(); } row.remove("type"); valueList.add(row); results.put(parentId, valueList); } }catch (SQLException se){ logger.error("Error: " + se.getMessage()); } finally { if (rs != null) { try { rs.close(); } catch (SQLException e) { logger.error("Error: " + e.getMessage()); } } } return results; } public static void main(String[] args) { while(accessCount < 10) { int no = accessCount % hosts.size(); logger.info(no); accessCount++; } } }
package h08; import java.awt.*; import java.applet.Applet; import java.awt.event.*; public class TextButtons extends Applet { TextField text; Button button; Button buttonR; String s; public void init() { text = new TextField(" ", 40); button = new Button("ok"); button.addActionListener(new ButtonListener()); add(text); add(button); buttonR = new Button("reset"); buttonR.addActionListener(new ResetListener()); add(buttonR); } public void paint(Graphics g) { g.drawString(""+s,20,40); } class ButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) { s = text.getText(); repaint(); } } class ResetListener implements ActionListener { public void actionPerformed(ActionEvent e) { text.setText(""); s = ""; repaint(); } } }
/* * 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 Model; import java.util.List; import javax.swing.table.AbstractTableModel; /** * * @author RIVANKA */ public class TabelModelImigran extends AbstractTableModel { public TabelModelImigran(List<Imigran> listOrder){ this.listImigran=listOrder; } @Override public int getRowCount() { return this.listImigran.size(); } @Override public int getColumnCount() { return 6; } @Override public String getColumnName(int column){ return switch (column) { case 0 -> "kode Paspor"; case 1 -> "nama"; case 2 -> "alamat"; case 3 -> "warga"; case 4 -> "jenis kelamin"; case 5 -> "tanggal Lahir"; default -> null; }; } @Override public Object getValueAt(int rowIndex, int columnIndex) { return switch (columnIndex) { case 0 -> listImigran.get(rowIndex).getKode(); case 1 -> listImigran.get(rowIndex).getNama(); case 2 -> listImigran.get(rowIndex).getAlamat(); case 3 -> listImigran.get(rowIndex).getWarga(); case 4 -> listImigran.get(rowIndex).getJenis_kelamin(); case 5 -> listImigran.get(rowIndex).getTanggal(); default -> null; }; } List<Imigran> listImigran; }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.vootoo.search.function.filter; import org.apache.lucene.queries.function.ValueSource; import org.vootoo.search.ValueSourceCollectorFilterable; /** * match is indexValue & queryValue != 0 */ public class BitCollectorFilterable extends ValueSourceCollectorFilterable { protected final long queryBit; public BitCollectorFilterable(ValueSource valueSource, long queryBit) { super(valueSource); this.queryBit = queryBit; } @Override public String description() { return "bit("+valueSource.description()+"):"+queryBit; } @Override public boolean matches(int doc) { long indexObj = functionValues.longVal(doc); return (indexObj & queryBit) != 0; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; BitCollectorFilterable that = (BitCollectorFilterable) o; if (queryBit != that.queryBit) return false; return true; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (int) (queryBit ^ (queryBit >>> 32)); return result; } }
package com.trump.auction.reactor.mock; import com.google.common.collect.ImmutableList; import com.trump.auction.reactor.api.BidderService; import com.trump.auction.reactor.api.model.Bidder; import org.springframework.stereotype.Service; import java.util.Arrays; import java.util.List; import java.util.Random; import java.util.concurrent.atomic.AtomicInteger; /** * {@link BidderService} 模拟实现 * * @author Owen * @since 2017/12/29 */ @Service public class MockBidderService implements BidderService { private AtomicInteger idGen = new AtomicInteger(10000); @Override public Bidder nextBidder() { return createRobot(); } @Override public Bidder nextBidder(Bidder lastBidder, String auctionNo) { return nextBidder(lastBidder); } @Override public Bidder nextBidder(Bidder lastBidder) { Bidder robot = nextBidder(); if (lastBidder == null) { return robot; } while (robot.equals(lastBidder)) { robot = nextBidder(); } return robot; } private Bidder createRobot() { int index = nextNameIndex(); Bidder robot = new Bidder(); robot.setSubId(String.valueOf(idGen.get() + index)); robot.setUserId("1"); robot.setName(allName().get(index)); robot.setAddrArea(nextArea()); return robot; } // private String nextName() { // int length = 0; // while (length < 2) { // length = new Random().nextInt(6); // } // // String start = "\\u4e00"; //// String end = "\\u9fa5"; // int startIndex = Integer.parseInt(start.substring(2, start.length()), 16); // int endIndex = startIndex + 2000; // // char[] nameArray = new char[length]; // for (int i = 0; i < length; i++) { // nameArray[i] = (char)(new Random().nextInt(endIndex - startIndex) + startIndex); // } // return new String(nameArray); // } private int nextNameIndex() { return new Random().nextInt(allName().size()); } private List<String> allName() { String[] names = new String[] { "半暮未凉", "夏有森光暖无疑", "雨巷", "风清淡雅", "漫天蒲公英", "夜雨飘雪", "白衬杉格子梦", "吾心给谁人", "青烟离歌", "夏日的綠色", "拢一蓑烟雨", "千城墨白", "倾城月光", "ら樱雪之城ペ", "白衣影眠梦", "花の物语", "青竹暖回阳", "冰泪紫茉", "悠然若雪", "眉蹙秋波", "天涯嘯西風", "迷乱花海", "倾城的美丽", "梦落轻寻", "静若繁花", "森林有鹿", "戏骨清风", "暖南绿倾i", "恍如夢境", "星辰美景", "夜梦萧寒", "醉魂愁梦相伴", "七颜初夏", "d调、樱花╰つ", "狂影秋风", "浅夏淡忆", "南薇", "时光恰如年", "耳边情话", "雨润静荷", "樱花﹨葬礼", "随梦而飞", "南蔷北薇", "森里伊人", "醉酒夢紅顏", "路尽隐香处", "森旅迷雾", "梦中旧人", "山涧晴岚", "望断江南岸", "剑舞天涯", "素笺淡墨", "星星滴蓝天", "≮梦之★情缘≯", "绿蕊★紫蓝", "笑颜百景", "清風挽離人", "柚夏", "捂风挽笑", "云末清廊", "森屿友人", "∫逝水无痕∫", "浮生醉清风", "倾城花音", "柚绿时光!", "倾城一笑醉红尘", "羽逸之光", "指名的幸福丶", "神锋暗杀队", "影丿魂战队", "兴城丶神之队", "t丿黔堂丨丶战队", "火速霹雳战队", "興峸丶神之队", "gpr梦幻之队", "魔夜战队", "大彩笔战队", "hd丶侠客队", "丿千年春丶梦之队", "咸鱼大队", "切菜战队", "王丨技术团队", "宠物恋灬梦之队", "燃烧嗜血大队", "☆轩殿战队★", "战魂★卫队", "幻魂丿队", "神话灬丿技术队", "影丿不死战队", "回龙星队", "华野突击小队", "丿无痕灬丨炫队", "完美灬女队", "rp℃战队", "雪儿灬盟队", "菟族丶零番队", "丿巅峰丶支队", "痞子丿敢死队", "vip丨巅峰队灬", "黑骑战队", "死亡★突击队", "may丶_猫队", "边境ご炫队", "s.y 战队", "不许败_战队丶", "秋明战队", "通天★战队", "河南灬国志队", "luck丶星队", "嗤古灬战队", "安安灬红队", "love厦门战队", "巛soso丶全队", "轩辕※团队", "狱队", "深夜丶黑衣队", "灭婊大队", "see丶神队", "幻丿突击队", "媚丨丶战队", "完美的战队", "梦兮ヽ花已落", "抹不掉的依赖", "记忆昰座荒岛", "梦醒、西楼", "删不掉思念", "掺泪情书", "烟消云散", "島是海哭碎菂訫", "续写忧伤", "回忆刺穿心脏╮", "眼角的淚光", "陌上花开迟", "旧城空念", "终于有始无终", "浅夏╭染指忧伤", "眼泪变成水蒸气", "〆泪湿衣襟", "情种多短命ζ", "晚风吻尽", "一个人旳荒岛", "流年丶染花落", "与孤独合葬", "苦涩的回忆", "眼泪里的鱼", "时光淡忘旧人心", "酒醉人心碎", "不可碰触的伤", "花谢忽如雪", "雾一样的忧伤", "浅笶≧掩饰泪光", "閉上眼ゝ說再見", "空城只因旧梦在", "浅场∵离别曲", "孤独陪葬我", "眼泪淋花", "眼泪〥为你流乾", "寡欢惨笑", "默言忆旧", "时光半落空城シ", "眼眸与伤", "欠你的泪滴", "未綄℡↘待續", "残城碎梦", "触不及的温柔", "梦醒梦碎", "残梦凉心", "呼吸都会痛", "想念终究是、想念", "指间滑过的忧伤", "花田流成泪海", "深巷裏的流浪貓" }; return Arrays.asList(names); } private String nextArea() { return allArea().get(new Random().nextInt(allArea().size())); } private List<String> allArea() { return ImmutableList.of("上海上海", "北京北京", "江苏南京", "广东广州", "浙江杭州", "辽宁大连", "四川广安"); } public static void main(String[] args) throws Exception { BidderService service = new MockBidderService(); for (int i = 0; i < 100; i++) { System.out.println(service.nextBidder()); } } }
package com.trump.auction.web.service; /** * Created by songruihuan on 2017/12/21. */ public interface TimeLimitService { }
package pl.globallogic.qaa_academy.oop; import java.util.ArrayList; import java.util.List; public class carPool { private List<Car> carPool; public carPool(){ carPool = new ArrayList<>(); } }
package com.proky.booking.persistence.dao; import com.proky.booking.persistence.entities.Role; import java.util.Optional; public interface IUserTypeDao extends IDao<Role> { Optional<Role> findByType(String type); }
package com.radauer.mathrix; public enum GroupType { VALUE, PERCENTAGE, FLAG; }
package com.bcc.gridmenuview; import android.content.Context; import android.content.res.TypedArray; import android.util.AttributeSet; import android.widget.FrameLayout; import androidx.annotation.Nullable; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.RecyclerView; import java.util.List; public class GridMenu extends FrameLayout { private static final int DEFAULT_SPAN_COUNT = 3; private GridMenuAdapter adapter = new GridMenuAdapter(); private int spanCount; public GridMenu(Context context, @Nullable AttributeSet attrs) { super(context, attrs); setupAttribute(attrs); setupRecyclerView(); } private void setupRecyclerView() { RecyclerView recyclerView = new RecyclerView(getContext()); recyclerView.setLayoutManager(new GridLayoutManager(getContext(), spanCount)); recyclerView.setAdapter(adapter); addView(recyclerView); } public void setMenuItems(List<MenuItem> menuItems) { adapter.setMenuItems(menuItems); } private void setupAttribute(@Nullable AttributeSet attrs) { TypedArray typedArray = getContext().getTheme() .obtainStyledAttributes(attrs, R.styleable.GridMenu, 0, 0); spanCount = typedArray.getInt(R.styleable.GridMenu_spanCount, DEFAULT_SPAN_COUNT); typedArray.recycle(); } public void setOnClickListener(OnItemClickListener listener){ adapter.setOnClickListener(listener); } }
package com.taotao.order.controller; import com.taotao.common.pojo.TaotaoResult; import com.taotao.order.pojo.OrderInfo; import com.taotao.order.service.OrderService; import com.taotao.pojo.TbItem; import com.taotao.pojo.TbUser; import com.taotao.utils.CookieUtils; import com.taotao.utils.JsonUtils; import org.apache.commons.lang3.StringUtils; import org.joda.time.DateTime; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import javax.servlet.http.HttpServletRequest; import java.util.ArrayList; import java.util.List; /** * 订单的Controller */ @Controller public class OrderController { @Value("${CART_KEY}") private String CART_KEY; @Autowired private OrderService orderService; @RequestMapping("/order/order-cart") public String showOrderCart(HttpServletRequest request) { //用户必须是登录状态 //取用户ID TbUser user = (TbUser)request.getAttribute("user"); System.out.println(user.getId()); //根据用户ID取收获地址列表,这里就使用静态数据了 //把收货地址列表取出传递给页面 //从cookie中取购物车商品列表展示到页面 List<TbItem> cartList = getCartItemList(request); request.setAttribute("cartList", cartList); //返回逻辑视图 return "order-cart"; } @RequestMapping(value="/order/create",method= RequestMethod.POST) public String createOrder(OrderInfo orderInfo, Model model,HttpServletRequest request) { // 1、接收表单提交的数据OrderInfo。 // 2、补全用户信息。 TbUser user = (TbUser)request.getAttribute("user"); orderInfo.setUserId(user.getId()); orderInfo.setBuyerNick(user.getUsername()); // 3、调用Service创建订单。 TaotaoResult result = orderService.createOrder(orderInfo); //设置逻辑视图中的内容 model.addAttribute("orderId", result.getData().toString()); model.addAttribute("payment", orderInfo.getPayment()); //得到3天后的日期 DateTime dateTime = new DateTime(); dateTime = dateTime.plusDays(3); model.addAttribute("date", dateTime.toString("yyyy-MM-dd")); //返回逻辑视图 return "success"; } private List<TbItem> getCartItemList(HttpServletRequest request){ //从cookie中取购物车商品列表 String json = CookieUtils.getCookieValue(request, CART_KEY, true);//为了防止乱码,统一下编码格式 if(StringUtils.isBlank(json)){ //说明cookie中没有商品列表,那么就返回一个空的列表 return new ArrayList<TbItem>(); } List<TbItem> list = JsonUtils.jsonToList(json,TbItem.class); return list; } }
package com.soy.seckill.service.impl; import com.soy.seckill.dao.SeckillDao; import com.soy.seckill.dao.SuccessKilledDao; import com.soy.seckill.dao.cache.RedisDao; import com.soy.seckill.dto.Exposer; import com.soy.seckill.dto.SeckillExecution; import com.soy.seckill.entity.Seckill; import com.soy.seckill.entity.SuccessKilled; import com.soy.seckill.enums.StateEnum; import com.soy.seckill.exception.RepeatKillException; import com.soy.seckill.exception.SeckillCloseException; import com.soy.seckill.exception.SeckillException; import com.soy.seckill.service.SeckillService; import org.apache.commons.collections.MapUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.DigestUtils; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by Soy on 2016/12/12. */ @Service public class SeckillServiceImpl implements SeckillService { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired private SeckillDao seckillDao; @Autowired private SuccessKilledDao successKilledDao; @Autowired private RedisDao redisDao; @Override public List<Seckill> getSeckillList() { return seckillDao.queryAll(0,10); } @Override public Seckill getById(int seckillId) { return seckillDao.queryById(seckillId); } // @Override // public Exposer exposerSeckillUrl(int seckillId) { // Seckill seckill = seckillDao.queryById(seckillId); // if (seckill == null){ // return new Exposer(false,seckillId); // } // Date startTime = seckill.getStartTime(); // Date endTime = seckill.getEndTime(); // //系统当前时间 // Date now = new Date(); // //如果在时间范围内 // if (now.after(startTime) && now.before(endTime)){ // String md5 = getMd5(seckillId); // //暴露秒杀地址 // return new Exposer(true, seckillId, md5); // }else{ // return new Exposer(false,now,startTime,endTime); // } // } @Override //优化:使用redis缓存,在超时的基础上维护一致性。 //由于库存做处理,故在此不需要保证库存的一致性。 public Exposer exposerSeckillUrl(int seckillId) { //从缓存中获取 Seckill seckill = redisDao.getSeckill(seckillId); //如果没获取到。 if(seckill==null){ seckill = seckillDao.queryById(seckillId); if(seckill==null){ //如果从数据库获取的为空 return new Exposer(false,seckillId); } //放入redis缓存中 String msg = redisDao.putSeckill(seckill); if(!"OK".equalsIgnoreCase(msg)){ //如果保存到redis不成功 logger.warn("seckillId={},保存到redis失败!!!",seckillId); } } Date startTime = seckill.getStartTime(); Date endTime = seckill.getEndTime(); //系统当前时间 Date now = new Date(); //如果在时间范围内 if (now.after(startTime) && now.before(endTime)){ String md5 = getMd5(seckillId); //暴露秒杀地址 return new Exposer(true, seckillId, md5); }else{ return new Exposer(false,now,startTime,endTime); } } @Override //优化:使用存储过程 public SeckillExecution executeSeckill(int seckillId, String userPhone, String md5) throws RepeatKillException, SeckillCloseException, SeckillException { if(md5==null || !md5.equals(getMd5(seckillId))){ return new SeckillExecution(seckillId,StateEnum.DATA_REWRITE); } Date killTime = new Date(); Map<String,Object> map = new HashMap<>(); map.put("seckillId",seckillId); map.put("killTime",killTime); map.put("userPhone",userPhone); map.put("result",null); try { //执行存储过程 seckillDao.killByProcedure(map); //获取result int result = MapUtils.getIntValue(map,"result",-2); if(result == 1){ SuccessKilled successKilled = successKilledDao.queryByIdWithSeckill(seckillId,userPhone); return new SeckillExecution(seckillId,StateEnum.SUCCESS,successKilled); }else { return new SeckillExecution(seckillId,StateEnum.stateOf(result)); } } catch (Exception e) { logger.error(e.getMessage(),e); return new SeckillExecution(seckillId,StateEnum.INNER_ERROR); } } // @Override // @Transactional // public SeckillExecution executeSeckill(int seckillId, String userPhone, String md5) // throws RepeatKillException, SeckillCloseException, SeckillException { // if(md5==null || md5.equals(getMd5(seckillId))){ // return new SeckillExecution(seckillId,StateEnum.DATA_REWRITE); // } // try { // int count = successKilledDao.insertSuccessKilled(seckillId, userPhone); // //插入成功,表示之前未秒杀 // if(count>0){ // Date now = new Date(); // int number = seckillDao.reduceNumber(seckillId, now); // //如果减库存成功 // if (number>0){ // SuccessKilled successKilled = successKilledDao.queryByIdWithSeckill(seckillId,userPhone); // return new SeckillExecution(seckillId, StateEnum.SUCCESS,successKilled); // }else{ // throw new SeckillCloseException("秒杀结束!"); // } // }else{ // throw new RepeatKillException("重复秒杀!"); // } // } catch (SeckillCloseException | RepeatKillException e) { // throw e; // } catch (Exception e){ // logger.error(e.getMessage(),e); // //所有检查型异常都转化为运行期异常 // throw new SeckillException(e.getMessage(),e); // } // } //MD5的盐 private final String salt = "fwebdlbwea@!#$#%gW$H$%Bw5423f3rh45$%w45h"; private String getMd5(int seckillId){ String base = seckillId + "/" + salt; String md5 = DigestUtils.md5DigestAsHex(base.getBytes()); return md5; } }
package io.jrevolt.sysmon.client.ui; import javafx.application.Application; import javafx.stage.Stage; import io.jrevolt.sysmon.client.ClientConfig; import io.jrevolt.sysmon.client.ClientMain; import io.jrevolt.sysmon.common.Version; import io.jrevolt.sysmon.model.AppCfg; import io.jrevolt.sysmon.model.SpringBootApp; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.ConfigurableApplicationContext; import org.apache.commons.io.FileUtils; import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.Yaml; import java.io.File; import java.io.IOException; import java.nio.file.Paths; import java.time.LocalDate; import java.time.ZoneOffset; import java.util.prefs.Preferences; /** * @author <a href="mailto:patrikbeno@gmail.com">Patrik Beno</a> * @version $Id$ */ public class FxMain extends Application { static private FxMain INSTANCE; static public FxMain instance() { return INSTANCE; } static public Stage stage() { return INSTANCE.stage; } static public void main(String[] args) { Application.launch(FxMain.class, args); } Stage stage; @Autowired ConfigurableApplicationContext ctx; @Autowired AppCfg app; @Autowired ClientConfig client; @Autowired FxHelper helper; { SpringBootApp.instance().autowire(this); } @Override public void start(Stage stage) throws Exception { INSTANCE = this; this.stage = stage; Base base = FxHelper.load(getMainFrameClass()); // Date jvmLaunched = new Date(Long.parseLong(System.getProperty("__jvm_launched"))); // Date appletLaunched = new Date(Long.parseLong(System.getProperty("__applet_launched"))); // Date now = new Date(System.currentTimeMillis()); // // System.out.println("launch time: "+(now.getTime() - jvmLaunched.getTime())); loadStage(); Version version = Version.getVersion(ClientMain.class); stage.setTitle(String.format( "%s (%s, %s)", app.getName(), version.getArtifactVersion(), LocalDate.from(version.getTimestamp().atZone(ZoneOffset.systemDefault())))); base.show(); stage.setOnCloseRequest(event -> { saveStage(); ctx.close(); // System.exit(0); }); } Class<? extends Base> getMainFrameClass() { return ClientFrame.class; } protected void customize() {} public void saveStage() { Preferences prefs = Preferences.userRoot().node(FxMain.class.getName()); prefs.putDouble("stage.x", stage().getX()); prefs.putDouble("stage.y", stage().getY()); prefs.putDouble("stage.width", stage().getWidth()); prefs.putDouble("stage.height", stage().getHeight()); } public void loadStage() { Preferences prefs = Preferences.userRoot().node(FxMain.class.getName()); stage().setX(prefs.getDouble("stage.x", 0)); stage().setY(prefs.getDouble("stage.d", 0)); stage().setWidth(prefs.getDouble("stage.width", 1024)); stage().setHeight(prefs.getDouble("stage.height", 768)); } }
import java.util.*; public class FindYMax { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int x = sc.nextInt(); Find(n, x); } public static void Find(int n, int x){ long factorial = 1; for(int i = 1; i <= n; i++){ factorial *= i; } int y = 0; while(factorial % x == 0){ factorial /= x; y++; } System.out.println(y); } }
package pro.likada.service.serviceImpl; import org.primefaces.model.TreeNode; import org.primefaces.model.chart.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import pro.likada.dao.ProductDAO; import pro.likada.model.Product; import pro.likada.model.ProductGroup; import pro.likada.model.ProductPrice; import pro.likada.service.ProductService; import javax.inject.Inject; import javax.inject.Named; import javax.transaction.Transactional; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.GregorianCalendar; import java.util.List; /** * Created by bumur on 14.02.2017. */ @Named("productService") @Transactional public class ProductServiceImpl implements ProductService { private static final Logger LOGGER = LoggerFactory.getLogger(ProductServiceImpl.class); @Inject private ProductDAO productDAO; private List<Long> groupsIds; @Override public Product findById(long id) { return productDAO.findById(id); } @Override public List<Product> getProductsByGroup(TreeNode selectedProductNode) { if(((ProductGroup)selectedProductNode.getData()).getId().equals(new Long(-1))) { return productDAO.getAllProducts(); } groupsIds = new ArrayList<Long>(); compareChilds(selectedProductNode, groupsIds); return productDAO.getProductsByGroupIds(groupsIds); } @Override public List<Product> getProductsByGroupId(Long groupId) { return productDAO.getProductsByGroupId(groupId); } @Override public void deleteById(Long id) { productDAO.deleteById(id); } @Override public void compareChilds(TreeNode node, List<Long> list) { if (node != null) { ProductGroup group = (ProductGroup) node.getData(); if (group != null) { if (group.getId() != null) { list.add(group.getId()); LOGGER.info(group.toString()); for (int i = 0; i < node.getChildCount(); i++) { TreeNode node_child = node.getChildren().get(i); compareChilds(node_child, list); } } } } } @Override public LineChartModel drawProductLineChart(Product product) { LineChartModel model = new LineChartModel(); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); if (product != null) { LOGGER.info("GENERATE CHART " + product.getId() + " " + product.getNameShort()); model.setShowPointLabels(false); DateAxis axis = new DateAxis(); axis.setTickAngle(-50); axis.setTickFormat("%d.%m.%y"); ChartSeries prices = new ChartSeries(); prices.setLabel(product.getNameShort()); double min = 0; double max = 0; List<ProductPrice> prices_list = product.getProductPricesList(); if (prices_list.size() > 0) { axis.setMax(dateFormat.format(prices_list.get(0).getTimeModified())); GregorianCalendar gc_max = new GregorianCalendar(); gc_max.setTime(prices_list.get(0).getTimeModified()); gc_max.add(GregorianCalendar.MONTH, -1); axis.setMin(dateFormat.format(gc_max.getTime())); } for (int i = 0; i < prices_list.size(); i++) { prices.set(dateFormat.format(prices_list.get(i).getTimeModified()), prices_list.get(i).getPrice()); if (min == 0) { min = prices_list.get(i).getPrice(); } else { if (prices_list.get(i).getPrice() < min) { min = prices_list.get(i).getPrice(); } } if (max == 0) { max = prices_list.get(i).getPrice(); } else { if (prices_list.get(i).getPrice() > max) { max = prices_list.get(i).getPrice(); } } } model.getAxes().put(AxisType.X, axis); Axis yAxis = model.getAxis(AxisType.Y); yAxis.setMin(Math.round(min / 5000) * 5000 - 5000); yAxis.setMax(Math.round(max / 5000) * 5000 + 5000); model.addSeries(prices); } return model; } @Override public void save(Product product) { productDAO.save(product); } @Override public List<Product> getAllProducts() { return productDAO.getAllProducts(); } }
// still working on it package handlers; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import objects.Board; import objects.Player; import objects.Tile; public class DirectionHandler implements ActionListener { private JButton _stay; private JButton _north; private JButton _east; private JButton _south; private JButton _west; private JButton _button; private Board _board; private int _player; private String _direction; public DirectionHandler(String button, JButton north, JButton east, JButton south, JButton west, JButton stay, Board board, int i) { _north = north; _east = east; _south = south; _west = west; _south = south; _stay = stay; _board = board; _player = i; _direction = button; } @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub int[] location = _board.get_player(_player).get_location(); char chup = _board.get_tileAL().get(location[0] - 1).get(location[1]).get_tileShape(); char ch = _board.get_tileAL().get(location[0]).get(location[1]).get_tileShape(); Tile tnorth = _board.get_tileAL().get(location[0]).get(location[1] - 1); Tile tsouth = _board.get_tileAL().get(location[0]).get(location[1] + 1); Tile twest = _board.get_tileAL().get(location[0 - 1]).get(location[1]); Tile teast = _board.get_tileAL().get(location[0] + 1).get(location[1]); Tile t = _board.get_tileAL().get(location[0]).get(location[1]); Player player = _board.get_player(_player); if (_button.getText() == "North") { if (tnorth.setUpOpenedSide(chup).get(2) == true && t.setUpOpenedSide(ch).get(0) == true && location[1] != 0) { _board.get_tileAL().get(location[0]).get(location[1] + 1).set_hasPlayerOnIt(true); _board.get_tileAL().get(location[0]).get(location[1]).set_hasPlayerOnIt(false); } } if (_button.getText() == "South") { if (tsouth.setUpOpenedSide(chup).get(0) == true && t.setUpOpenedSide(ch).get(2) == true && location[1] != 6) { _board.get_tileAL().get(location[0]).get(location[1] - 1).set_hasPlayerOnIt(true); _board.get_tileAL().get(location[0]).get(location[1]).set_hasPlayerOnIt(false); } } if (_button.getText() == "East") { if (teast.setUpOpenedSide(chup).get(3) == true && t.setUpOpenedSide(ch).get(1) == true && location[0] != 6) { _board.get_tileAL().get(location[0] + 1).get(location[1]).set_hasPlayerOnIt(true); _board.get_tileAL().get(location[0]).get(location[1]).set_hasPlayerOnIt(false); } } if (_button.getText() == "West") { if (twest.setUpOpenedSide(chup).get(2) == true && t.setUpOpenedSide(ch).get(0) == true && location[0] != 0) { _board.get_tileAL().get(location[0] - 1).get(location[1]).set_hasPlayerOnIt(true); _board.get_tileAL().get(location[0]).get(location[1]).set_hasPlayerOnIt(false); } } else System.out.println("TRY AGAIN"); } }
package resources; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Properties; import java.util.concurrent.TimeUnit; import org.apache.commons.io.FileUtils; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import com.beust.jcommander.Parameters; public class BaseTest { static int i=0; public static WebDriver driver; public Properties prop; private String timeStamp; public static String destinationfile; public void initializeDriver() throws IOException { prop = new Properties(); FileInputStream fis = new FileInputStream( "C:\\users\\nadh\\E2EProject\\src\\test\\java\\resources\\data.properties"); prop.load(fis); String browsername = prop.getProperty("browser"); if (browsername.equals("chrome")) { driver = new ChromeDriver(); System.setProperty("webdriver.chrome.driver", "D:\\career\\Career softwares\\chrome version 83\\chromedriver_win32\\chromedriver.exe"); System.out.println(browsername); } else if (browsername.equals("firefox")) { System.setProperty("webdriver.gecko.driver", "D:\\career\\Career softwares\\geckodriver-v0.26.0-win64\\geckodriver.exe"); driver = new FirefoxDriver(); System.out.println(browsername); } else if (browsername == "IE") { } String url=prop.getProperty("url"); switch (url) { case "dev": url=prop.getProperty("dev"); break; case "qa": url=prop.getProperty("qa"); break; case "uat": url=prop.getProperty("uat"); break; } driver.get(url); driver.manage().window().maximize(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); } /*public WebDriver getDriver() { return driver; }*/ public String getscreenshot(String classname) throws IOException { //getCurrentTime(); File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); String destinationfile="D:\\screenshot2\\"+classname+"screnshots.png"; FileUtils.copyFile(scrFile, new File(destinationfile)); System.out.println("i took a screenshot and saved in D drive"); System.out.println("and the number is"+ " " +i++ +" "); return destinationfile; } /*public void getCurrentTime(){ Date date=new Date(); // String value=date.toLocaleString(); SimpleDateFormat dateFormat=new SimpleDateFormat("MMddyyyyHH:mm:ss"); timeStamp=dateFormat.format(date); System.out.println(timeStamp); // timeStamp=value; */ }
package home; import java.io.BufferedInputStream; import java.sql.SQLOutput; public class Main { public static void main(String[] args) { System.out.println("dhfjsdhf"); System.out.println("Введите первое число"); double firstNumber = Methods.getNumber(); System.out.println("Введите оперцию"); System.out.println(); char operation = Methods.getOperation(); System.out.println("Введите второе число"); double secondNumber = Methods.getNumber(); double result = Methods.calc(firstNumber, secondNumber, operation); if (result - (int) result == 0) { System.out.println("Ответ " + (int) result); } else { System.out.println("Ответ " + result); } } }
package org.framestudy.spring_mybatis.relationmag.mapper; import java.util.List; import org.apache.ibatis.annotations.Many; import org.apache.ibatis.annotations.Result; import org.apache.ibatis.annotations.ResultType; import org.apache.ibatis.annotations.Results; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.mapping.FetchType; import org.framestudy.spring_mybatis.relationmag.beans.Classes; import org.framestudy.spring_mybatis.relationmag.beans.Students; public interface ClassMapper { @Select("select * from t_class where id = #{id}") @Results({ @Result(id=true,property="id",column="id",javaType=Integer.class), @Result(property="name",column="cla_name",javaType=String.class), @Result(property="stus",javaType=List.class,column="id",many=@Many( fetchType=FetchType.LAZY,select="getStudentByClassId")) }) public Classes getClassesWithStusByClassId(int id); @Select("select id as id, stu_name as name from t_stus where fk_cla_id = #{id}") @ResultType(Students.class) public List<Students> getStudentByClassId(int id); }
package com.lenovohit.elh.pay.model; import javax.persistence.Entity; import javax.persistence.Table; import com.lenovohit.core.model.BaseIdModel; /** * 收费项表 * @author Administrator * */ @Entity @Table(name="ELH_CHARGE") public class Charge extends BaseIdModel {//TODO 不考虑非就医项收费 private static final long serialVersionUID = -6165675026927905337L; private String idHlht; private String name; private Double receiveAmount; private Double realAmount; private String status; private String patient;//TODO 增加字段 private String bizSource; private String bizId;//记录医院端收费项所属的医疗项的id private String treatdetail; private String treatment; private String type; private String pricePer; private String chargePer; private String orderPer; private String comment; private String createTime; private String occurTime; private String regTime; private String payTime; private String orderNo; private String orderId ; public String getIdHlht() { return idHlht; } public void setIdHlht(String idHlht) { this.idHlht = idHlht; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Double getReceiveAmount() { return receiveAmount; } public void setReceiveAmount(Double receiveAmount) { this.receiveAmount = receiveAmount; } public Double getRealAmount() { return realAmount; } public void setRealAmount(Double realAmount) { this.realAmount = realAmount; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getPatient() { return patient; } public void setPatient(String patient) { this.patient = patient; } public String getBizSource() { return bizSource; } public void setBizSource(String bizSource) { this.bizSource = bizSource; } public String getBizId() { return bizId; } public void setBizId(String bizId) { this.bizId = bizId; } public String getTreatdetail() { return treatdetail; } public void setTreatdetail(String treatdetail) { this.treatdetail = treatdetail; } public String getTreatment() { return treatment; } public void setTreatment(String treatment) { this.treatment = treatment; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getPricePer() { return pricePer; } public void setPricePer(String pricePer) { this.pricePer = pricePer; } public String getChargePer() { return chargePer; } public void setChargePer(String chargePer) { this.chargePer = chargePer; } public String getOrderPer() { return orderPer; } public void setOrderPer(String orderPer) { this.orderPer = orderPer; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } public String getCreateTime() { return createTime; } public void setCreateTime(String createTime) { this.createTime = createTime; } public String getOccurTime() { return occurTime; } public void setOccurTime(String occurTime) { this.occurTime = occurTime; } public String getRegTime() { return regTime; } public void setRegTime(String regTime) { this.regTime = regTime; } public String getPayTime() { return payTime; } public void setPayTime(String payTime) { this.payTime = payTime; } public String getOrderNo() { return orderNo; } public void setOrderNo(String orderNo) { this.orderNo = orderNo; } public String getOrderId() { return orderId; } public void setOrderId(String orderId) { this.orderId = orderId; } public static long getSerialversionuid() { return serialVersionUID; } }
package com.entities; import java.io.Serializable; import java.util.List; import javax.persistence.*; /** * Entity implementation class for Entity: Drugstore * */ @Entity public class Drugstore implements Serializable { static EntityManagerFactory ENTITY_MANAGER_FACTORY = Persistence.createEntityManagerFactory("suppliermicroservice-jpa"); private static final long serialVersionUID = 1L; @Id private int id; private String name; private String address; private String phone; private String email; private String uri; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getUri() { return uri; } public void setUri(String uri) { this.uri = uri; } public static long getSerialversionuid() { return serialVersionUID; } public Drugstore() { super(); } public boolean save() { EntityManager em = ENTITY_MANAGER_FACTORY.createEntityManager(); EntityTransaction et = null; boolean succesfulltransaction = false; try { et = em.getTransaction(); et.begin(); Drugstore drugstore = new Drugstore(); drugstore.setName(name); drugstore.setEmail(email); drugstore.setPhone(phone); drugstore.setUri(uri); drugstore.setAddress(address); em.persist(drugstore); et.commit(); succesfulltransaction = true; } catch (Exception e) { if (et != null) { et.rollback(); } } finally { em.close(); } return succesfulltransaction; } public boolean removeDrugstore() { EntityManager em = ENTITY_MANAGER_FACTORY.createEntityManager(); EntityTransaction et = null; boolean succesfulltransaction = false; try { et = em.getTransaction(); et.begin(); Drugstore drugstore = em.find( Drugstore.class , this.id); em.remove(drugstore); et.commit(); succesfulltransaction = true; } catch (Exception e) { if (et != null) { et.rollback(); } } finally { em.close(); } return succesfulltransaction; } public static List<Drugstore> getDrugstores() { EntityManager em = ENTITY_MANAGER_FACTORY.createEntityManager(); String query = "SELECT c FROM Drugstore c WHERE c.id IS NOT NULL"; TypedQuery<Drugstore> tq = em.createQuery(query, Drugstore.class); List<Drugstore> drugstores = null; try { drugstores = tq.getResultList(); drugstores.forEach( Drugstore -> System.out.println("Drugstore") ); } catch (Exception e) { e.printStackTrace(); } finally { em.close(); } return drugstores; } public static Drugstore getDrugstore( int id) { EntityManager em = ENTITY_MANAGER_FACTORY.createEntityManager(); EntityTransaction et = null; Drugstore drugstore = null; try { et = em.getTransaction(); et.begin(); drugstore = em.find( Drugstore.class , id); } catch (Exception e) { e.printStackTrace(); } finally { em.close(); } return drugstore; } }
package kz.greetgo.gbatis.struct.resource; import java.io.InputStream; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ClassResourceRef implements ResourceRef { private final Class<?> aClass; private final String path; private ClassResourceRef(Class<?> aClass, String path) { this.aClass = aClass; this.path = path; } @Override public String toString() { return aClass.getSimpleName() + " : " + path; } public static ResourceRef create(Class<?> aClass, String path) { return new ClassResourceRef(aClass, normalizePath(path)); } private static final Pattern KILL1 = Pattern.compile("//"); private static final Pattern KILL2 = Pattern.compile("/\\./"); private static final Pattern KILL3 = Pattern.compile("/([^/]+)/\\.\\./"); private static final Pattern KILL4 = Pattern.compile("[^/]+/\\.\\./(.*)"); static String normalizePath(String path) { while (true) { boolean changed = false; { Matcher matcher = KILL1.matcher(path); if (matcher.find()) { path = path.substring(0, matcher.start()) + '/' + path.substring(matcher.end()); changed = true; } } { Matcher matcher = KILL2.matcher(path); if (matcher.find()) { path = path.substring(0, matcher.start()) + '/' + path.substring(matcher.end()); changed = true; } } { Matcher matcher = KILL3.matcher(path); if (matcher.find()) { if (!matcher.group(1).equals("..")) { path = path.substring(0, matcher.start()) + '/' + path.substring(matcher.end()); changed = true; } } } { Matcher matcher = KILL4.matcher(path); if (matcher.matches()) { path = matcher.group(1); changed = true; } } if (!changed) return path; } } @Override public InputStream getInputStream() { return aClass.getResourceAsStream(path); } @Override public ResourceRef change(String path) { if (path.startsWith("/")) return create(aClass, path); final int lastSlash = this.path.lastIndexOf('/'); if (lastSlash < 0) return create(aClass, path); return create(aClass, this.path.substring(0, lastSlash + 1) + path); } @Override public String display() { return aClass.getSimpleName() + "|" + path; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ClassResourceRef that = (ClassResourceRef) o; return !(aClass != null ? !aClass.equals(that.aClass) : that.aClass != null) && !(path != null ? !path.equals(that.path) : that.path != null); } @Override public int hashCode() { int result = aClass != null ? aClass.hashCode() : 0; result = 31 * result + (path != null ? path.hashCode() : 0); return result; } }
package org.crce.interns.service.impl; import java.io.File; import java.io.IOException; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.crce.interns.beans.AllotmentBean; import org.crce.interns.dao.ManageAllotmentDao; import org.crce.interns.model.Allotment; import org.crce.interns.service.ManageAllotmentService; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.multipart.commons.CommonsMultipartFile; @Service("manageAllotmentService") @Transactional(propagation = Propagation.SUPPORTS, readOnly = true) public class ManageAllotmentServiceImpl implements ManageAllotmentService{ @Autowired private ManageAllotmentDao manageAllotmentDao; private String saveDirectory = "C:/work/"; @Transactional(propagation = Propagation.REQUIRED, readOnly = false) public void addAllotment(AllotmentBean allotmentBean) { // TODO Auto-generated method stub Allotment allotment = new Allotment(); BeanUtils.copyProperties(allotmentBean, allotment); //profile.setRole_id("1"); manageAllotmentDao.createAllotment(allotment); } @Transactional(propagation = Propagation.REQUIRED, readOnly = false) public List<Allotment> listAllotment() { // TODO Auto-generated method stub return manageAllotmentDao.listAllotment(); } @Override public void handleFileUpload(HttpServletRequest request, CommonsMultipartFile fileUpload) { // TODO Auto-generated method stub if (!fileUpload.isEmpty()) { System.out.println("Saving file: " + fileUpload.getOriginalFilename()); if (!fileUpload.getOriginalFilename().equals("")) try { fileUpload.transferTo(new File(saveDirectory + fileUpload.getOriginalFilename())); } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //manageAllotmentDao.addNewResume(username,saveDirectory + fileUpload.getOriginalFilename()); } }
package com.mx.cdmx.cacho; import java.io.IOException; import java.lang.annotation.Target; import java.math.BigDecimal; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.text.DecimalFormat; import java.text.NumberFormat; import java.text.ParseException; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; public class PR { public static void main(String[] args) { List<Integer> abcArr = new ArrayList<>(); String str = ""; StringBuilder strBld = new StringBuilder(); abcArr.add(7); abcArr.add(6); abcArr.add(4); abcArr.add(5); int initSize = abcArr.size(); boolean ok = abcArr.stream().anyMatch(a -> a == 9 ); System.out.println("anyMatch: "+ok); int l = 2; int r = 24; List<Integer> intArr = new ArrayList<Integer>() ; List<Integer> intArr1 = new ArrayList<Integer>() ; for (;l <= r;l++) { intArr.add(l); } intArr1 = intArr.stream().filter(i -> i%2 == 1).collect(Collectors.toList()); System.out.println("filter: "+intArr1); ///////////////////////////////////////// int[] apples = {3,2,6,2}; IntStream applesStream = Arrays.stream(apples); applesStream.forEach(x ->{x = x * 4; System.out.println("x: " + x);}); // applesStream. // applesStream.forEach(x -> System.out.println("x1: "+ x)); StringBuffer ok1 = new StringBuffer(""); //abcArr = abcArr.stream().filter(s ->s.contains("Spiderman")).collect(Collectors.toList()); Stream<Integer> abcStream = abcArr.stream().sorted(); Stream<Integer> abcStream1 = abcArr.stream().sorted(); Stream<Integer> abcStreamNs = abcArr.parallelStream(); str = abcStream.map(Object::toString).collect(Collectors.joining()); abcArr.stream().sorted().forEach(strBld::append); System.out.println("str: "+str); System.out.println("strBld: "+strBld); System.out.println("abcArr: "+abcArr); System.out.println("abcArr.size: "+abcArr.size()); System.out.println("init.size: "+initSize); abcStreamNs.forEach(a -> { System.out.println("2 a : "+ a);}); } /* * public static void main(String[] args) { * * // nums = [2, 7, 11, 15], target = 9, * * int[] nums = {2, 7, 11, 15}; int target = 18; * List<Integer> resArr = new * ArrayList<>(); for (int i = 0; i <= nums.length -1; i++ ) { if (nums[i] < * target) { resArr.add(i); } } System.out.println(resArr); } */ /* * public static void main(String[] args) { * System.out.println("class loader for HashMap: " + * java.util.HashMap.class.getClassLoader()); * * //System.out.println("class loader for DNSNameService: " // + * sun.net.spi.nameservice.dns.DNSNameService.class // .getClassLoader()); * * System.out.println("class loader for this class: " + * PR.class.getClassLoader()); * * //System.out.println(com.mysql.jdbc.Blob.class.getClassLoader()); } */ ///////////////////////////////////////////////////// /* * public static void main(String args[]) { Double dobValue = * ThreadLocalRandom.current().nextDouble(1, 20); String value = * customFormat("##.##", dobValue); sendToFile("./output.txt", value); * readFile(); } * * private static void readFile() { Path path = Paths.get("./output.txt"); try { * Files.lines(path).forEach(a -> { StringBuilder sb = new StringBuilder(); * String dlls = convert(Integer.parseInt(a.substring(0, a.lastIndexOf(".")))); * String cents = convert(Integer.parseInt(a.substring(a.lastIndexOf(".") + 1, * a.length()))); sb.append(dlls); sb.append(" dollars "); sb.append(cents); * sb.append(" cents"); sendToFile("./output1.txt", sb.toString()); }); * * } catch (IOException e) { e.printStackTrace(); } } * * private static final String[] tensNames = { "", " ten", " twenty", " thirty", * " forty", " fifty", " sixty", " seventy", " eighty", " ninety" }; final * static String[] numNames = { "", " one", " two", " three", " four", " five", * " six", " seven", " eight", " nine", " ten", " eleven", " twelve", * " thirteen", " fourteen", " fifteen", " sixteen", " seventeen", " eighteen", * " nineteen" }; * * public static String convert(int number) { * * if (number == 0) { return "zero"; } * * String prefix = ""; * * if (number < 0) { number = -number; prefix = "negative"; } * * String current = ""; * * do { int n = number % 1000; if (n != 0) { String s = * convertLessThanOneThousand(n); current = s + current; } number /= 1000; } * while (number > 0); * * return (prefix + current).trim(); } * * private static String convertLessThanOneThousand(int number) { String * current; * * if (number % 100 < 20) { current = numNames[number % 100]; number /= 100; } * else { current = numNames[number % 10]; number /= 10; * * current = tensNames[number % 10] + current; number /= 10; } if (number == 0) * return current; return numNames[number] + " hundred" + current; } * * private static void sendToFile(String fileName, String line) { Path path = * Paths.get(fileName); try { if (Files.notExists(path)) { * Files.createFile(path); } Files.write(path, line.getBytes()); * * } catch (IOException e) { e.printStackTrace(); } } * * static public String customFormat(String pattern, double value) { * DecimalFormat myFormatter = new DecimalFormat(pattern); String output = * myFormatter.format(value); return output; } */ }
/* * (c) 2009 Thomas Smits */ package de.smits_net.tpe.apiimpltrennung; public class CalculatorImpl implements Calculator { public int add(int a, int b) { return a + b; } public int sub(int a, int b) { return a - b; } }
public class Main { public static void main(String[] args){ CircularArrayQueue myNewQueue=new CircularArrayQueue(4); System.out.println("\nThe number of items is "+myNewQueue.noItems()); myNewQueue.enqueue(1); myNewQueue.enqueue(2); myNewQueue.enqueue(3); System.out.println("\nThe number of items is "+myNewQueue.noItems()); // myNewQueue.enqueue(7); System.out.println("Capacity left = "+myNewQueue.getCapacityLeft()); //System.out.print(myNewQueue.dequeue()+" "); //System.out.print(myNewQueue.dequeue()+" "); myNewQueue.enqueue(4); myNewQueue.dequeue(); myNewQueue.enqueue(5); System.out.println("\nThe number of items is "+myNewQueue.noItems()); myNewQueue.enqueue(6); System.out.println("Last element "+myNewQueue.dequeue()+" "); System.out.println("Last element "+myNewQueue.dequeue()+" "); System.out.println("Last element "+myNewQueue.dequeue()+" "); System.out.println("Last element "+myNewQueue.dequeue()+" "); System.out.println("Last element "+myNewQueue.dequeue()+" "); if(myNewQueue.isEmpty()) System.out.print("IT IS EMPTY"); else System.out.println("IT is not"); System.out.print("\nThe number of items is "+myNewQueue.noItems()); //System.out.print(myNewQueue.dequeue()+" "); } }
package com.example.havoc.getchildapi; import android.app.ProgressDialog; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.example.havoc.getchildapi.RestClientr.RestClient; import com.example.havoc.getchildapi.model.LoginPojo; import com.example.havoc.getchildapi.model.SystemInfoPojo; import retrofit.Callback; import retrofit.Response; public class LoginActivity extends AppCompatActivity { EditText mLogin, mPassword, mAuthenticate; Button mLoginButton, mForgotPassword; String authenticate= "false"; TextView mSystemName; ProgressDialog mProgressDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); //Checking if the user is already logged in and skipping the login process through Shared Preferences// SharedPreferences preferences = getApplicationContext().getSharedPreferences("DGSchoolPrefs", 0); if (preferences.getString("USERID", null)!=null){ Intent homeIntent = new Intent(this, MainActivity.class); startActivity(homeIntent); } } @Override protected void onStart() { super.onStart(); initValues(); } private void initValues() { mSystemName=(TextView)findViewById(R.id.app_name_textView); mLogin= (EditText)findViewById(R.id.email_editText); mPassword=(EditText)findViewById(R.id.password_editText); mLoginButton=(Button)findViewById(R.id.login_button); mForgotPassword=(Button)findViewById(R.id.forgot_password_button); //Getting the System name first to display in Login Page// callSystemInfo(); mLoginButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { callLogin(); } }); mForgotPassword=(Button)findViewById(R.id.forgot_password_button); mForgotPassword.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(LoginActivity.this, "Hello", Toast.LENGTH_SHORT).show(); } }); } //Getting the School Name// private void callSystemInfo() { RestClient.RetroApiInterface retroApiInterface= RestClient.getClient(); retroApiInterface.apiSystemInfo(authenticate) .enqueue(new Callback<SystemInfoPojo>() { @Override public void onResponse(Response<SystemInfoPojo> response) { if (response.body()!= null){ String name = response.body().getSystemName(); mSystemName.setText(name); } else if (response.body()==null){ Toast.makeText(LoginActivity.this, "System Error", Toast.LENGTH_SHORT).show(); } } @Override public void onFailure(Throwable t) { } }); } //Getting the Login Details// private void callLogin() { mProgressDialog = new ProgressDialog(LoginActivity.this); mProgressDialog.setMessage("Logging in"); mProgressDialog.setCancelable(false); mProgressDialog.show(); RestClient.RetroApiInterface retroApiInterface= RestClient.getClient(); retroApiInterface.apiLogin(mLogin.getText().toString().trim(), mPassword.getText().toString().trim(), authenticate.toString().trim()) .enqueue(new Callback<LoginPojo>() { @Override public void onResponse(Response<LoginPojo> response) { mProgressDialog.dismiss(); if (response.body()!=null){ if (response.body().getStatus().equals("success")){ String loginType = response.body().getLoginType(); String loginUserId= response.body().getLoginUserId(); String userName= response.body().getName(); String authKey= response.body().getAuthenticationKey(); //Storing the login details to skip the login process if already logged in// SharedPreferences preferences = getApplicationContext().getSharedPreferences("DGSchool", 0); SharedPreferences.Editor editor = preferences.edit(); //Storing login details for further use in respective activity// editor.putString("LOGINTYPE", loginType); editor.putString("USERID", loginUserId); editor.putString("USERNAME", userName); editor.putString("AUTHKEY", authKey); //Getting and Storing extra information of user, if the user is Student// if (loginType.equals("student")){ editor.putString("CLASSID", response.body().getClassID()); } editor.apply(); Intent homeIntent= new Intent(LoginActivity.this, MainActivity.class); startActivity(homeIntent); } } else if (response.body()==null){ Toast.makeText(LoginActivity.this, "Error", Toast.LENGTH_SHORT).show(); } } @Override public void onFailure(Throwable t) { mProgressDialog.dismiss(); Toast.makeText(LoginActivity.this, "Error", Toast.LENGTH_SHORT).show(); } }); } }
package com.permission_owner.model; public class Permission_ownerVO implements java.io.Serializable{ private String pm_no; private String mg_no; public String getPm_no() { return pm_no; } public void setPm_no(String pm_no) { this.pm_no = pm_no; } public String getMg_no() { return mg_no; } public void setMg_no(String mg_no) { this.mg_no = mg_no; } }
package no.hvl.data102; import no.hvl.data102.CD.Genre; import no.hvl.data102.adt.CDarkivADT; public class CDarkiv2 implements CDarkivADT { private int antall = 0; private LinearNode<CD> start; private final String TOM = "CD arkivet er tomt"; public CDarkiv2() { start = null; antall = 0; } @Override public CD[] hentCdTabell() { CD[] tab = new CD[antall]; int i = 0; LinearNode<CD> denne = start; if (start == null) { System.out.println(TOM); } else { while (i < antall && denne != null) { tab[i] = denne.getElement(); denne = denne.getNext(); i++; } } return tab; } @Override public void leggTilCd(CD nyCd) { LinearNode<CD> newNode = new LinearNode<CD>(nyCd); newNode.setNext(start); // Setter node til start start = newNode; // N� er start den nye noden antall++; } @Override public boolean slettCd(int cdNr) { boolean delete = false; LinearNode<CD> tempNode = start; LinearNode<CD> neste = tempNode.getNext(); if (start == null) { // sjekker om det er noen elementer return delete; } if (start.getElement().getCdNumber() == cdNr) { // hvis det er første element der skal slettes start = start.getNext(); antall--; return true; } while (tempNode != null && delete != true) { if (tempNode.getElement().getCdNumber() == cdNr && neste == null) {// Hvis det er sidste elemente der skal // slettes. tempNode = null; antall--; } if (neste.getElement().getCdNumber() == cdNr) {// sletter noder midt i tabellen tempNode.setNext(neste.getNext()); // hopper over noden som har cdnummeret delete = true; antall--; } else { tempNode = tempNode.getNext(); } } return delete; } @Override public CD[] sokTittel(String delstreng) { CD[] tab = new CD[antall]; int i = 0; LinearNode<CD> denne = start; if (antall == 0) { System.out.println(TOM); } else { while (denne != null) { if (denne.getElement().getCdTitle().contains(delstreng)) { tab[i] = denne.getElement(); i++; denne = denne.getNext(); } else { denne = denne.getNext(); } } } tab = trimTab(tab, i); return tab; } @Override public CD[] sokArtist(String delstreng) { CD[] tab = new CD[antall]; int i = 0; LinearNode<CD> denne = start; if (antall == 0) { System.out.println(TOM); } else { while (denne != null) { if (denne.getElement().getArtist().contains(delstreng)) { tab[i] = denne.getElement(); i++; denne = denne.getNext(); } else { denne = denne.getNext(); } } tab = trimTab(tab, i); } return tab; } private CD[] trimTab(CD[] tab, int n) { // n er antall elementer CD[] cdtab2 = new CD[n]; int i = 0; CD[] cdtab2 = new CD[n]; while (i < n) { cdtab2[i] = tab[i]; i++; } return cdtab2; } @Override public int hentAntall() { return antall; } @Override public int hentAntall(Genre sjanger) { LinearNode<CD> denne = start; int nr = 0; while (denne != null) { if (denne.getElement().getGenre() == sjanger) { nr++; denne = denne.getNext(); } else { denne = denne.getNext(); } } return nr; } }
package be.darkshark.parkshark.api.dto.util; public class PhoneNumberDTO { private String countryCode; private int phoneNumber; public PhoneNumberDTO() { } public PhoneNumberDTO(String countryCode, int phoneNumber) { this.countryCode = countryCode; this.phoneNumber = phoneNumber; } public String getCountryCode() { return countryCode; } public void setCountryCode(String countryCode) { this.countryCode = countryCode; } public int getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(int phoneNumber) { this.phoneNumber = phoneNumber; } }
package com.example.ahmed.bakingapp; import android.app.IntentService; import android.appwidget.AppWidgetManager; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.database.Cursor; import com.example.ahmed.bakingapp.database.RecipeContract; import java.util.ArrayList; /** * An {@link IntentService} subclass for handling asynchronous task requests in * a service on a separate handler thread. * <p> * helper methods. */ public class UpdateWidgetService extends IntentService { // IntentService can perform, e.g. ACTION_FETCH_NEW_ITEMS private static final String ACTION_UPDATE_WIDGET = "com.example.ahmed.bakingapp.action.UPDATE"; ArrayList<String> names; public UpdateWidgetService() { super("UpdateWidgetService"); names = new ArrayList<>(); } /** * Starts this service to perform action Foo with the given parameters. If * the service is already performing a task this action will be queued. * * @see IntentService */ public static void startActionRecipes(Context context) { Intent intent = new Intent(context, UpdateWidgetService.class); intent.setAction(ACTION_UPDATE_WIDGET); context.startService(intent); } @Override protected void onHandleIntent(Intent intent) { if (intent != null) { final String action = intent.getAction(); if (ACTION_UPDATE_WIDGET.equals(action)) { handleActionRecipes(); } } } /** * Handle action Foo in the provided background thread with the provided * parameters. */ private void handleActionRecipes() { Cursor cursor = getContentResolver().query(RecipeContract.TableColumns.CONTENT_URI, null, null, null, RecipeContract.TableColumns._ID); if (cursor != null && cursor.getCount() > 0) { if (cursor.moveToFirst()) { do { names.add(cursor.getString(cursor.getColumnIndex(RecipeContract.TableColumns.COLUMN_RECIPE))); } while (cursor.moveToNext()); } cursor.close(); } AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this); int[] appWidgetIds = appWidgetManager.getAppWidgetIds(new ComponentName(this, IngredientsWidget.class)); appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetIds, R.id.widgetListView); IngredientsWidget.updateWidget(this, appWidgetManager, appWidgetIds, names); } }
package com.test.base; /** * Given a non-negative integer N, find the largest number * that is less than or equal to N with monotone increasing digits. * * 给一个非负的正整数,求一个比他小或等于他,且高位到低位,单调递增的最大值 * * @author YLine * * 2019年5月9日 上午8:23:03 */ public interface Solution { public int monotoneIncreasingDigits(int N); }
package paket; public class benzin implements Yakit{ public void depo() { System.out.println("Depoda BENZİN var."); } }
package bullscows; import java.util.Random; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int bulls = 0; int cows = 0; int guesses = 1; int len = 0; int possible_symbols = 0; boolean notFound = true; boolean firstInput = true; System.out.println("Input the length of the secret code:"); if (firstInput) { String len1 = sc.nextLine(); try { len = Integer.parseInt(len1); } catch (NumberFormatException e) { System.out.println("Error.Invalid user input: " + len1); firstInput = false; } } System.out.println("Input the number of possible symbols in the code:"); if (firstInput) { String possible_symbols1 = sc.nextLine(); try { possible_symbols = Integer.parseInt(possible_symbols1); } catch (NumberFormatException e) { System.out.println("Error.Invalid user input: " + possible_symbols1); firstInput = false; } } if (len > 36 || len == 0) { System.out.println("Error: can't generate a secret number with a length of " + len + " because " + "there aren't enough unique digits"); } else if (possible_symbols > 36 || possible_symbols == 0) { System.out.println("Error of possible symbols len, max length is no more than 36"); } else if (possible_symbols < len) { System.out.println("Error: it's not possible to generate a code with a length of " + len +"" + "with " + possible_symbols +"unique symbols"); } else { System.out.println("Okay, let's start a game!"); chosenNum = rand(len, possible_symbols); String str = replaceWithStars(chosenNum); System.out.print("The secret is prepared:" + str + " "); num(len,possible_symbols); } //String guessedNumber = sc.nextLine(); if ((len <= 36 && len > 0) && (possible_symbols <= 36 && possible_symbols > 0) && (possible_symbols >= len)) { do { System.out.println("Turn " + guesses + ": "); String guessedNumber = sc.nextLine(); //System.out.println(guessedNumber.length() + " " + len); if (guessedNumber.length() == len) { bulls = computeBulls(guessedNumber, chosenNum); cows = computeCows(guessedNumber, chosenNum); } if (guessedNumber.length() != len) { System.out.println("Error. Your guess should contain " + len + " symbols (Digits)"); } else if (bulls == len) { System.out.println("Grade: " + bulls + " bulls"); System.out.println("Congratulations! You guessed the secret code."); notFound = false; } else { System.out.println("Grade: " + bulls + " bulls and " + cows + " Cows"); guesses++; } } while (notFound); } //sc.close(); } private static String chosenNum = ""; private static String rand(int len, int possible_symbols) { Random random = new Random(); int randomDigit = 0; //char symbol = Character.forDigit(randomDigit, symbolsRange); //String text = String.valueOf(pseudoRandomNumber); String symbols = "0123456789abcdefghijklmnopqrstuvwxyz"; StringBuilder sb = new StringBuilder(); while (len != sb.length()) { int last_index_symbol = symbols.indexOf(symbols.charAt(possible_symbols-1)); randomDigit = random.nextInt(last_index_symbol - 0) + 0; char b = symbols.charAt(randomDigit); if (!sb.toString().contains(String.valueOf(b))) { sb.append(b); } } return sb.toString(); } private static String replaceWithStars(String chosenNum) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < chosenNum.length(); i++){ sb.append('*'); } return sb.toString(); } private static void num (int len, int possible_symbols){ String symbols = "0123456789abcdefghijklmnopqrstuvwxyz"; char b = symbols.charAt(possible_symbols - 1); //System.out.println(b); if (possible_symbols < 11) { System.out.print(" (0 - " + "9" + ")\n"); } else if (possible_symbols == 11) { System.out.print(" (0 - 9) " + "(a)" + "\n"); } else { System.out.print(" (0 - 9) " + "(a - " + b + ")\n"); } } private static int computeBulls(String num1, String num2) { int bullCounter = 0; for (int i = 0; i < num2.length(); i++) { if (num2.charAt(i) == num1.charAt(i)) { bullCounter++; } } return bullCounter; } private static int computeCows(String num1, String num2) { int cowsCounter = 0; for (int i = 0; i < num2.length(); i++) { for (int j = 0; j < num1.length(); j++) { if (num2.charAt(i) == num1.charAt(j) && i != j) { cowsCounter++; } } } return cowsCounter; } }
package com.distributie.beans; public class ArticoleFactura { private String nume; private String cantitate; private String umCant; private String tipOperatiune; private String departament; private String greutate; private String umGreutate; public ArticoleFactura() { } public String getNume() { return nume; } public void setNume(String nume) { this.nume = nume; } public String getCantitate() { return cantitate; } public void setCantitate(String cantitate) { this.cantitate = cantitate; } public String getUmCant() { return umCant; } public void setUmCant(String umCant) { this.umCant = umCant; } public String getTipOperatiune() { return tipOperatiune; } public void setTipOperatiune(String tipOperatiune) { this.tipOperatiune = tipOperatiune; } public String getDepartament() { return departament; } public void setDepartament(String departament) { this.departament = departament; } public String getGreutate() { return greutate; } public void setGreutate(String greutate) { this.greutate = greutate; } public String getUmGreutate() { return umGreutate; } public void setUmGreutate(String umGreutate) { this.umGreutate = umGreutate; } }
/** * AdminController * @author Aziz Rahman * @author Amy Guinto */ package view; import java.io.IOException; import java.util.ArrayList; import app.PhotoAlbum; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.stage.Modality; import javafx.stage.Stage; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.ListView; import javafx.scene.control.TextField; import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; import javafx.scene.text.Text; import model.*; public class AdminController { @FXML Button back; @FXML Button quit; @FXML Button add; @FXML Button delete; @FXML TextField field2; //Add User Pop-Up @FXML Button ok; @FXML Button cancel; @FXML TextField field; //Delete User Pop-Up @FXML Button okD; @FXML Text user; @FXML ListView<String> listView; ArrayList<User> users = PhotoAlbum.getInstance().users; ObservableList<String> obsList = FXCollections.observableArrayList("admin"); /** * start(Stage stage) overrides method * @param stage */ public void start(Stage stage) { // for debugging for(int i = 0; i < users.size(); i++) { obsList.add(users.get(i).toString()); } users.add(new User("admin")); if(obsList.size() > 0) { listView.setItems(obsList); listView.getSelectionModel().select(0); } //obsList.add("test"); listView.setItems(obsList); listView.getSelectionModel().select(0); } /** * back() returns to login screen * @throws Exception */ public void back() throws Exception { /* Stage stage = (Stage)back.getScene().getWindow(); Parent root = FXMLLoader.load(getClass().getResource("/view/Login.fxml")); Scene scene = new Scene(root); stage.setScene(scene); stage.show(); */ Stage stage = (Stage)back.getScene().getWindow(); FXMLLoader loader = new FXMLLoader(); loader.setLocation(getClass().getResource("/view/Login.fxml")); AnchorPane root = (AnchorPane)loader.load(); LoginController loginController = loader.getController(); //loginController.start(stage); Scene scene = new Scene(root); stage.setScene(scene); } /** * quit() terminates the application */ public void quit() { // serialize objects Stage stage = (Stage)quit.getScene().getWindow(); stage.close(); } /** * add() adds a user and updates the listview * @throws IOException */ public void add() throws IOException{ String s = field2.getText().toLowerCase(); users.add(new User(s)); obsList.add(field2.getText().toLowerCase()); listView.setItems(obsList); /*Stage stage; Parent root; stage = new Stage(); root = FXMLLoader.load(getClass().getResource("AddUserPopUp.fxml")); stage.setScene(new Scene(root)); stage.setTitle("Add User"); stage.initModality(Modality.APPLICATION_MODAL); stage.initOwner(add.getScene().getWindow()); stage.showAndWait(); */ } /** * delete() deletes the selected user and updates the listview * @throws IOException */ public void delete() throws IOException{ for (int i = 0; i < users.size(); i++){ if (obsList.get(i).toString().equals(field2.getText().toLowerCase())){ users.remove(i); obsList.remove(i); break; } } listView.setItems(obsList); } /* Stage stage; Parent root; stage = new Stage(); root = FXMLLoader.load(getClass().getResource("DeleteUserPopUp.fxml")); stage.setScene(new Scene(root)); stage.setTitle("Delete User"); stage.initModality(Modality.APPLICATION_MODAL); stage.initOwner(okD.getScene().getWindow()); stage.showAndWait(); } public void ok(){ Stage stage = (Stage)ok.getScene().getWindow(); users.add(new User(field.getText().toLowerCase())); for(int i = 0; i < users.size(); i++) { System.out.println("User: " + users.get(i)); } obsList.add(field.getText().toLowerCase()); for(int i = 0; i < obsList.size(); i++) { System.out.println("from list: " + obsList.get(i).toString()); } if(obsList.size() > 0){ if (listView == null) System.out.println("LISTVIEW IS NULL"); listView.setItems(obsList); } stage.close(); } public void cancel(){ Stage stage = (Stage)cancel.getScene().getWindow(); stage.close(); } public void okD(){ Stage stage = (Stage)okD.getScene().getWindow(); for (int i = 0; i < users.size(); i++){ if (users.get(i).toString().equals(user.getText())) users.remove(i); } stage.close(); } */ }
package xyz.carbule8.video.command; import lombok.extern.slf4j.Slf4j; import java.io.BufferedReader; import java.io.IOException; import java.util.List; @Slf4j public abstract class SimpleExecute implements ExecuteCommand { @Override public String execute(Object... args) throws IOException { BufferedReader bufferedReader = this.startCommand(args); StringBuilder stringBuilder = new StringBuilder(); String line = null; while ((line = bufferedReader.readLine()) != null) { log.info(line); stringBuilder.append(line); } bufferedReader.close(); return stringBuilder.toString(); } @Override public abstract List<String> getCommand(Object... args); }
package classes; import java.util.ArrayList; import java.util.List; public class Node { private Node Parent; private List<Node> Children; private String character; private Position Position; public Node() { Parent = null; Children = new ArrayList<Node>(); } public Node(Node parent) { Parent = parent; Children = new ArrayList<Node>(); } public void add(Node child) { Children.add(child); } public void setCharacter(String character) { this.character = character; } public void setPosition(Position inPosition) { this.Position = inPosition; } public Position getPosition() { return Position; } public List<Node> getChildren(){ return Children; } @Override public String toString() { return character; } }
package com.shangdao.phoenix.entity.pictureturn; import org.springframework.data.jpa.repository.JpaRepository; public interface PictureTurnsFileRepository extends JpaRepository<PictureTurnsFile, Long> { }
package com.hdy.myhxc.mapper.ex; import com.hdy.myhxc.model.Menu; import com.hdy.myhxc.model.ex.MenuEx; import org.apache.ibatis.annotations.*; import org.apache.ibatis.type.JdbcType; import org.springframework.stereotype.Repository; import java.util.List; /** * @author m760384371 * @date 2019/8/26 */ @Repository @Mapper public interface MenuExMapper { /** * 查询一级菜单 * @return */ @SelectProvider(type = MenuExSqlProvider.class, method = "getListForLevel1") @Results({@Result(column = "UUID",property = "uuid",jdbcType = JdbcType.VARCHAR,id = true), @Result(column = "Menu_ID",property = "menuId",jdbcType = JdbcType.VARCHAR), @Result(column = "Menu_Name",property = "menuName",jdbcType = JdbcType.VARCHAR), @Result(column = "Menu_URL",property = "menuUrl",jdbcType = JdbcType.VARCHAR), @Result(column = "Parent_ID",property = "parentId",jdbcType = JdbcType.VARCHAR), @Result(column = "Menu_ICO",property = "menuIco",jdbcType = JdbcType.VARCHAR), @Result(column = "Leavel_ID",property = "leavelId",jdbcType = JdbcType.VARCHAR), @Result(column = "SORT",property = "sort",jdbcType = JdbcType.VARCHAR), @Result(column = "Create_User",property = "createUser",jdbcType = JdbcType.VARCHAR), @Result(column = "Create_Date",property = "createDate",jdbcType = JdbcType.VARCHAR), @Result(column = "Update_User",property = "updateUser",jdbcType = JdbcType.VARCHAR), @Result(column = "Update_Date",property = "updateDate",jdbcType = JdbcType.VARCHAR), @Result(column = "DelFg",property = "delfg",jdbcType = JdbcType.VARCHAR), @Result(column = "UUID",property = "children",many = @Many(select = "com.hdy.myhxc.mapper.ex.MenuExMapper.getListForLevel2")), }) List<MenuEx> getListForLevel1(); /** * 查询二级菜单 * @param uuid * @return */ @SelectProvider(type = MenuExSqlProvider.class, method = "getListForLevel2") @Results({@Result(column = "UUID",property = "uuid",jdbcType = JdbcType.VARCHAR,id = true), @Result(column = "Menu_ID",property = "menuId",jdbcType = JdbcType.VARCHAR), @Result(column = "Menu_Name",property = "menuName",jdbcType = JdbcType.VARCHAR), @Result(column = "Menu_URL",property = "menuUrl",jdbcType = JdbcType.VARCHAR), @Result(column = "Parent_ID",property = "parentId",jdbcType = JdbcType.VARCHAR), @Result(column = "Menu_ICO",property = "menuIco",jdbcType = JdbcType.VARCHAR), @Result(column = "Leavel_ID",property = "leavelId",jdbcType = JdbcType.VARCHAR), @Result(column = "SORT",property = "sort",jdbcType = JdbcType.VARCHAR), @Result(column = "Create_User",property = "createUser",jdbcType = JdbcType.VARCHAR), @Result(column = "Create_Date",property = "createDate",jdbcType = JdbcType.VARCHAR), @Result(column = "Update_User",property = "updateUser",jdbcType = JdbcType.VARCHAR), @Result(column = "Update_Date",property = "updateDate",jdbcType = JdbcType.VARCHAR), @Result(column = "DelFg",property = "delfg",jdbcType = JdbcType.VARCHAR), }) List<MenuEx> getListForLevel2(@Param("UUID") String uuid); }
package kodiaproject.demo.repository; import kodiaproject.demo.model.UniversityDetailModel; import kodiaproject.demo.model.UniversityRequestModel; import kodiaproject.demo.model.UniversityDatabaseModel; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import java.util.List; import java.util.Optional; public interface UniversityRepository extends JpaRepository<UniversityDatabaseModel, Integer> { List<UniversityRequestModel> findAllBy(); Optional<UniversityDetailModel> findByApiId(@Param("apiId") int id); }
/* * Copyright 2012 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.tch.test.chat.netty; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import java.net.UnknownHostException; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; /** * Handles a server-side channel. */ public class MyServerHandler extends SimpleChannelInboundHandler<String> { private static AtomicInteger counter = new AtomicInteger(0); private static Map<Channel, Integer> channels = new ConcurrentHashMap<Channel, Integer>(); @Override public void channelActive(final ChannelHandlerContext ctx) throws UnknownHostException { Integer channelNum = counter.incrementAndGet(); channels.put(ctx.channel(), channelNum); ctx.writeAndFlush("Hello user-" + channelNum + "\r\n"); } @Override public void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception { // Send the received message to all channels but the current one. for (Map.Entry<Channel, Integer> entry : channels.entrySet()) { Channel c = entry.getKey(); if (c != ctx.channel()) { c.writeAndFlush("user-" + channels.get(ctx.channel()) + " said: " + msg + '\n'); } else { c.writeAndFlush("[you] said: " + msg + '\n'); } } // Close the connection if the client has sent 'bye'. if ("bye".equals(msg.toLowerCase())) { ctx.close(); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { cause.printStackTrace(); ctx.close(); } }
package com.example.mizansen.Network.ModelNetwork; public class AccountModel extends ErrorModel { public String token=""; public String user_email; public String user_nicename; public String user_display_name; }
package com.esum.as2.message; import javax.mail.Session; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * AS2 Message를 정의한다. * * Copyrights(c) eSum Technologies., Inc. All rights reserved. */ public class AS2Message extends Message { private Logger log = LoggerFactory.getLogger(AS2Message.class); /** HTTP Basic Authentication 값 */ private String httpBasicAuth; /** * HTTP Basic Authentication Value를 리턴한다. * * @return String */ public String getHTTPBasicAuth() { return httpBasicAuth; } /** * HTTP Basic Authentication Value를 설정한다. * * @param value String Basic [id]:[random] */ public void setHTTPBasicAuth(String value) { httpBasicAuth = value; } /** * 텅빈 AS2Message를 생성한다. */ public AS2Message(){ super(MessageConstants.PROTOCOL_AS2); } /** * FROM, TO정보를 가지는 AS2Message를 생성한다. * * @param from as2-from * @param to as2-to */ public AS2Message(String from, String to){ super(MessageConstants.PROTOCOL_AS2); setAS2From(from); setAS2To(to); } /** * MimeBodyPart로 된 data를 리턴한다. * @see com.esum.as2.message.Message#getData() */ public MimeBodyPart getData() { return data; } public MimeMessage toMimeMessage() throws AS2MessageException { Session session = Session.getDefaultInstance(System.getProperties()); MimeMessage mimeMessage = new MimeMessage(session); try { Object content = data.getContent(); if(content instanceof MimeMultipart) mimeMessage.setContent((MimeMultipart)content); else if(content instanceof MimeBodyPart){ MimeMultipart mmp = new MimeMultipart(); mmp.addBodyPart((MimeBodyPart)content); } else throw new Exception("Unsupported mime content. "+content.getClass().getName()); } catch (Exception e) { throw new AS2MessageException(AS2MessageException.ERROR_MIME_PACKAGING, "toMimeMessage()", e.getMessage(),e); } return mimeMessage; } public void setData(MimeBodyPart data) throws AS2MessageException{ this.data = data; if (data != null) { try { setContentType(data.getContentType()); String[] contentDisposition = data.getHeader("content-disposition"); if(contentDisposition!=null) setHeader("content-disposition", contentDisposition[0]); setContentLength(data.getSize()); // -1 } catch (Exception e) { throw new AS2MessageException(AS2MessageException.ERROR_MIME_PACKAGING, "setData()", e.getMessage(),e); } } } public boolean isRequestingMDN() { return getDispositionNotificationTo()!=null; } public boolean isAsyncMessage() { if(getReceiptDeliveryOptions()!=null){ return true; } return false; } }
package network.nerve.converter.heterogeneouschain.eth.model; import network.nerve.converter.heterogeneouschain.lib.model.HtgSimpleBlockHeader; /** * 同步区块的高度 * * @author wangkun23 */ public class EthSimpleBlockHeader extends HtgSimpleBlockHeader { }
package com.lovers.java.domain; import java.util.Date; public class UserPhotoAlbum { /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column user_photo_album.album_id * * @mbg.generated Wed Sep 25 10:59:33 CST 2019 */ private Integer albumId; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column user_photo_album.album_name * * @mbg.generated Wed Sep 25 10:59:33 CST 2019 */ private String albumName; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column user_photo_album.album_cover * * @mbg.generated Wed Sep 25 10:59:33 CST 2019 */ private Integer albumCover; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column user_photo_album.album_describe * * @mbg.generated Wed Sep 25 10:59:33 CST 2019 */ private String albumDescribe; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column user_photo_album.user_id * * @mbg.generated Wed Sep 25 10:59:33 CST 2019 */ private Integer userId; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column user_photo_album.create_time * * @mbg.generated Wed Sep 25 10:59:33 CST 2019 */ private Date createTime; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column user_photo_album.modified_time * * @mbg.generated Wed Sep 25 10:59:33 CST 2019 */ private Date modifiedTime; /** * This method was generated by MyBatis Generator. * This method returns the value of the database column user_photo_album.album_id * * @return the value of user_photo_album.album_id * * @mbg.generated Wed Sep 25 10:59:33 CST 2019 */ public Integer getAlbumId() { return albumId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column user_photo_album.album_id * * @param albumId the value for user_photo_album.album_id * * @mbg.generated Wed Sep 25 10:59:33 CST 2019 */ public void setAlbumId(Integer albumId) { this.albumId = albumId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column user_photo_album.album_name * * @return the value of user_photo_album.album_name * * @mbg.generated Wed Sep 25 10:59:33 CST 2019 */ public String getAlbumName() { return albumName; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column user_photo_album.album_name * * @param albumName the value for user_photo_album.album_name * * @mbg.generated Wed Sep 25 10:59:33 CST 2019 */ public void setAlbumName(String albumName) { this.albumName = albumName == null ? null : albumName.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column user_photo_album.album_cover * * @return the value of user_photo_album.album_cover * * @mbg.generated Wed Sep 25 10:59:33 CST 2019 */ public Integer getAlbumCover() { return albumCover; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column user_photo_album.album_cover * * @param albumCover the value for user_photo_album.album_cover * * @mbg.generated Wed Sep 25 10:59:33 CST 2019 */ public void setAlbumCover(Integer albumCover) { this.albumCover = albumCover; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column user_photo_album.album_describe * * @return the value of user_photo_album.album_describe * * @mbg.generated Wed Sep 25 10:59:33 CST 2019 */ public String getAlbumDescribe() { return albumDescribe; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column user_photo_album.album_describe * * @param albumDescribe the value for user_photo_album.album_describe * * @mbg.generated Wed Sep 25 10:59:33 CST 2019 */ public void setAlbumDescribe(String albumDescribe) { this.albumDescribe = albumDescribe == null ? null : albumDescribe.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column user_photo_album.user_id * * @return the value of user_photo_album.user_id * * @mbg.generated Wed Sep 25 10:59:33 CST 2019 */ public Integer getUserId() { return userId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column user_photo_album.user_id * * @param userId the value for user_photo_album.user_id * * @mbg.generated Wed Sep 25 10:59:33 CST 2019 */ public void setUserId(Integer userId) { this.userId = userId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column user_photo_album.create_time * * @return the value of user_photo_album.create_time * * @mbg.generated Wed Sep 25 10:59:33 CST 2019 */ public Date getCreateTime() { return createTime; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column user_photo_album.create_time * * @param createTime the value for user_photo_album.create_time * * @mbg.generated Wed Sep 25 10:59:33 CST 2019 */ public void setCreateTime(Date createTime) { this.createTime = createTime; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column user_photo_album.modified_time * * @return the value of user_photo_album.modified_time * * @mbg.generated Wed Sep 25 10:59:33 CST 2019 */ public Date getModifiedTime() { return modifiedTime; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column user_photo_album.modified_time * * @param modifiedTime the value for user_photo_album.modified_time * * @mbg.generated Wed Sep 25 10:59:33 CST 2019 */ public void setModifiedTime(Date modifiedTime) { this.modifiedTime = modifiedTime; } }
package com.gsccs.sme.plat.site.model; import com.gsccs.sme.api.domain.site.Banner; /** * 热点导航 * * @author x.d zhang * */ public class BannerT extends Banner{ }
package com.indictrans.services; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import com.indictrans.Dao.CustomerDao; import com.indictrans.model.Customer; public interface CustomerService { public Customer findById(Long id); public List<Customer> getRecord(); public void setRecord(Customer customerEntity); public void update(Customer Entity,int id); }