text stringlengths 10 2.72M |
|---|
package com.shensu.pojo;
import java.io.Serializable;
import java.util.List;
public class RecipesType implements Serializable {
//分类的id
private Integer recipestypeid;
//食谱的创建时间
private String recipestypecreattime;
// 食谱类目
private String recipestypename;
//0是下架 1是上架
private Integer recipestypestate;
//分类的图片
private String recipsetypeimg;
//食谱集合
List<Recipes> recipesList;
public List<Recipes> getRecipesList() {
return recipesList;
}
public void setRecipesList(List<Recipes> recipesList) {
this.recipesList = recipesList;
}
private static final long serialVersionUID = 1L;
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column RecipesType.recipesTypeId
*
* @return the value of RecipesType.recipesTypeId
*
* @mbggenerated
*/
public Integer getRecipestypeid() {
return recipestypeid;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column RecipesType.recipesTypeId
*
* @param recipestypeid the value for RecipesType.recipesTypeId
*
* @mbggenerated
*/
public void setRecipestypeid(Integer recipestypeid) {
this.recipestypeid = recipestypeid;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column RecipesType.recipesTypeCreatTime
*
* @return the value of RecipesType.recipesTypeCreatTime
*
* @mbggenerated
*/
public String getRecipestypecreattime() {
return recipestypecreattime;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column RecipesType.recipesTypeCreatTime
*
* @param recipestypecreattime the value for RecipesType.recipesTypeCreatTime
*
* @mbggenerated
*/
public void setRecipestypecreattime(String recipestypecreattime) {
this.recipestypecreattime = recipestypecreattime == null ? null : recipestypecreattime.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column RecipesType.recipesTypeName
*
* @return the value of RecipesType.recipesTypeName
*
* @mbggenerated
*/
public String getRecipestypename() {
return recipestypename;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column RecipesType.recipesTypeName
*
* @param recipestypename the value for RecipesType.recipesTypeName
*
* @mbggenerated
*/
public void setRecipestypename(String recipestypename) {
this.recipestypename = recipestypename == null ? null : recipestypename.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column RecipesType.recipesTypeState
*
* @return the value of RecipesType.recipesTypeState
*
* @mbggenerated
*/
public Integer getRecipestypestate() {
return recipestypestate;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column RecipesType.recipesTypeState
*
* @param recipestypestate the value for RecipesType.recipesTypeState
*
* @mbggenerated
*/
public void setRecipestypestate(Integer recipestypestate) {
this.recipestypestate = recipestypestate;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column RecipesType.recipseTypeImg
*
* @return the value of RecipesType.recipseTypeImg
*
* @mbggenerated
*/
public String getRecipsetypeimg() {
return recipsetypeimg;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column RecipesType.recipseTypeImg
*
* @param recipsetypeimg the value for RecipesType.recipseTypeImg
*
* @mbggenerated
*/
public void setRecipsetypeimg(String recipsetypeimg) {
this.recipsetypeimg = recipsetypeimg == null ? null : recipsetypeimg.trim();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
RecipesType other = (RecipesType) obj;
if (recipesList == null) {
if (other.recipesList != null)
return false;
} else if (!recipesList.equals(other.recipesList))
return false;
if (recipestypecreattime == null) {
if (other.recipestypecreattime != null)
return false;
} else if (!recipestypecreattime.equals(other.recipestypecreattime))
return false;
if (recipestypeid == null) {
if (other.recipestypeid != null)
return false;
} else if (!recipestypeid.equals(other.recipestypeid))
return false;
if (recipestypename == null) {
if (other.recipestypename != null)
return false;
} else if (!recipestypename.equals(other.recipestypename))
return false;
if (recipestypestate == null) {
if (other.recipestypestate != null)
return false;
} else if (!recipestypestate.equals(other.recipestypestate))
return false;
if (recipsetypeimg == null) {
if (other.recipsetypeimg != null)
return false;
} else if (!recipsetypeimg.equals(other.recipsetypeimg))
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((recipesList == null) ? 0 : recipesList.hashCode());
result = prime * result + ((recipestypecreattime == null) ? 0 : recipestypecreattime.hashCode());
result = prime * result + ((recipestypeid == null) ? 0 : recipestypeid.hashCode());
result = prime * result + ((recipestypename == null) ? 0 : recipestypename.hashCode());
result = prime * result + ((recipestypestate == null) ? 0 : recipestypestate.hashCode());
result = prime * result + ((recipsetypeimg == null) ? 0 : recipsetypeimg.hashCode());
return result;
}
@Override
public String toString() {
return "RecipesType [recipestypeid=" + recipestypeid + ", recipestypecreattime=" + recipestypecreattime
+ ", recipestypename=" + recipestypename + ", recipestypestate=" + recipestypestate
+ ", recipsetypeimg=" + recipsetypeimg + ", recipesList=" + recipesList + "]";
}
} |
package model;
public enum City {
GDANSK,
WARSAW,
ZAKOPANE;
}
|
package com.esum.hotdeploy.descriptor;
import java.util.HashSet;
import java.util.Set;
public class ApplicationDescriptor {
private String appName;
private Set<String> loaderOverride = new HashSet<String>();
public String getAppName() {
return appName;
}
public void setAppName(String appName) {
this.appName = appName;
}
public Set<String> getLoaderOverride() {
return loaderOverride;
}
public void setLoaderOverride(Set<String> loaderOverride) {
this.loaderOverride = loaderOverride;
}
}
|
package pl.edu.pw.elka.etherscan;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import pl.edu.pw.elka.etherscan.dtos.EtherscanTransactionsDto;
import pl.edu.pw.elka.minedBlocks.dtos.MinedBlocksDto;
class RealEtherscanConnector implements EtherscanConnector {
private final RestTemplate restTemplate;
private final static String BASE_API_URL =
"http://api.etherscan.io/api?module=account&action=txlist&startblock=%s&endblock=%s&sort=asc&address=%s";
private final static String MINED_BLOCKS_URL =
"https://api.etherscan.io/api?module=account&action=getminedblocks&blocktype=blocks&address=%s";
RealEtherscanConnector() {
restTemplate = new RestTemplate();
}
@Override
public EtherscanTransactionsDto getTransactions(String address, String startBlock, String endBlock) {
final String apiUrl = String.format(BASE_API_URL, startBlock, endBlock, address);
System.out.println(apiUrl);
final ResponseEntity<EtherscanTransactionsDto> entity = restTemplate.getForEntity(apiUrl, EtherscanTransactionsDto.class);
return entity.getBody();
}
@Override
public MinedBlocksDto getMinedBlocks(String address) {
final String apiUrl = String.format(MINED_BLOCKS_URL, address);
final ResponseEntity<MinedBlocksDto> entity = restTemplate.getForEntity(apiUrl, MinedBlocksDto.class);
return entity.getBody();
}
}
|
package com.mcl.mancala.beans;
import com.mcl.mancala.game.Mechanics;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class PlayerMoveTest {
@Test
public void playerMoveBeanConstructorTest() {
Mancala mancala = new Mechanics().start();
PlayerMove playerMove = new PlayerMove(mancala, 1, 2);
assertEquals(mancala, playerMove.getMancala());
assertEquals(1, playerMove.getPlayerToMove());
assertEquals(2, playerMove.getSmallPitToMoveFrom());
}
@Test
public void playerMoveBeanSettersTest() {
Mancala mancala = new Mechanics().start();
PlayerMove playerMove = new PlayerMove();
playerMove.setMancala(mancala);
playerMove.setPlayerToMove(2);
playerMove.setSmallPitToMoveFrom(5);
assertEquals(mancala, playerMove.getMancala());
assertEquals(2, playerMove.getPlayerToMove());
assertEquals(5, playerMove.getSmallPitToMoveFrom());
}
}
|
package xtrus.ex.mgr.exmci.controller;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.esum.appetizer.config.Configurer;
import com.esum.appetizer.controller.AbstractController;
import com.esum.appetizer.util.PageUtil;
import com.esum.appetizer.util.RequestUtils;
import xtrus.ex.mgr.exmci.service.ExIfInfoService;
import xtrus.ex.mgr.exmci.vo.ExIfInfo;
@Controller
public class ExIfInfoController extends AbstractController {
@Autowired
private ExIfInfoService baseService;
/**
* IF 문서 관리 - 목록 화면
*/
@RequestMapping(value = "/c/ex/exmci/exIfInfoList")
public String exIfInfoList(HttpServletRequest request, Model model) {
String ifId = request.getParameter("searchIfId");
String ifType = request.getParameter("searchIfType");
String ioType = request.getParameter("searchIoType");
int currentPage = RequestUtils.getParamInt(request, "currentPage", 1);
PageUtil pageUtil = new PageUtil(currentPage, Configurer.getPropertyInt("Common.LIST.COUNT_PER_PAGE", 10), 10,
baseService.countList(ifId, ifType, ioType, null));
List<ExIfInfo> list = baseService.selectList(ifId, ifType, ioType, null, pageUtil);
model.addAttribute("list", list);
model.addAttribute("pageUtil", pageUtil);
return "/c/ex/exmci/exIfInfoList";
}
/**
* IF 문서 관리 - 등록 화면
*/
@RequestMapping(value = "/c/ex/exmci/exIfInfoInsert")
public String exIfInfoInsert(HttpServletRequest request, Model model) {
// 초기값 설정
ExIfInfo vo = new ExIfInfo();
vo.setUseFlag("N");
vo.setIfType("S"); // BATCH
vo.setIoType("I"); // 수신
model.addAttribute("vo", vo);
return "/c/ex/exmci/exIfInfoInsert";
}
/**
* IF 문서 관리 - 상세 화면
*/
@RequestMapping(value = "/c/ex/exmci/exIfInfoDetail")
public String exIfInfoDetail(HttpServletRequest request, Model model) {
String ifId = request.getParameter("ifId");
ExIfInfo vo = baseService.select(ifId);
model.addAttribute("vo", vo);
return "/c/ex/exmci/exIfInfoInsert";
}
/**
* IF 문서 관리 - 목록 팝업
*/
@RequestMapping(value = "/c/ex/exmci/exIfInfoListPopup")
public String exIfInfoListPopup(HttpServletRequest request, Model model) {
int currentPage = RequestUtils.getParamInt(request, "currentPage", 1);
String useFlag = "Y";
PageUtil pageUtil = new PageUtil(currentPage, Configurer.getPropertyInt("Common.LIST.COUNT_PER_PAGE", 10), 10,
baseService.countList(null, null, null, useFlag));
List<ExIfInfo> list = baseService.selectList(null, null, null, useFlag, pageUtil);
model.addAttribute("list", list);
model.addAttribute("pageUtil", pageUtil);
return "/c/ex/exmci/exIfInfoListPopup";
}
}
|
package com.zaiou.common.mybatis.po;
import java.io.Serializable;
/**
* @Description:
* @auther: LB 2018/9/19 16:31
* @modify: LB 2018/9/19 16:31
*/
public interface Po extends Serializable {
}
|
package com.thoughtworks.ketsu.web;
import com.thoughtworks.ketsu.domain.users.Order;
import com.thoughtworks.ketsu.domain.users.Payment;
import com.thoughtworks.ketsu.web.validators.NullFieldValidator;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.net.URI;
import java.util.Arrays;
import java.util.Map;
public class PaymentApi {
private Order order;
public PaymentApi(Order order) {
this.order = order;
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response pay(Map<String, Object> info) {
new NullFieldValidator().validate(Arrays.asList("pay_type", "amount"), info);
order.pay(info);
return Response.created(URI.create("")).build();
}
@GET
@Produces(MediaType.APPLICATION_JSON)
public Payment getPay() {
return order.getPayment().orElseThrow(() -> new WebApplicationException(Response.Status.NOT_FOUND));
}
}
|
package com.atguigu.exer;
/*
小明要去买一部手机,他询问了4家店的价格,分别是2800.5元,2900元,2750.0元和3100元,显示输出最低价
*/
public class PriceTest {
public static void main(String[] args) {
double[] ps = {2800.5,2900,2750.0,3100};
//把第一个元素先当成最小的值
double min = ps[0];
for (int i = 1; i < ps.length; i++) {
//如果min中的数值比数组中的数值大,那么将数组中的数组赋值给min(min中永远是最小的值)
if(min > ps[i]){
min = ps[i];
}
}
System.out.println(min);
}
}
|
package com.example.ips.service;
import com.example.ips.model.ServerplanLogHistory;
import java.util.List;
import java.util.Map;
/**
* @author: Farben
* @description: ServerplanLogHistoryService:服务器规划-变更日志业务类接口
* @create: 2019/12/20-14:44
**/
public interface ServerplanLogHistoryService {
/**
* 查询全部LogHistory信息
* @return
*/
List<ServerplanLogHistory> getAllLogHistory();
/**
* 根据主键查询LogHistory信息
*/
ServerplanLogHistory getLogHistoryByKey(Integer id);
/**
* 插入信息
*/
Map<String, Object> LogHistoryAdd(ServerplanLogHistory serverplanLogHistory);
/**
* 更新信息
*/
Map<String, Object> LogHistoryUpdate(ServerplanLogHistory serverplanLogHistory);
}
|
package c.c.quadraticfunction.drawing;
public class CanvasSettings {
static public int width;
static public int height;
static public int density;
static public int margin;
static public int drawAreaWidth;
static public int drawAreaHeight;
}
|
package Model;
import Client.Client;
import Client.IClientStrategy;
import IO.MyDecompressorInputStream;
import Server.Server;
import Server.ServerStrategyGenerateMaze;
import Server.ServerStrategySolveSearchProblem;
import View.Main;
import algorithms.mazeGenerators.Maze;
import algorithms.mazeGenerators.Position;
import algorithms.search.Solution;
import javafx.scene.control.Alert;
import javafx.scene.input.KeyCode;
import javafx.stage.FileChooser;
import java.io.*;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Observable;
/**
* This class represents the Model of the game
*/
public class MyModel extends Observable implements IModel {
private Server mazeGeneratingServer;
private Server solveSearchProblemServer;
private int characterPositionRow;
private int characterPositionColumn;
private boolean didWeSolve;
private Solution solution;
private Maze maze;
/**
* The constructor for MyModel
* Creates a new maze generating server and a new search problem solving server
*/
public MyModel() {
// Raise the servers
mazeGeneratingServer = new Server(5400, 1000, new ServerStrategyGenerateMaze());
solveSearchProblemServer = new Server(5401, 1000, new ServerStrategySolveSearchProblem());
didWeSolve = false;
}
/**
* Starts the maze generating and search problem solving servers
*/
public void startServers() {
mazeGeneratingServer.start();
solveSearchProblemServer.start();
}
/**
* Stops the maze generating and search problem solving servers
*/
private void stopServers() {
mazeGeneratingServer.stop();
solveSearchProblemServer.stop();
}
@Override
public void generateMaze(int width, int height) {
//Generate maze
didWeSolve = false;
//threadPool.submit(() -> {
generateRandomMaze(width, height);
characterPositionRow = maze.getStartPosition().getRowIndex();
characterPositionColumn = maze.getStartPosition().getColumnIndex();
setChanged();
notifyObservers("MazeDisplayer, PlayerDisplayer");
//});
}
@Override
public void solveMaze() {
//threadPool.submit(() -> {
didWeSolve = true;
solveMazeSearchProblem();
setChanged();
notifyObservers("SolutionDisplayer");
//});
}
/**
* Generates a random maze through the maze generating server
* @param width - the maze's width
* @param height - the maze's height
*/
private void generateRandomMaze(int width, int height) {
try {
Client client = new Client(InetAddress.getLocalHost(), 5400, new IClientStrategy() {
public void clientStrategy(InputStream inFromServer, OutputStream outToServer) {
try {
ObjectOutputStream toServer = new ObjectOutputStream(outToServer);
ObjectInputStream fromServer = new ObjectInputStream(inFromServer);
toServer.flush();
int[] mazeSize = new int[]{width, height};
toServer.writeObject(mazeSize);
toServer.flush();
byte[] compressedMaze = (byte[]) (fromServer.readObject());
InputStream is = new MyDecompressorInputStream(new ByteArrayInputStream(compressedMaze));
byte[] decompressedMaze = new byte[width * height + 6 + 24];
is.read(decompressedMaze);
maze = new Maze(decompressedMaze);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
});
client.communicateWithServer();
}
catch (UnknownHostException e) {
e.printStackTrace();
}
}
/**
* Solving a search problem given the model's current maze through the search problem solving server
*/
private void solveMazeSearchProblem() {
try {
Client client = new Client(InetAddress.getLocalHost(), 5401, new IClientStrategy() {
@Override
public void clientStrategy(InputStream inFromServer, OutputStream outToServer) {
try {
ObjectOutputStream toServer = new ObjectOutputStream(outToServer);
ObjectInputStream fromServer = new ObjectInputStream(inFromServer);
toServer.flush();
toServer.writeObject(maze);
toServer.flush();
solution = (Solution) fromServer.readObject();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
});
client.communicateWithServer();
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
@Override
public void moveCharacter(KeyCode movement) {
if (maze != null) {
switch (movement) {
case NUMPAD8:
if (maze.isPositionInMaze(new Position(characterPositionRow - 1, characterPositionColumn)) &&
!maze.isPositionAWall(new Position(characterPositionRow - 1, characterPositionColumn)))
characterPositionRow--;
break;
case NUMPAD2:
if (maze.isPositionInMaze(new Position(characterPositionRow + 1, characterPositionColumn)) &&
!maze.isPositionAWall(new Position(characterPositionRow + 1, characterPositionColumn)))
characterPositionRow++;
break;
case NUMPAD6:
if (maze.isPositionInMaze(new Position(characterPositionRow, characterPositionColumn + 1)) &&
!maze.isPositionAWall(new Position(characterPositionRow, characterPositionColumn + 1)))
characterPositionColumn++;
break;
case NUMPAD4:
if (maze.isPositionInMaze(new Position(characterPositionRow, characterPositionColumn - 1)) &&
!maze.isPositionAWall(new Position(characterPositionRow, characterPositionColumn - 1)))
characterPositionColumn--;
break;
case UP:
if (maze.isPositionInMaze(new Position(characterPositionRow - 1, characterPositionColumn)) &&
!maze.isPositionAWall(new Position(characterPositionRow - 1, characterPositionColumn)))
characterPositionRow--;
break;
case DOWN:
if (maze.isPositionInMaze(new Position(characterPositionRow + 1, characterPositionColumn)) &&
!maze.isPositionAWall(new Position(characterPositionRow + 1, characterPositionColumn)))
characterPositionRow++;
break;
case RIGHT:
if (maze.isPositionInMaze(new Position(characterPositionRow, characterPositionColumn + 1)) &&
!maze.isPositionAWall(new Position(characterPositionRow, characterPositionColumn + 1)))
characterPositionColumn++;
break;
case LEFT:
if (maze.isPositionInMaze(new Position(characterPositionRow, characterPositionColumn - 1)) &&
!maze.isPositionAWall(new Position(characterPositionRow, characterPositionColumn - 1)))
characterPositionColumn--;
break;
case NUMPAD7:
if (maze.isPositionInMaze(new Position(characterPositionRow - 1, characterPositionColumn - 1)) &&
!maze.isPositionAWall(new Position(characterPositionRow - 1, characterPositionColumn - 1)) &&
(!maze.isPositionAWall(new Position(characterPositionRow - 1, characterPositionColumn)) ||
!maze.isPositionAWall(new Position(characterPositionRow, characterPositionColumn - 1)))) {
characterPositionRow--;
characterPositionColumn--;
}
break;
case NUMPAD9:
if (maze.isPositionInMaze(new Position(characterPositionRow - 1, characterPositionColumn + 1)) &&
!maze.isPositionAWall(new Position(characterPositionRow - 1, characterPositionColumn + 1)) &&
(!maze.isPositionAWall(new Position(characterPositionRow - 1, characterPositionColumn)) ||
!maze.isPositionAWall(new Position(characterPositionRow, characterPositionColumn + 1)))) {
characterPositionRow--;
characterPositionColumn++;
}
break;
case NUMPAD3:
if (maze.isPositionInMaze(new Position(characterPositionRow + 1, characterPositionColumn + 1)) &&
!maze.isPositionAWall(new Position(characterPositionRow + 1, characterPositionColumn + 1)) &&
(!maze.isPositionAWall(new Position(characterPositionRow + 1, characterPositionColumn)) ||
!maze.isPositionAWall(new Position(characterPositionRow, characterPositionColumn + 1)))) {
characterPositionRow++;
characterPositionColumn++;
}
break;
case NUMPAD1:
if (maze.isPositionInMaze(new Position(characterPositionRow + 1, characterPositionColumn - 1)) &&
!maze.isPositionAWall(new Position(characterPositionRow + 1, characterPositionColumn - 1)) &&
(!maze.isPositionAWall(new Position(characterPositionRow + 1, characterPositionColumn)) ||
!maze.isPositionAWall(new Position(characterPositionRow, characterPositionColumn - 1)))) {
characterPositionRow++;
characterPositionColumn--;
}
break;
}
}
if (getCharacterPositionRow() == maze.getGoalPosition().getRowIndex() && getCharacterPositionColumn() == maze.getGoalPosition().getColumnIndex())
didWeSolve = true;
setChanged();
notifyObservers(didWeSolve ? "PlayerDisplayer, SUCCESS" : "PlayerDisplayer");
}
@Override
public boolean load()
{
FileChooser fc = new FileChooser();
fc.setTitle("Load Game");
fc.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("Game-Saved-Files", "*.SavedMaze"));
fc.setInitialDirectory(new File(System.getProperty("user.dir")));
File file = fc.showOpenDialog(Main.pStage);
if (file != null){
try {
ObjectInputStream gameLoader = new ObjectInputStream(new FileInputStream(file));
maze = (Maze) gameLoader.readObject();
characterPositionRow = maze.getStartPosition().getRowIndex();
characterPositionColumn = maze.getStartPosition().getColumnIndex();
didWeSolve = false;
setChanged();
notifyObservers("MazeDisplayer, PlayerDisplayer");
return true;
}
catch (Exception e) {
Alert a = new Alert(Alert.AlertType.ERROR);
a.setContentText("Could not load The game Ha Ha :(\n Please try again!");
a.showAndWait();
return false;
}
}
return false;
}
@Override
public void exit() {
stopServers();
// threadPool.shutdown();
}
@Override
public void closeModel() {
this.exit();
}
@Override
public void saveGame() {
FileChooser fc = new FileChooser();
fc.setTitle(" It's Time To Save The Game");
fc.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("Game-Saved-Files", "*.SavedMaze"));
fc.setInitialDirectory(new File(System.getProperty("user.dir")));
File file_to_save = fc.showSaveDialog(Main.pStage);
if (file_to_save != null){
boolean if_OK = false;
try{
ObjectOutputStream Saver = new ObjectOutputStream(new FileOutputStream(file_to_save));
Saver.flush();
Saver.writeObject(maze);
Saver.flush();
Saver.close();
if_OK = true;
} catch (Exception e){
if_OK = false;
}
finally {
Alert status = new Alert(if_OK ? Alert.AlertType.CONFIRMATION : Alert.AlertType.ERROR);
status.setContentText(if_OK ? "Game Saved!" : " Don't Know why, But Could not save game :(\n Please try again!");
status.showAndWait();
}
}
}
@Override
public void ChangeProperties(String chosenAlgo, String chosenMaze, String num_of_threads) {
int Thredes=Integer.parseInt(num_of_threads);
boolean GoodInput = true;
if(Thredes<=0 || chosenAlgo==null||chosenMaze==null||num_of_threads==null){
GoodInput=false;
Alert a = new Alert(Alert.AlertType.ERROR);
a.setContentText("Bad Input :(\n Please try again!");
a.showAndWait();
}
if(GoodInput) {
try {
File file = new File("./Resources/config.properties");
String first = "searchingAlgorithm=" + chosenAlgo + "\n";
String second = "mazeGenerator=" + chosenMaze + "\n";
String third = "threadPoolSize=" + num_of_threads;
// if file doesnt exists, then create it
if (!file.exists())
file.createNewFile();
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(first);
bw.write(second);
bw.write(third);
bw.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public int[][] getMaze() {
return maze.getMaze();
}
@Override
public int getCharacterPositionRow() {
return characterPositionRow;
}
@Override
public int getCharacterPositionColumn() {
return characterPositionColumn;
}
@Override
public Position getGoalPosition() {
return maze.getGoalPosition();
}
@Override
public Position getStartPosition() {
return maze.getStartPosition();
}
@Override
public Solution getSolution() {
return solution;
}
}
|
// Problem URL = http://www.spoj.com/problems/EDIST/
import java.util.Scanner;
class EditDistance {
public static void main(String[] args) {
int testcase;
Scanner sc = new Scanner(System.in);
testcase = sc.nextInt(); // Get number of testcases
while(testcase>0){
String a,b;
a = sc.next(); // get first string
b = sc.next(); // get second string
int aLength = a.length();
int bLength = b.length();
int minArr[][]= new int[(aLength+1)][(bLength+1)]; // Declare an Array
for(int i=0;i<=aLength;i++){
minArr[i][0] = i; // Initialize the firts column.
}
for(int i=0;i<=bLength;i++){
minArr[0][i] = i; // Initialize the first row
}
for(int i=1;i<=aLength;i++){
for(int j=1;j<=bLength;j++){
if(a.charAt(i-1)==b.charAt(j-1)){
minArr[i][j]=minArr[i-1][j-1];
}else{
int min = findMin(minArr[i-1][j],minArr[i][j-1],minArr[i-1][j-1]);
minArr[i][j] = min+1;
}
}
}
System.out.println(minArr[aLength][bLength]);
testcase--;
}
}
// To find the minimum of 3 numbers
public static int findMin(int a, int b, int c){
int min = a;
if(min>b) min = b;
if(min>c) min = c;
return min;
}
}
|
package ui;
import java.awt.BorderLayout;
import java.util.ArrayList;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import modelo.Remito;
import persistencia.RemitoDAO;
import javax.swing.JScrollPane;
import javax.swing.JLabel;
public class PedidosPendientesListaUI extends JFrame {
private JPanel contentPane;
JList list = new JList();
RemitoDAO dao=new RemitoDAO();
private final JLabel lblSeleccioneUnPedido_1 = new JLabel("Seleccione un Pedido:");
public PedidosPendientesListaUI() {
setTitle("Pedidos Pendientes");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout(0, 0));
list.setValueIsAdjusting(true);
JScrollPane scrollPane = new JScrollPane(list);
contentPane.add(scrollPane);
contentPane.add(lblSeleccioneUnPedido_1, BorderLayout.NORTH);
list.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent arg0) {
if ( !arg0.getValueIsAdjusting() && ! list.isSelectionEmpty()){
//tengo que sacar el id del string con todo
String seleccion=(String)list.getSelectedValue();
String split[]=seleccion.split("-");
int remitoId=Integer.parseInt(split[1].trim());
dao.getElecciones(remitoId);
PedidosPendientesListaUI.this.setVisible(false);
}
}
});
//contentPane.add(list, BorderLayout.CENTER);
}
public void inicializarUI(){
dao.cargarRemitosPendientes();
ArrayList<Integer> pedidosPendId =dao.getIdRemitosPendientes();
ArrayList<String> fechaPedidosPendientes =dao.getFechaRemitoPendiente();
DefaultListModel<String> modelo=new DefaultListModel<>();
int j=0;
for(Integer id:pedidosPendId){
String m= "Remito - "+ id + " - Fecha: " + fechaPedidosPendientes.get(j);
modelo.addElement(m);
j++;
}
list.setModel(modelo);
this.setVisible(true);
}
}
|
/**
* NounEnumSerializer
*/
package com.bs.bod.converter;
import java.io.IOException;
import com.bs.bod.NounEnum;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
/**
* @author dbs on Dec 26, 2015 2:12:29 PM
* @version 1.0
* @since V0.0.1
*
*/
public class NounEnumSerializer extends JsonSerializer<NounEnum> {
@Override
public void serialize(NounEnum value, JsonGenerator jgen, SerializerProvider serializers) throws IOException, JsonProcessingException {
jgen.writeNumber(value.ordinal());
}
}
|
package uz.pdp.lesson5task1.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import uz.pdp.lesson5task1.entity.Company;
import uz.pdp.lesson5task1.payload.ApiResponse;
import uz.pdp.lesson5task1.payload.CompanyDto;
import uz.pdp.lesson5task1.service.CompanyService;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
@RestController
@RequestMapping("/company")
public class CompanyController {
@Autowired
CompanyService companyService;
@PostMapping
public ResponseEntity<?> addCompany(@RequestBody CompanyDto companyDto) {
ApiResponse apiResponse = companyService.addCompany(companyDto);
if (apiResponse.isSuccess()) return ResponseEntity.ok(apiResponse);
return ResponseEntity.status(409).body(apiResponse);
}
@GetMapping("/getAll")
public ResponseEntity<?> getAll() {
List<Company> companies = companyService.companyInfo();
if (companies.isEmpty()) return ResponseEntity.status(409).body(companies);
return ResponseEntity.ok(companies);
}
@GetMapping("/getByToken")
public ResponseEntity<?> getByToken() {
Company companyInfoByToken = companyService.getCompanyInfoByToken();
if (companyInfoByToken != null) return ResponseEntity.ok(companyInfoByToken);
return ResponseEntity.status(409).body(companyInfoByToken);
}
@DeleteMapping
public ResponseEntity<?> delete() {
ApiResponse delete = companyService.delete();
if (!delete.isSuccess()) return ResponseEntity.status(409).body(delete);
return ResponseEntity.ok(delete);
}
@PutMapping
public ResponseEntity<?> edit( @RequestBody CompanyDto companyDto) {
ApiResponse apiResponse = companyService.edit(companyDto);
if (apiResponse.isSuccess()) return ResponseEntity.ok(apiResponse);
return ResponseEntity.status(409).body(apiResponse);
}
}
|
package edu.mit.cci.simulation.client.model.jaxb;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.adapters.XmlAdapter;
public class ClientArrayAdapter {
@XmlElement
public String data;
public ClientArrayAdapter() {
}
public ClientArrayAdapter(Object[] data) {
if (data == null) this.data = null;
else {
this.data = "[";
String sep = "";
for (Object o : data) {
this.data += (sep + (o == null ? "null" : o.toString()));
sep = ",";
}
this.data += "]";
}
}
private static String[] parseString(String s) {
if (s == null) {
return null;
} else {
s = s.substring(1, s.length() - 1);
return s.split(",");
}
}
private static Class[] parseClass(String s) {
if (s == null) {
return null;
} else {
String[] st = parseString(s);
Class[] result = new Class[st.length];
int i = 0;
for (String t : st) {
try {
t = t.replaceFirst("class\\s","");
result[i] = Class.forName(t);
} catch (ClassNotFoundException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
result[i] = Object.class;
}
i++;
}
return result;
}
}
public static class StringAdapter extends XmlAdapter<ClientArrayAdapter, String[]> {
@Override
public ClientArrayAdapter marshal(String[] v) throws Exception {
return new ClientArrayAdapter(v);
}
@Override
public String[] unmarshal(ClientArrayAdapter v) throws Exception {
return parseString(v.data);
}
}
public static class ClassAdapter extends XmlAdapter<ClientArrayAdapter, Class<Object>[]> {
@Override
public ClientArrayAdapter marshal(Class<Object>[] v) throws Exception {
return new ClientArrayAdapter(v);
}
@Override
public Class<Object>[] unmarshal(ClientArrayAdapter v) throws Exception {
return parseClass(v.data);
}
}
} |
package com.teams.Controller;
import com.teams.Dto.NationalTeamsDto;
import com.teams.Entities.NationalTeams;
import com.teams.Repository.NationalTeamsRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
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.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import java.util.List;
@Controller
public class NationalTeamsController {
@Autowired
NationalTeamsRepository nationalTeamsRepository;
@GetMapping("/nationalTeams")
public String getNationalTeams(Model model) {
List<NationalTeams> nationalTeams = (List<NationalTeams>) nationalTeamsRepository.findAll();
model.addAttribute("nationalTeams", nationalTeams);
return "nationalTeams";
}
@GetMapping("/nationalTeams/add")
@Secured("ROLE_ADMIN")
public String showNationalTeams(NationalTeamsDto nationalTeamsDto){
nationalTeamsDto.setName((List<NationalTeams>)nationalTeamsRepository.findAll());
return "nationalTeam-add";
}
@PostMapping("nationalTeams/add")
@Secured("ROLE_ADMIN")
public String addNationalTeam(@Validated NationalTeamsDto nationalTeamsDto, BindingResult result, Model model) {
if (result.hasErrors()) {
return "nationalTeam-add";}
return null;
}
// NationalTeamsRepository.save(
//
// void convertDtoToEntity(NationalTeams);
// model.addAttribute("nationalTeams", NationalTeamsRepository.findAll());
// return "nationalTeams";
}
|
package com.lmz.selenilum;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.io.File;
public class frameChange {
public static void main(String[] args) throws InterruptedException {
////先设置访问ChromeDriver的路径
// 将系统属性“webdriver.chrome.driver” 设置为 ChromeDriver.exe 文件的路径并实例化ChromeDriver类。
System.setProperty("webdriver.chrome.driver", "D:\\chromedriver\\chromedriver.exe");
WebDriver driver=new ChromeDriver();
File file =new File("D:\\oct\\testone\\src\\main\\java\\com\\lmz\\web\\frame.html");
String filepath=file.getAbsolutePath();
driver.get(filepath);
//切换到iframe(mane=ttt)
// byid查不到,name可以
// driver.switchTo().frame("ttt");
//switchTo().frame()默认可以直接取表单的id 或name 属性。如果iframe 没有可用的id 和name 属性,
//则可以通过下面的方式进行定位。
WebElement xf=driver.findElement(By.xpath("//*[@id=\"=asd\"]"));
driver.switchTo().frame(xf);
driver.findElement(By.id("kw")).sendKeys("webdriver");
driver.findElement(By.id("su")).click();
//返回上一级表单
//如果完成了在当前表单上的操作,则可以通过switchTo().defaultContent()方法跳出表单
driver.switchTo().defaultContent();
}
}
|
package com.example.maplechat;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import java.io.IOException;
import java.util.UUID;
public class UserAccountActivity extends AppCompatActivity {
private ImageView user_image;
private TextView user_name_text_view;
private TextView email_text_view;
private Uri imageUrl;
private Button upload_image;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_account);
user_image = findViewById(R.id.user_image);
upload_image = findViewById(R.id.upload_image_button);
// User Image selection
user_image.setOnClickListener(view -> {
Intent gallery = new Intent(Intent.ACTION_PICK);
gallery.setType("image/*");
startActivityForResult(gallery, 1);
});
// Open gallery
upload_image.setOnClickListener(view -> {
uploadImage();
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK && data != null) {
imageUrl = data.getData();
getImage();
}
}
// Getting and setting image
private void getImage() {
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imageUrl);
} catch (IOException e) {
e.printStackTrace();
}
user_image.setImageBitmap(bitmap);
}
// Upload the image on the firebase
private void uploadImage() {
ProgressDialog dialog = new ProgressDialog(this);
dialog.setTitle("Uploading...");
dialog.show();
FirebaseStorage storage = FirebaseStorage.getInstance();
storage.getReference("images/" + UUID.randomUUID().toString()).putFile(imageUrl).addOnCompleteListener(task -> {
if (task.isSuccessful()) {
task.getResult().getStorage().getDownloadUrl().addOnCompleteListener(task1 -> {
if (task1.isSuccessful()) {
updateProfilePicture(task1.getResult().toString());
Toast.makeText(UserAccountActivity.this, "Image uploaded!", Toast.LENGTH_LONG).show();
}
});
} else {
Toast.makeText(UserAccountActivity.this, task.getException().getLocalizedMessage(), Toast.LENGTH_LONG).show();
}
dialog.dismiss();
}).addOnProgressListener(snapshot -> {
// Progress for image upload
final double progress = 100.0 * snapshot.getBytesTransferred() / snapshot.getTotalByteCount();
dialog.setMessage("Image Uploaded " + (int) progress + "%");
});
}
// Updating profile picture for the user on the server
private void updateProfilePicture(String Url) {
FirebaseDatabase.getInstance().getReference("users/" + FirebaseAuth.getInstance().getCurrentUser().getUid() + "/imageUrl").setValue(Url);
}
} |
package io;
import java.io.IOException;
import java.io.OutputStream;
public class MyCompressorOutputStream extends OutputStream{
OutputStream out;
MyCompressorOutputStream(OutputStream outStr){
out = outStr;
}
@Override
public void write(byte[] b) throws IOException {
out.write(Tools.compress(b));
}
@Override
public void write(int b) throws IOException {
throw new UnsupportedOperationException("write(int) not supported");
}
}
|
package com.gaby.annotation;
import java.lang.annotation.*;
/**
*@discrption:字段校验器(是否必须)
*@user:Gaby
*@createTime:2019-03-17 21:57
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@Inherited
public @interface Field {
String comment() default "";
boolean nullable() default true;
}
|
package org.camunda.bpm.engine.test.fluent.assertions;
import java.util.Date;
import org.camunda.bpm.engine.ProcessEngine;
import org.camunda.bpm.engine.runtime.Job;
import org.fest.assertions.api.Assertions;
/**
* Fluent assertions for {@link Job}
*
*/
public class JobAssert extends AbstractProcessAssert<JobAssert, Job> {
protected JobAssert(final ProcessEngine engine, final Job actual) {
super(engine, actual, JobAssert.class);
}
public static JobAssert assertThat(final ProcessEngine engine, final Job actual) {
return new JobAssert(engine, actual);
}
/**
* Assertion on the due date of the {@link org.camunda.bpm.engine.task.Task}.
*
* @param expectedDueDate
* the due date
*
* @return a {@link JobAssert} that can be further configured before starting
* the process instance
*
* @see org.camunda.bpm.engine.task.Task#getDueDate()
*/
public JobAssert hasDueDate(final Date expectedDueDate) {
isNotNull();
final Date actualDuedate = actual.getDuedate();
Assertions.assertThat(actualDuedate)
.overridingErrorMessage("Expected job '%s' to have '%s' as due date but has '%s'", actual.getId(), expectedDueDate, actualDuedate)
.equals(expectedDueDate);
return this;
}
/**
*
* @param expectedId
* the job id
*
* @return a {@link JobAssert} that can be further configured before starting
* the process instance
*/
public JobAssert hasId(final String expectedId) {
isNotNull();
final String actualId = actual.getId();
Assertions.assertThat(actualId).overridingErrorMessage("Expected job with id '%s', but was '%s'", expectedId, actualId).isEqualTo(expectedId);
return this;
}
}
|
import java.util.*;
class shaurya
{
public static void main(String args[])
{
Scanner sc= new Scanner(System.in);
System.out.println("enter the length of stirng");
int n=sc.nextInt();
System.out.println("enter the number of operations");
int m=sc.nextInt();
System.out.println("enter the string");
String s =sc.next();
int x,y,z,c=0;
boolean[] answer=new boolean[0];
for(x=0;x<m;x++)
{
int menu=sc.nextInt();
if(menu==2)
{
answer=Arrays.copyOf(answer,answer.length + 1);
int a=sc.nextInt()-1;
int b=sc.nextInt()-1;
String s1=s.substring(a,b+1);
String s2="";
for(y=0;y<s1.length();y++)
{
s2=s1.charAt(y)+s2;
}
if(s1.equalsIgnoreCase(s2))
{
answer[c]=true;
c++;
}
else
{
answer[c]=false;
c++;
}
}
if(menu==1)
{
int index=sc.nextInt()-1;
char ch=sc.next().charAt(0);
String s1="";
for(y=0;y<s.length();y++)
{
char ch1=s.charAt(y);
if(y==index)
{
s1=s1+ch;
}
else
{
s1=s1+ch1;
}
}
s=s1;
s1="";
}
}
for(x=0;x<answer.length;x++)
{
if(answer[x]==true)
System.out.println("Yes");
else
System.out.println("No");
}
}
}
|
package com.example.demo.dto;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.ToString;
import java.math.BigDecimal;
@EqualsAndHashCode
@ToString
@Getter
@AllArgsConstructor
public class InputDto {
private final BigDecimal operando1;
private final BigDecimal operando2;
}
|
package com.kh.portfolio.board.dao;
import java.util.List;
import com.kh.portfolio.board.vo.BoardCategoryVO;
import com.kh.portfolio.board.vo.BoardFileVO;
import com.kh.portfolio.board.vo.BoardVO;
import com.kh.portfolio.board.vo.NoticeVO;
import lombok.Data;
public interface NoticeDAO {
//게시글작성
int noticeWrite(NoticeVO noticeVO);
//게시글수정
int noticeModify(NoticeVO noticeVO);
//게시글삭제
int noticeDelete(String nnum);
//게시글보기
NoticeVO noticeView(String nnum);
//조회수 +1 증가
int noticeUpdateHit(String nnum);
List<NoticeVO> noticeMain();
//게시글목록
//1)전체
List<NoticeVO> noticeList();
//2)검색어 없는 게시글페이징
List<NoticeVO> noticeList( int startRec, int endRec);
//3)검색어 있는 게시글검색(전체,제목,내용,작성자ID,별칭)
List<NoticeVO> noticeList( int startRec, int endRec, String searchType,String keyword);
//총 레코드수
int noticeTotalRecordCount(String searchType,String keyword);
// //게시글답글작성
// int noticeReply(NoticeVO noticeVO);
}
|
package Servlets;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
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 Database.DBConnection;
import com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException;
/**
* Servlet implementation class BetServlet
*/
@WebServlet("/BetServlet")
public class BetServlet extends HttpServlet {
long CurrentBetID = 0;
private static final long serialVersionUID = 1L;
public DBConnection place_bet = DBConnection.getInstance();
/**
* @see HttpServlet#HttpServlet()
*/
public BetServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
// @SuppressWarnings("unchecked")
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("Placing bet...");
try {
if (Integer.parseInt(place_bet
.ExecuteQuery(
"SELECT account, Bets FROM players WHERE Username = \""
+ UsernameValidation(request
.getParameter("username")) + "\";")
.get(0).get(0)) == 0
&& Integer.parseInt(place_bet
.ExecuteQuery(
"SELECT account, Bets FROM players WHERE Username = \""
+ UsernameValidation(request
.getParameter("username"))
+ "\";").get(0).get(1)) >= 3) {
// free users cannot make more than 3 bets
// New location to be redirected
String site = new String("Pages/MoreThan3Bets.html");
response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
response.setHeader("Location", site);
System.out.println("Free user trying to make more than 3 bets");
} else {
try {
int account_type = Integer.parseInt(place_bet.ExecuteQuery(
"SELECT account FROM players WHERE Username = \""
+ UsernameValidation(request
.getParameter("username"))
+ "\";")
.get(0).get(0));
place_bet
.ExecuteQuery("INSERT INTO bets (USERNAME, BetID, RiskLevel, Amount) VALUES (\""
+ UsernameValidation(request
.getParameter("username"))
+ "\", \""
+ GenerateBetID()
+ "\", \""
+ ValidateRiskLevel(account_type,
Integer.parseInt(request
.getParameter("risk_lvl")))
+ "\", \""
+ ValidateBetAmount(
account_type,
Integer.parseInt(request
.getParameter("bet_amt")),
getTotalBetAmount(place_bet
.ExecuteQuery(
"SELECT sum(amount) FROM bets WHERE Username = \""
+ UsernameValidation(request
.getParameter("username"))
+ "\";")
.get(0))) + "\");");
place_bet
.ExecuteQuery("UPDATE players SET Bets = Bets+1 WHERE username = \""
+ request.getParameter("username") + "\";");
// New location to be redirected
String site = new String("Pages/BetSuccess.html");
response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
response.setHeader("Location", site);
} catch (UnsupportedOperationException oe) {
// New location to be redirected
BetServlet.this.CurrentBetID--;
String site = new String("Pages/InvalidRisk.html");
response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
response.setHeader("Location", site);
oe.printStackTrace();
} catch (SQLException se) {
// New location to be redirected
BetServlet.this.CurrentBetID--;
String site = new String("Pages/InvalidBetAmount.html");
response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
response.setHeader("Location", site);
se.printStackTrace();
}
}
} catch (MySQLIntegrityConstraintViolationException primarykey_violation) {
BetServlet.this.CurrentBetID--;
System.out.println("There exists a bet with the same bet ID!");
} catch (Exception e) {
BetServlet.this.CurrentBetID--;
// New location to be redirected
String site = new String("Pages/MaxCumulativeBets.html");
response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
response.setHeader("Location", site);
System.out.println("Invalid Bet Parameters");
e.printStackTrace();
}
}
public void init() {
try {
ArrayList<ArrayList<String>> last_id = new ArrayList<>(
place_bet.ExecuteQuery("SELECT max(BetID) FROM bets;"));
if (last_id.get(0).get(0) != null)
this.CurrentBetID = Long.parseLong(last_id.get(0).get(0));
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String UsernameValidation(String username) throws SQLException {
Pattern p = Pattern.compile("^[A-Za-z0-9]+$");
Matcher m = p.matcher(username);
boolean b = m.find();
if (b == true && username.length() >= 6) {
return username;
} else {
throw new SQLException();
}
}
public int ValidateRiskLevel(int account_type, int risk_level)
throws UnsupportedOperationException {
if (((account_type == 0) && (risk_level == 0))
|| ((account_type == 1) && (risk_level >= 0) && (risk_level < 3))) {
return risk_level;
} else
throw new UnsupportedOperationException();
}
public int ValidateBetAmount(int account_type, int bet_amount,
int total_bets) throws SQLException, Exception {
if (bet_amount > 0
&& total_bets >= 0
&& (((account_type == 0) && (bet_amount <= 5)) || ((account_type == 1) && ((total_bets + bet_amount) <= 5000)))) {
return bet_amount;
} else if ((account_type == 1) && ((total_bets + bet_amount) > 5000)) {
throw new Exception();
}
else {
throw new SQLException();
}
}
public long GenerateBetID() {
try {
BetServlet.this.CurrentBetID++;
} catch (Exception e) {
BetServlet.this.CurrentBetID = 1;
}
return CurrentBetID;
}
public int getTotalBetAmount(ArrayList<String> arraylist) {
if (arraylist.get(0) == null) {
return 0;
} else
return Integer.parseInt(arraylist.get(0));
}
}
|
package com.karya.dao.impl;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.karya.dao.IEmployeeReportDao;
import com.karya.model.EmploySalaryRegisterReport001MB;
import com.karya.model.EmployWorkHolidayReport001MB;
import com.karya.model.EmployeeBirthdayReport001MB;
import com.karya.model.EmployeeLeaveBalanceReport001MB;
import com.karya.model.MonthlyAttendSheet001MB;
@Repository
@Transactional
public class EmployeeReportDaoImpl implements IEmployeeReportDao{
@PersistenceContext
private EntityManager entityManager;
@SuppressWarnings("unchecked")
public List<EmployeeLeaveBalanceReport001MB> listempleavebalancereport() {
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<EmployeeLeaveBalanceReport001MB> cq = builder.createQuery(EmployeeLeaveBalanceReport001MB.class);
Root<EmployeeLeaveBalanceReport001MB> root = cq.from(EmployeeLeaveBalanceReport001MB.class);
cq.select(root);
return entityManager.createQuery(cq).getResultList();
}
public void addempleavebalancereport(EmployeeLeaveBalanceReport001MB employeeleavebalancereport001mb) {
entityManager.merge(employeeleavebalancereport001mb);
}
public EmployeeLeaveBalanceReport001MB getempleavebalancereport(int elbId) {
EmployeeLeaveBalanceReport001MB employeeleavebalancereport001mb = entityManager.find(EmployeeLeaveBalanceReport001MB.class, elbId);
return employeeleavebalancereport001mb;
}
public void deleteempleavebalancereport(int elbId) {
EmployeeLeaveBalanceReport001MB employeeleavebalancereport001mb = entityManager.find(EmployeeLeaveBalanceReport001MB.class, elbId);
entityManager.remove(employeeleavebalancereport001mb);
}
//employ birthday
@SuppressWarnings("unchecked")
public List<EmployeeBirthdayReport001MB> listempbirhtdayreport() {
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<EmployeeBirthdayReport001MB> cq = builder.createQuery(EmployeeBirthdayReport001MB.class);
Root<EmployeeBirthdayReport001MB> root = cq.from(EmployeeBirthdayReport001MB.class);
cq.select(root);
return entityManager.createQuery(cq).getResultList();
}
public void addempbirhtdayreport(EmployeeBirthdayReport001MB employeebirthdayreport001mb) {
entityManager.merge(employeebirthdayreport001mb);
}
public EmployeeBirthdayReport001MB getempbirhtdayreport(int empbirthId) {
EmployeeBirthdayReport001MB employeebirthdayreport001mb = entityManager.find(EmployeeBirthdayReport001MB.class, empbirthId);
return employeebirthdayreport001mb;
}
public void deleteempbirhtdayreport(int empbirthId) {
EmployeeBirthdayReport001MB employeebirthdayreport001mb = entityManager.find(EmployeeBirthdayReport001MB.class, empbirthId);
entityManager.remove(employeebirthdayreport001mb);
}
//employ work hoilday
@SuppressWarnings("unchecked")
public List<EmployWorkHolidayReport001MB> listempworkholiday() {
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<EmployWorkHolidayReport001MB> cq = builder.createQuery(EmployWorkHolidayReport001MB.class);
Root<EmployWorkHolidayReport001MB> root = cq.from(EmployWorkHolidayReport001MB.class);
cq.select(root);
return entityManager.createQuery(cq).getResultList();
}
public void addempworkholiday(EmployWorkHolidayReport001MB employeeworkholidayreport001mb) {
entityManager.merge(employeeworkholidayreport001mb);
}
public EmployWorkHolidayReport001MB getempworkholiday(int empwhId) {
EmployWorkHolidayReport001MB employeeworkholidayreport001mb = entityManager.find(EmployWorkHolidayReport001MB.class, empwhId);
return employeeworkholidayreport001mb;
}
public void deleteempworkholiday(int empwhId) {
EmployWorkHolidayReport001MB employeeworkholidayreport001mb = entityManager.find(EmployWorkHolidayReport001MB.class, empwhId);
entityManager.remove(employeeworkholidayreport001mb);
}
//employ salary register
@SuppressWarnings("unchecked")
public List<EmploySalaryRegisterReport001MB> listempsalaryregister() {
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<EmploySalaryRegisterReport001MB> cq = builder.createQuery(EmploySalaryRegisterReport001MB.class);
Root<EmploySalaryRegisterReport001MB> root = cq.from(EmploySalaryRegisterReport001MB.class);
cq.select(root);
return entityManager.createQuery(cq).getResultList();
}
public void addempsalaryregister(EmploySalaryRegisterReport001MB employeesalaryregisterreport001mb) {
entityManager.merge(employeesalaryregisterreport001mb);
}
public EmploySalaryRegisterReport001MB getempsalaryregister(int esregId) {
EmploySalaryRegisterReport001MB employeesalaryregisterreport001mb = entityManager.find(EmploySalaryRegisterReport001MB.class, esregId);
return employeesalaryregisterreport001mb;
}
public void deleteempsalaryregister(int esregId) {
EmploySalaryRegisterReport001MB employeesalaryregisterreport001mb = entityManager.find(EmploySalaryRegisterReport001MB.class, esregId);
entityManager.remove(employeesalaryregisterreport001mb);
}
//monthly attend sheet
@SuppressWarnings("unchecked")
public List<MonthlyAttendSheet001MB> listmonthlyattendsheet() {
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<MonthlyAttendSheet001MB> cq = builder.createQuery(MonthlyAttendSheet001MB.class);
Root<MonthlyAttendSheet001MB> root = cq.from(MonthlyAttendSheet001MB.class);
cq.select(root);
return entityManager.createQuery(cq).getResultList();
}
public void addmonthlyattendsheet(MonthlyAttendSheet001MB monthlyattendsheet001mb) {
entityManager.merge(monthlyattendsheet001mb);
}
public MonthlyAttendSheet001MB getmonthlyattendsheet(int atsId) {
MonthlyAttendSheet001MB monthlyattendsheet001mb = entityManager.find(MonthlyAttendSheet001MB.class, atsId);
return monthlyattendsheet001mb;
}
public void deletemonthlyattendsheet(int atsId) {
MonthlyAttendSheet001MB monthlyattendsheet001mb = entityManager.find(MonthlyAttendSheet001MB.class, atsId);
entityManager.remove(monthlyattendsheet001mb);
}
}
|
package app.services;
import app.entity.Hospital;
import app.entity.Room;
import app.repository.RoomRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class RoomService implements AbstractServiceInterface<Room> {
@Autowired
private RoomRepository roomRepository;
@Autowired
private HospitalService hospitalService;
@Override
public void save(Room room) {
roomRepository.save(room);
}
@Override
public void update(Room room) {
roomRepository.save(room);
}
@Override
public boolean delete(long id) {
Room room = roomRepository.findOne(id);
if(room != null) {
roomRepository.delete(id);
return true;
}
return false;
}
@Override
public List<Room> list() {
return roomRepository.findAll();
}
@Override
public Room findById(long id) {
return roomRepository.findOne(id);
}
public List<Room> findByHospitalId(long id) {
Hospital hospital = hospitalService.findById(id);
return roomRepository.findByHospital(hospital);
}
/*
public List<Room> findByHospital(long id) {
return roomRepository.findByHospital(id);
}
*/
}
|
package com.github.andlyticsproject.exception;
public class SignupException extends Exception {
private static final long serialVersionUID = 1L;
public SignupException(String value) {
super(value);
}
}
|
import java.io.*;
import java.net.*;
public class server2
{
public static void main(String args[])throws IOException
{
int Serverport=3001,clientport=3000;
DatagramSocket ds;
DatagramPacket p;
byte buffer[]=new byte[100];
ds=new DatagramSocket(Serverport);
p=new DatagramPacket(buffer,buffer.length);
BufferedReader dis=new BufferedReader(new InputStreamReader(System.in));
System.out.println("server started");
System.out.println("Type\"end\"to exit");
InetAddress ia=InetAddress.getByName("localhost");
while(true)
{
String str=dis.readLine();
if(str==null||str.equals("end"))
{
buffer=str.getBytes();
ds.send(new DatagramPacket(buffer,str.length(),ia,clientport));
break;
}
buffer=str.getBytes();
ds.send(new DatagramPacket(buffer,str.length(),ia,clientport));
ds.receive(p);
String s=new String(p.getData(),0,p.getLength());
if(s.equals("end"))
break;
else
System.out.println(s);
}
}
}
|
package com.gaoshin.onsalelocal.osl.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
import common.db.entity.DbEntity;
@Entity
@Table
@XmlRootElement
public class StoreComment extends DbEntity {
@Column(nullable = true, length = 64)
private String storeId;
@Column(nullable = true, length = 64)
private String userId;
@Column(nullable = true, length = 64)
private String content;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getStoreId() {
return storeId;
}
public void setStoreId(String storeId) {
this.storeId = storeId;
}
}
|
package com.git.cloud.openstack.model;
public enum OpenstackManageEnum {
OPENSTACK_MANAGE_USER("OPENSTACK_MANAGE_USER"),
OPENSTACK_MANAGE_PWD("OPENSTACK_MANAGE_PWD"),
OPENSTACK_MANAGE_PROJECT("OPENSTACK_MANAGE_PROJECT"),
OPENSTACK_MANAGE_DOMAIN("OPENSTACK_MANAGE_DOMAIN"),
OPENSTACK_MANAGE_ROLE("OPENSTACK_MANAGE_ROLE"),
OPENSTACK_PV_MANAGE_USER("OPENSTACK_PV_MANAGE_USER"),
OPENSTACK_PV_MANAGE_PWD("OPENSTACK_PV_MANAGE_PWD"),
OPENSTACK_PV_MANAGE_PROJECT("OPENSTACK_PV_MANAGE_PROJECT"),
OPENSTACK_PV_MANAGE_DOMAIN("OPENSTACK_PV_MANAGE_DOMAIN"),
OPENSTACK_MANAGE_USER_SC ("OPENSTACK_MANAGE_USER_SC"),
OPENSTACK_MANAGE_PWD_SC ("OPENSTACK_MANAGE_PWD_SC"),
OPENSTACK_MANAGE_PROJECT_ID_SC ("OPENSTACK_MANAGE_PROJECT_ID_SC"),
OPENSTACK_MANAGE_DOMAIN_NAME_SC ("OPENSTACK_MANAGE_DOMAIN_NAME_SC"),
OPENSTACK_MANAGE_DOMAIN_SC ("OPENSTACK_MANAGE_DOMAIN_SC"),
OPENSTACK_MANAGE_PROJECT_ID ("OPENSTACK_MANAGE_PROJECT_ID"),
//6.3 SC运营管理员(创建规格使用)
OPENSTACK_MANAGE_SYS_USER_SC ("OPENSTACK_MANAGE_SYS_USER_SC"),
OPENSTACK_MANAGE_SYS_PWD_SC ("OPENSTACK_MANAGE_SYS_PWD_SC"),
OPENSTACK_MANAGE_SYS_PROJECT_NAME_SC ("OPENSTACK_MANAGE_SYS_PROJECT_NAME_SC"),
OPENSTACK_MANAGE_SYS_DOMAIN_SC ("OPENSTACK_MANAGE_SYS_DOMAIN_SC"),
OPENSTACK_PHY_NET ("OPENSTACK_PHY_NET");
private final String value;
public String getValue() {
return value;
}
private OpenstackManageEnum(String value) {
this.value = value;
}
public static OpenstackManageEnum fromString(String value ) {
if (value != null) {
for (OpenstackManageEnum openstackManageEnum : OpenstackManageEnum.values()) {
if (value.equalsIgnoreCase(openstackManageEnum.value)) {
return openstackManageEnum;
}
}
}
return null;
}
}
|
package nh.automation.tools.entity;
/**
* 项目 :UI自动化测试 SSM 类描述:
* 测试数据管理
* @author Eric
* @date 2017年3月11日 nh.automation.tools.common
*/
public class WsDataManger {
private int caseId;
private String apiName;
private String apiHost;
private String apiType;
private String apiParameter;
private String expectResult;
private String executedResult;
private String executedStatus;
private int executedCode;
private String apiDese;
private String runTime;
private String reason;
private String parameterType;
private String depend;
private int dependStatus;
public String getMongoDbQuery() {
return mongoDbQuery;
}
public void setMongoDbQuery(String mongoDbQuery) {
this.mongoDbQuery = mongoDbQuery;
}
public String getRunTimeRequest() {
return runTimeRequest;
}
public void setRunTimeRequest(String runTimeRequest) {
this.runTimeRequest = runTimeRequest;
}
public String getRunTimeResponse() {
return runTimeResponse;
}
public void setRunTimeResponse(String runTimeResponse) {
this.runTimeResponse = runTimeResponse;
}
public String getMongoDbQueryResult() {
return mongoDbQueryResult;
}
public void setMongoDbQueryResult(String mongoDbQueryResult) {
this.mongoDbQueryResult = mongoDbQueryResult;
}
private String mongoDbQuery;
private String runTimeRequest;
private String runTimeResponse;
private String mongoDbQueryResult;
public int getCaseId() {
return caseId;
}
public void setCaseId(int caseId) {
this.caseId = caseId;
}
public String getApiName() {
return apiName;
}
public void setApiName(String apiName) {
this.apiName = apiName;
}
public String getApiHost() {
return apiHost;
}
public void setApiHost(String apiHost) {
this.apiHost = apiHost;
}
public String getApiParameter() {
return apiParameter;
}
public void setApiParameter(String apiParameter) {
this.apiParameter = apiParameter;
}
public String getExpectResult() {
return expectResult;
}
public void setExpectResult(String expectResult) {
this.expectResult = expectResult;
}
public String getApiDese() {
return apiDese;
}
public void setApiDese(String apiDese) {
this.apiDese = apiDese;
}
public int getExecutedCode() {
return executedCode;
}
public void setExecutedCode(int executedCode) {
this.executedCode = executedCode;
}
public String getApiType() {
return apiType;
}
public void setApiType(String apiType) {
this.apiType = apiType;
}
public String getRunTime() {
return runTime;
}
public void setRunTime(String runTime) {
this.runTime = runTime;
}
public String getReason() {
return reason;
}
public void setReason(String reason) {
this.reason = reason;
}
public String getExecutedResult() {
return executedResult;
}
public void setExecutedResult(String executedResult) {
this.executedResult = executedResult;
}
public String getExecutedStatus() {
return executedStatus;
}
public void setExecutedStatus(String executedStatus) {
this.executedStatus = executedStatus;
}
public String getParameterType() {
return parameterType;
}
public void setParameterType(String parameterType) {
this.parameterType = parameterType;
}
public String getDepend() {
return depend;
}
public void setDepend(String depend) {
this.depend = depend;
}
public int getDependStatus() {
return dependStatus;
}
public void setDependStatus(int dependStatus) {
this.dependStatus = dependStatus;
}
@Override
public String toString() {
return "CaseManger [caseId=" + caseId + ", apiName=" + apiName + ", apiHost=" + apiHost + ", apiType=" + apiType
+ ", apiParameter=" + apiParameter + ", expectResult=" + expectResult + ", executedResult=" + executedResult
+ ", executedResult=" + executedResult+ ", apiDese=" + apiDese + ", runTime=" + runTime + ", reason=" + reason
+ "]";
}
}
|
/*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.beans;
import java.util.Map;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.lang.Nullable;
/**
* Common interface for classes that can access named properties
* (such as bean properties of an object or fields in an object).
*
* <p>Serves as base interface for {@link BeanWrapper}.
*
* @author Juergen Hoeller
* @since 1.1
* @see BeanWrapper
* @see PropertyAccessorFactory#forBeanPropertyAccess
* @see PropertyAccessorFactory#forDirectFieldAccess
*/
public interface PropertyAccessor {
/**
* Path separator for nested properties.
* Follows normal Java conventions: getFoo().getBar() would be "foo.bar".
*/
String NESTED_PROPERTY_SEPARATOR = ".";
/**
* Path separator for nested properties.
* Follows normal Java conventions: getFoo().getBar() would be "foo.bar".
*/
char NESTED_PROPERTY_SEPARATOR_CHAR = '.';
/**
* Marker that indicates the start of a property key for an
* indexed or mapped property like "person.addresses[0]".
*/
String PROPERTY_KEY_PREFIX = "[";
/**
* Marker that indicates the start of a property key for an
* indexed or mapped property like "person.addresses[0]".
*/
char PROPERTY_KEY_PREFIX_CHAR = '[';
/**
* Marker that indicates the end of a property key for an
* indexed or mapped property like "person.addresses[0]".
*/
String PROPERTY_KEY_SUFFIX = "]";
/**
* Marker that indicates the end of a property key for an
* indexed or mapped property like "person.addresses[0]".
*/
char PROPERTY_KEY_SUFFIX_CHAR = ']';
/**
* Determine whether the specified property is readable.
* <p>Returns {@code false} if the property doesn't exist.
* @param propertyName the property to check
* (may be a nested path and/or an indexed/mapped property)
* @return whether the property is readable
*/
boolean isReadableProperty(String propertyName);
/**
* Determine whether the specified property is writable.
* <p>Returns {@code false} if the property doesn't exist.
* @param propertyName the property to check
* (may be a nested path and/or an indexed/mapped property)
* @return whether the property is writable
*/
boolean isWritableProperty(String propertyName);
/**
* Determine the property type for the specified property,
* either checking the property descriptor or checking the value
* in case of an indexed or mapped element.
* @param propertyName the property to check
* (may be a nested path and/or an indexed/mapped property)
* @return the property type for the particular property,
* or {@code null} if not determinable
* @throws PropertyAccessException if the property was valid but the
* accessor method failed
*/
@Nullable
Class<?> getPropertyType(String propertyName) throws BeansException;
/**
* Return a type descriptor for the specified property:
* preferably from the read method, falling back to the write method.
* @param propertyName the property to check
* (may be a nested path and/or an indexed/mapped property)
* @return the property type for the particular property,
* or {@code null} if not determinable
* @throws PropertyAccessException if the property was valid but the
* accessor method failed
*/
@Nullable
TypeDescriptor getPropertyTypeDescriptor(String propertyName) throws BeansException;
/**
* Get the current value of the specified property.
* @param propertyName the name of the property to get the value of
* (may be a nested path and/or an indexed/mapped property)
* @return the value of the property
* @throws InvalidPropertyException if there is no such property or
* if the property isn't readable
* @throws PropertyAccessException if the property was valid but the
* accessor method failed
*/
@Nullable
Object getPropertyValue(String propertyName) throws BeansException;
/**
* Set the specified value as current property value.
* @param propertyName the name of the property to set the value of
* (may be a nested path and/or an indexed/mapped property)
* @param value the new value
* @throws InvalidPropertyException if there is no such property or
* if the property isn't writable
* @throws PropertyAccessException if the property was valid but the
* accessor method failed or a type mismatch occurred
*/
void setPropertyValue(String propertyName, @Nullable Object value) throws BeansException;
/**
* Set the specified value as current property value.
* @param pv an object containing the new property value
* @throws InvalidPropertyException if there is no such property or
* if the property isn't writable
* @throws PropertyAccessException if the property was valid but the
* accessor method failed or a type mismatch occurred
*/
void setPropertyValue(PropertyValue pv) throws BeansException;
/**
* Perform a batch update from a Map.
* <p>Bulk updates from PropertyValues are more powerful: This method is
* provided for convenience. Behavior will be identical to that of
* the {@link #setPropertyValues(PropertyValues)} method.
* @param map a Map to take properties from. Contains property value objects,
* keyed by property name
* @throws InvalidPropertyException if there is no such property or
* if the property isn't writable
* @throws PropertyBatchUpdateException if one or more PropertyAccessExceptions
* occurred for specific properties during the batch update. This exception bundles
* all individual PropertyAccessExceptions. All other properties will have been
* successfully updated.
*/
void setPropertyValues(Map<?, ?> map) throws BeansException;
/**
* The preferred way to perform a batch update.
* <p>Note that performing a batch update differs from performing a single update,
* in that an implementation of this class will continue to update properties
* if a <b>recoverable</b> error (such as a type mismatch, but <b>not</b> an
* invalid field name or the like) is encountered, throwing a
* {@link PropertyBatchUpdateException} containing all the individual errors.
* This exception can be examined later to see all binding errors.
* Properties that were successfully updated remain changed.
* <p>Does not allow unknown fields or invalid fields.
* @param pvs a PropertyValues to set on the target object
* @throws InvalidPropertyException if there is no such property or
* if the property isn't writable
* @throws PropertyBatchUpdateException if one or more PropertyAccessExceptions
* occurred for specific properties during the batch update. This exception bundles
* all individual PropertyAccessExceptions. All other properties will have been
* successfully updated.
* @see #setPropertyValues(PropertyValues, boolean, boolean)
*/
void setPropertyValues(PropertyValues pvs) throws BeansException;
/**
* Perform a batch update with more control over behavior.
* <p>Note that performing a batch update differs from performing a single update,
* in that an implementation of this class will continue to update properties
* if a <b>recoverable</b> error (such as a type mismatch, but <b>not</b> an
* invalid field name or the like) is encountered, throwing a
* {@link PropertyBatchUpdateException} containing all the individual errors.
* This exception can be examined later to see all binding errors.
* Properties that were successfully updated remain changed.
* @param pvs a PropertyValues to set on the target object
* @param ignoreUnknown should we ignore unknown properties (not found in the bean)
* @throws InvalidPropertyException if there is no such property or
* if the property isn't writable
* @throws PropertyBatchUpdateException if one or more PropertyAccessExceptions
* occurred for specific properties during the batch update. This exception bundles
* all individual PropertyAccessExceptions. All other properties will have been
* successfully updated.
* @see #setPropertyValues(PropertyValues, boolean, boolean)
*/
void setPropertyValues(PropertyValues pvs, boolean ignoreUnknown)
throws BeansException;
/**
* Perform a batch update with full control over behavior.
* <p>Note that performing a batch update differs from performing a single update,
* in that an implementation of this class will continue to update properties
* if a <b>recoverable</b> error (such as a type mismatch, but <b>not</b> an
* invalid field name or the like) is encountered, throwing a
* {@link PropertyBatchUpdateException} containing all the individual errors.
* This exception can be examined later to see all binding errors.
* Properties that were successfully updated remain changed.
* @param pvs a PropertyValues to set on the target object
* @param ignoreUnknown should we ignore unknown properties (not found in the bean)
* @param ignoreInvalid should we ignore invalid properties (found but not accessible)
* @throws InvalidPropertyException if there is no such property or
* if the property isn't writable
* @throws PropertyBatchUpdateException if one or more PropertyAccessExceptions
* occurred for specific properties during the batch update. This exception bundles
* all individual PropertyAccessExceptions. All other properties will have been
* successfully updated.
*/
void setPropertyValues(PropertyValues pvs, boolean ignoreUnknown, boolean ignoreInvalid)
throws BeansException;
}
|
package httpServer;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.net.InetAddress;
import java.net.UnknownHostException;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
public class HttpWindow extends JFrame {
private static final long serialVersionUID = 1L;
public HttpWindow(int port) {
// IPアドレスの取得
String ip_addr = "N/A";
try {
ip_addr = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
e.printStackTrace();
}
// このJFrame(ウィンドウ)の設定
this.setSize(470, 200);
this.setLocationRelativeTo(null);
this.setTitle("About HTTP Server");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// パネル用のTitleBorderの設定
TitledBorder t = new TitledBorder("About HTTP Server");
t.setTitleFont(new Font("", Font.PLAIN, 20));
CompoundBorder in_border = new CompoundBorder(t, new EmptyBorder(10,10,10,10));
CompoundBorder border = new CompoundBorder(new EmptyBorder(20,20,20,20), in_border);
// パネルの設定
JPanel p = new JPanel();
p.setBackground(Color.WHITE);
p.setOpaque(true);
p.setBorder(border);
p.setLayout(new GridLayout(3, 2));
p.add(new JLabel("IP Address"));
p.add(new JTextField(ip_addr) {
private static final long serialVersionUID = 1L;
{
this.setHorizontalAlignment(CENTER);
this.setEditable(false);
}
});
p.add(new JLabel("Listener PORT"));
p.add(new JTextField("" + port) {
private static final long serialVersionUID = 1L;
{
this.setHorizontalAlignment(CENTER);
this.setEditable(false);
}
});
p.add(new JLabel("Open with Browser"));
p.add(new JTextField("http://"+ ip_addr +":" + port) {
private static final long serialVersionUID = 1L;
{
this.setHorizontalAlignment(CENTER);
this.setEditable(false);
}
});
this.setLayout(new BorderLayout());
this.add(p, BorderLayout.CENTER);
this.setVisible(true);
}
}
|
package tradingmaster.model;
import java.time.LocalDateTime;
public interface ITradeStore {
Long getMaxTradeId(IMarket market);
void persistTrades(TradeBatch batch);
TradeBatch loadTrades(String exchange, String market, LocalDateTime start, LocalDateTime endDate);
}
|
package com.git.cloud.resmgt.compute.dao;
import java.util.HashMap;
import java.util.List;
import com.git.cloud.common.dao.ICommonDAO;
import com.git.cloud.common.exception.RollbackableBizException;
import com.git.cloud.resmgt.common.model.po.CmHostPo;
import com.git.cloud.resmgt.common.model.po.RmDatacenterPo;
import com.git.cloud.resmgt.common.model.vo.IpRuleInfoVo;
import com.git.cloud.resmgt.compute.model.po.DuPoByRmHost;
import com.git.cloud.resmgt.compute.model.vo.CloudServiceVoByRmHost;
import com.git.cloud.resmgt.compute.model.vo.IpRules;
import com.git.cloud.resmgt.compute.model.vo.VmVo;
public interface IRmHostDao extends ICommonDAO {
public void saveVm(VmVo vm) throws RollbackableBizException;
public List <IpRules> getIpRules(VmVo vm );
public List<CloudServiceVoByRmHost> getCloudServices(VmVo vm) ;
public boolean checkVmIsExist(String vmName);
public List<DuPoByRmHost> getDuList(VmVo vm);
public boolean checkDataStore(String dataStoreName,String hostId);
public HashMap<String, String> findDatastoreId(String dataStoreName, String hostId);
public HashMap<String, String> findDeviceInfoByHostId(String hostId);
public List<IpRuleInfoVo> findIpRuleInfoByHostIdAndCloSerId(String hostId,String cloudService);
public RmDatacenterPo findDatacenterInfoByHostId(String hostId);
public List<DuPoByRmHost> getDuListNoServiceId();
}
|
package com.awss3.awss3;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.Bucket;
import com.amazonaws.services.s3.model.S3Object;
import com.amazonaws.services.s3.model.S3ObjectInputStream;
import com.amazonaws.services.s3.model.S3ObjectSummary;
@CrossOrigin
@RestController
public class Awss3restController {
Regions clientRegion = Regions.US_EAST_1;
String BUCKETNAME = "ec2logs-bucket";
String KEY = "log/auth.log";
String ACCESS_KEY = "access_ey";
String SECRET_KEY = "secret_key";
@GetMapping("/buckets")
public ResponseEntity<String> listBuckets(HttpServletRequest httpServletRequest) {
BasicAWSCredentials cred = new BasicAWSCredentials(ACCESS_KEY, SECRET_KEY);
AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
.withRegion(clientRegion)
.withCredentials(new AWSStaticCredentialsProvider(cred))
.build();
List<Bucket> listBuckets = s3Client.listBuckets();
listBuckets.forEach(buc -> {
System.out.println(buc.getName());
});
return null;
}
@GetMapping("/keys")
public ResponseEntity<String> listKeys() {
BasicAWSCredentials cred = new BasicAWSCredentials(ACCESS_KEY, SECRET_KEY);
AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
.withRegion(clientRegion)
.withCredentials(new AWSStaticCredentialsProvider(cred))
.build();
List<S3ObjectSummary> objectSummaries = s3Client.listObjects(BUCKETNAME).getObjectSummaries();
objectSummaries.forEach(objs -> {
System.out.println(objs.getKey());
});
return null;
}
@GetMapping("/download")
public ResponseEntity<String> downloadObject() throws IOException {
BasicAWSCredentials cred = new BasicAWSCredentials(ACCESS_KEY, SECRET_KEY);
AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
.withRegion(clientRegion)
.withCredentials(new AWSStaticCredentialsProvider(cred))
.build();
S3Object object = s3Client.getObject(BUCKETNAME, KEY);
displayTextInputStream(object.getObjectContent());
return null;
}
private static void displayTextInputStream(InputStream input) throws IOException {
// Read the text input stream one line at a time and display each line.
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
System.out.println();
}
}
|
package zzt.dao;
import global.dao.Databaseconnection;
import global.model.Classroom;
import global.model.Office;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import zzt.model.Zzt_Teacher_login;
import zzt.view.Zzt_JIF_Classroom;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
public class Zzt_Classroom_access {
public static ArrayList<Classroom> getClassroom(String d_id) throws SQLException,
ClassNotFoundException {
// 生成查找“Office”表的select查询语句
String sql = "SELECT * FROM classroom";
// 如果传入的部门编号不为空,则SQL语句添加查找条件为根据部门编号查找“Office”视图数据
if (!(d_id == null || d_id.equals(""))) {
sql += " WHERE d_id='" + d_id + "'";
}
// 初始化“Office”类的数组列表对象
ArrayList<Classroom> Classroomlist = new ArrayList<Classroom>();
// 取得数据库的连接
java.sql.Connection con = Databaseconnection.getconnection();
// 如果数据库的连接为空,则返回空
if (con == null)
return null;
// 生成数据库声明对象
Statement st = (Statement) con.createStatement();
// 声明对象执行SQL语句,返回满足条件的结果集
ResultSet rs = st.executeQuery(sql);
// 如果结果集有数据
while (rs.next()) {
// private int cr_id;
// private String d_id;
// private String cr_name;
// private int ct_id;
// private int cr_seating;
// private int b_id;
int cr_id=rs.getInt("cr_id");
String cr_name = rs.getString("cr_name");
d_id=rs.getString("d_id");
int ct_id=rs.getInt("ct_id");
int cr_seating = rs.getInt("cr_seating");
int b_id=rs.getInt("b_id");
// String b_name = rs.getString("b_name");
// String b_alias = rs.getString("b_alias");
// String b_address = rs.getString("b_address");
// int cr_seating = rs.getInt("cr_seating");
// String d_name = rs.getString("d_name");
// 根据结果集的数据生成“Office”类对象
Classroom of = new Classroom(cr_id, d_id, cr_name, ct_id, cr_seating, b_id);
// 将“Office”类对象添加到“Office”类的数组列表对象中
Classroomlist.add(of);
}
// 返回“View_teacher”类的数组列表对象
return Classroomlist;
}
}
|
package com.motondon.threadpoolexecutordemoapp.view;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.NavUtils;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import com.motondon.threadpoolexecutordemoapp.R;
import com.motondon.threadpoolexecutordemoapp.common.Constants;
import com.motondon.threadpoolexecutordemoapp.service.DummyService;
public class CurrentTestActivity extends AppCompatActivity {
private static final String TAG = CurrentTestActivity.class.getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_current_test);
Fragment fragment = getSupportFragmentManager().findFragmentByTag(CurrentTestFragment.TAG);
if (fragment == null) {
Intent i = getIntent();
if (i == null) {
throw new IllegalStateException("This should never happen. Expect NUMBER_OF_REQUESTED_TASKS parameter.");
}
fragment = new CurrentTestFragment();
// Pass args from the MainFragment to the CurrentTestFragment. There is no need to extract it, just pass it along.
fragment.setArguments(i.getExtras());
getSupportFragmentManager().beginTransaction().replace(R.id.current_test_activity_container_id, fragment, CurrentTestFragment.TAG).commit();
}
// Code to enable Up/Home button on the status bar
android.support.v7.app.ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.d(TAG, "onOptionsItemSelected");
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
// Call DummyService by passing DESTROY action. This will call stopSelf()
Intent i = new Intent(getApplicationContext(), DummyService.class);
i.setAction(Constants.DESTROY);
startService(i);
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
} |
public class HRCommunicator {
public static String developersName = "Pawel";
// Declare the important constants!
public static final String GREAT_COMPANY = "Toast";
public static final String LOCATION = "Dublin (see: Merrion Square, Pearse Street DART station)";
public static final String COMPANY_TYPE = "all-in-one Restaurant Management and POS system";
public static final String[] CHALLENGES = {
"scaling", "data synchronization",
"payment processing", "wi-fi networking"};
public static final String YOUR_NEW_ROLE = "Senior Engineer on a team of 3-5 engineers";
public static final String[] TECH_STACK = {
"Java", "Android", "microservices", "AWS",
"with HTML, Angular, React, ES6 on the front end"};
public static final int SMALL_DRAMATIC_PAUSE = 2000; //time in ms
public static final int LARGE_DRAMATIC_PAUSE = 3000;
public static void main(String[] args) {
if(args.length==1){
developersName = args[0];
}
System.out.format("Hey There, %s!\n",developersName);
System.out.println("Recruiters often suck at connecting with engineers..."
+ "so I thought I would try speaking your language!");
HRCommunicator hrComm = new HRCommunicator();
hrComm.startSpiel();
}
/**
* Method to run through the spiel
*/
public void startSpiel(){
dramaticPause(2000);
spielWriter
(
"\nThe important 0's & 1's",
LARGE_DRAMATIC_PAUSE,
true
);
spielWriter
(
GREAT_COMPANY+" is an "+COMPANY_TYPE,
LARGE_DRAMATIC_PAUSE,
true
);
spielWriter
(
"We are conveniently located in "+LOCATION,
LARGE_DRAMATIC_PAUSE,
true
);
spielWriter
(
"The role we are looking to fill is for a "+YOUR_NEW_ROLE,
LARGE_DRAMATIC_PAUSE,
true
);
spielWriter
(
"\nWe are looking for someone who can help us be great at: ",
LARGE_DRAMATIC_PAUSE,
false
);
stringArrayWriter(CHALLENGES);
spielWriter
(
"Our tech stack is: ",
LARGE_DRAMATIC_PAUSE,
false
);
stringArrayWriter(TECH_STACK);
spielWriter
(
"Our success thus far has included gaining "
+ "venture capital funding, customers in all 50 states and adoption "
+ "by lots of restaurants great and small.\n",
LARGE_DRAMATIC_PAUSE,
true
);
spielWriter
(
"Interested in hearing more? Suggest a few times that you're available "
+ "for a quick conversation. I’d be happy to fill you in on us and our open roles.",
LARGE_DRAMATIC_PAUSE,
true
);
}
/**
* Method for printing out the contents of String arrays to the console
* @param arrayToWrite
*/
public void stringArrayWriter(String[] arrayToWrite){
for(int arrayIndex=0; arrayIndex<arrayToWrite.length; arrayIndex++){
spielWriter(arrayToWrite[arrayIndex], SMALL_DRAMATIC_PAUSE, false);
if(arrayIndex+1<arrayToWrite.length-1){
System.out.print(", ");
}
else if(arrayIndex+1 == arrayToWrite.length-1){
System.out.print(" and ");
}
else{
System.out.println(".");
}
}
}
/**
* Method for printing out awesome info to the console
* @param message
* @param pause
* @param newLine
*/
public void spielWriter(String message, int pause, boolean newLine){
if(newLine==true){
System.out.println(message);
}
else{
System.out.print(message);
}
if(pause>0 && pause<10000){
dramaticPause(pause);
}
}
/**
* Method for delaying the inevitable
* @param delayTime
*/
public void dramaticPause(int delayTime){
try {
Thread.sleep(delayTime);
} catch (InterruptedException e) {
System.out.println("You interrupted my dramatic pause!");
}
}
} |
package by.vsu;
public class StringChecker {
public static boolean checkBalance(String str){
int balanceCounter = 0;
for(char ch : str.toCharArray()){
if(ch == '('){
balanceCounter++;
}
if(ch == ')'){
balanceCounter--;
}
if(balanceCounter < 0){
return false;
}
}
if(balanceCounter != 0)return false;
return true;
}
}
|
package com.emg.projectsmanage.auth;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.security.web.authentication.session.SessionAuthenticationException;
import org.springframework.stereotype.Component;
@Component
public class AuthenticationFailHander extends SimpleUrlAuthenticationFailureHandler {
private static final Logger logger = Logger.getLogger(AuthenticationFailHander.class);
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
AuthenticationException exception) {
String strUrl = request.getContextPath() + "/login.jsp?login_error=%d";
Integer errorCode = -1;
try {
if (exception instanceof UsernameNotFoundException) {
errorCode = 1;
} else if (exception instanceof BadCredentialsException) {
errorCode = 2;
} else if (exception instanceof SessionAuthenticationException) {
errorCode = 3;
} else if (exception instanceof DisabledException) {
errorCode = 4;
} else {
logger.error(exception.getMessage(), exception);
}
response.sendRedirect(String.format(strUrl, errorCode));
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
}
|
package com.cc.cocktail.mvc.controller.sample;
import javax.annotation.Resource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import com.cc.cocktail.mvc.controller.base.BaseController;
import com.cc.cocktail.mvc.service.sample.SampleService;
/**
* @Type: sampleController.java
* @Desc:
* @author bielu
* @date Jul 11, 2017 11:07:58 AM
* @version V1.0
*/
@RestController
@RequestMapping("/sample")
public class SampleController extends BaseController{
@Resource(name = "sampleService")
SampleService sampleService;
@RequestMapping("/sample")
public Object sample() {
ModelAndView view = new ModelAndView("sample/sample");
Object data = sampleService.getNameById(1);
view.addObject("data", data);
return view;
}
}
|
package com.esum.comp.sap3.server;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.esum.comp.sap3.SAPCode;
import com.esum.comp.sap3.SAPConfig;
import com.esum.comp.sap3.SAPException;
import com.esum.comp.sap3.handler.SAPFunctionHandler;
import com.esum.comp.sap3.table.SAPFunctionInfoRecord;
import com.esum.comp.sap3.table.SAPFunctionInfoTable;
import com.esum.comp.sap3.table.SAPIfInfoRecord;
import com.esum.comp.sap3.util.SAPUtil;
import com.esum.framework.core.component.ComponentException;
import com.esum.framework.core.component.config.ComponentConfigFactory;
import com.esum.framework.core.component.table.InfoTableManager;
import com.sap.conn.jco.AbapClassException;
import com.sap.conn.jco.AbapException;
import com.sap.conn.jco.JCoFunction;
import com.sap.conn.jco.server.JCoServerContext;
import com.sap.conn.jco.server.JCoServerFunctionHandler;
public class DefaultJCoServerFunctionHandler implements JCoServerFunctionHandler {
private Logger log = LoggerFactory.getLogger(DefaultJCoServerFunctionHandler.class);
private String traceId;
private SAPFunctionInfoTable sapFunctionInfoTable;
private SAPFunctionHandler functionHandler;
private SAPIfInfoRecord sapIfInfoRecord;
private SAPFunctionInfoRecord functionInfoRecord;
public DefaultJCoServerFunctionHandler(String traceId,
SAPFunctionHandler functionHandler) throws ComponentException {
this.traceId = traceId;
this.sapFunctionInfoTable = (SAPFunctionInfoTable)InfoTableManager.getInstance().getInfoTable(SAPConfig.SAP_FUNCTION_INFO_TABLE_ID);
this.functionHandler = functionHandler;
}
public SAPFunctionInfoRecord getFunctionInfoRecord() {
return functionInfoRecord;
}
public void setFunctionInfoRecord(SAPFunctionInfoRecord functionInfoRecord) {
this.functionInfoRecord = functionInfoRecord;
}
public SAPIfInfoRecord getSapIfInfoRecord() {
return sapIfInfoRecord;
}
public void setSapIfInfoRecord(SAPIfInfoRecord sapIfInfoRecord) {
this.sapIfInfoRecord = sapIfInfoRecord;
}
@Override
public void handleRequest(JCoServerContext serverCtx, JCoFunction function) throws AbapException, AbapClassException {
if(log.isDebugEnabled()) {
log.debug(traceId+"----------------------------------------------------------------");
log.debug(traceId+"call : " + function.getName());
log.debug(traceId+"ConnectionId : " + serverCtx.getConnectionID());
log.debug(traceId+"SessionId : " + serverCtx.getSessionID());
log.debug(traceId+"TID : " + serverCtx.getTID());
log.debug(traceId+"repository name : " + serverCtx.getRepository().getName());
log.debug(traceId+"is in transaction : " + serverCtx.isInTransaction());
log.debug(traceId+"is stateful : " + serverCtx.isStatefulSession());
log.debug(traceId+"----------------------------------------------------------------");
log.debug(traceId+"gwhost: " + serverCtx.getServer().getGatewayHost());
log.debug(traceId+"gwserv: " + serverCtx.getServer().getGatewayService());
log.debug(traceId+"progid: " + serverCtx.getServer().getProgramID());
log.debug(traceId+"----------------------------------------------------------------");
log.debug(traceId+"attributes : ");
log.debug(traceId+serverCtx.getConnectionAttributes().toString());
log.debug(traceId+"----------------------------------------------------------------");
log.debug(traceId+"CPIC conversation ID: " + serverCtx.getConnectionAttributes().getCPICConversationID());
log.debug(traceId+"----------------------------------------------------------------");
}
log.info(traceId+"Called Remote Function by SAP. function : " + function.getName());
String dataBuffer = null;
if(!functionInfoRecord.getSapFunctionName().equals(function.getName())) {
try {
functionInfoRecord = (SAPFunctionInfoRecord)sapFunctionInfoTable.getSapFunctionInfoByFunctionName(function.getName());
if (functionInfoRecord == null)
throw new SAPException(SAPCode.ERROR_NOT_FOUND_SAPFUNCTIONINFO, "handleRequest()",
"There is no SAP Function Info for Function name "+function.getName());
} catch (Exception e) {
log.error(traceId+"Unknown Exception occured in Receiving data from SAP.", e);
return;
}
}
try {
//SAPFunctionInfoRecord 에서 테이블 리스트 정보(SAP_TABLES) 추출
if(log.isDebugEnabled())
log.debug(traceId+"RFC table List : " + functionInfoRecord.getSapTables());
List<String> tableList = SAPUtil.getTokenList(functionInfoRecord.getSapTables(), "|", true);
// handle receive (2015.12.16 - kim.ryeowon)
dataBuffer = functionHandler.handleReceive(function, tableList);
if (dataBuffer == null || dataBuffer.length() == 0)
throw new SAPException(SAPCode.ERROR_SAP_DATA_PROCESS, "handleRequest()", "Received data is NULL.");
} catch (SAPException e) {
log.error(traceId+"SAPException occured in Receiving data from SAP. "+e.getMessage());
return;
} catch (Exception e) {
log.error(traceId+"Unknown Exception occured in Receiving data from SAP.", e);
return;
}
try {
SAPConfig sapConfig = (SAPConfig)ComponentConfigFactory.getInstance(SAPConfig.MODULE_ID);
String msgRecvStatus = sapConfig.getReqMsgInputStatus();
//Make Data list
// TODO : encoding ??
byte[] payload = dataBuffer.toString().getBytes();
log.info(traceId+"Processing Received Data From SAP Start.");
SAPOutboundHandler outboundHandler = new SAPOutboundHandler(
SAPConfig.MODULE_ID, sapIfInfoRecord, payload, msgRecvStatus);
outboundHandler.process();
} catch (ComponentException e) {
log.error(traceId+"ComponentException occured in Processing received data.", e);
} catch (Exception e) {
log.error(traceId+"Unknown exception occured in Processing received data.", e);
}
log.info(traceId+"Remote Function Processing Completed. function : " + function.getName());
}
}
|
package bnogent.m.actions;
import bnogent.m.Calc;
import bnogent.m.CalcBase;
public class AddChiffreAction extends PersoAction {
private int i;
protected int index;
public AddChiffreAction(Calc.StateEnum _prevState, Calc.StateEnum _next,CalcBase calcBase, int i, int index, String methodString) {
super(_prevState, _next, calcBase,methodString);
this.index = index;
this.i = i;
}
@Override
public void exec() {
super.exec();
if (index==1)
calcBase.add1(i);
if (index==2)
calcBase.add2(i);
}
@Override
public void rollback() {
super.rollback();
calcBase.remove();
}
}
|
//
// DO NOT EDIT THIS FILE, IT HAS BEEN GENERATED USING AndroidAnnotations.
//
package org.sayesaman.tut4.path;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import com.googlecode.androidannotations.api.SdkVersionHelper;
import com.viewpagerindicator.TabPageIndicator;
import org.sayesaman.R.id;
import org.sayesaman.R.layout;
import org.sayesaman.database.dao.SalePathDao_;
public final class PageViewActivity_
extends PageViewActivity
{
@Override
public void onCreate(Bundle savedInstanceState) {
init_(savedInstanceState);
super.onCreate(savedInstanceState);
setContentView(layout.tut4_page);
}
private void init_(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(android.view.WindowManager.LayoutParams.FLAG_FULLSCREEN, android.view.WindowManager.LayoutParams.FLAG_FULLSCREEN);
dao = SalePathDao_.getInstance_(this);
}
private void afterSetContentView_() {
tut4_indicator = ((TabPageIndicator) findViewById(id.tut4_indicator));
tut4_viewpager = ((ViewPager) findViewById(id.tut4_viewpager));
((SalePathDao_) dao).afterSetContentView_();
xx();
}
@Override
public void setContentView(int layoutResID) {
super.setContentView(layoutResID);
afterSetContentView_();
}
@Override
public void setContentView(View view, android.view.ViewGroup.LayoutParams params) {
super.setContentView(view, params);
afterSetContentView_();
}
@Override
public void setContentView(View view) {
super.setContentView(view);
afterSetContentView_();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (((SdkVersionHelper.getSdkInt()< 5)&&(keyCode == KeyEvent.KEYCODE_BACK))&&(event.getRepeatCount() == 0)) {
onBackPressed();
}
return super.onKeyDown(keyCode, event);
}
public static PageViewActivity_.IntentBuilder_ intent(Context context) {
return new PageViewActivity_.IntentBuilder_(context);
}
public static class IntentBuilder_ {
private Context context_;
private final Intent intent_;
public IntentBuilder_(Context context) {
context_ = context;
intent_ = new Intent(context, PageViewActivity_.class);
}
public Intent get() {
return intent_;
}
public PageViewActivity_.IntentBuilder_ flags(int flags) {
intent_.setFlags(flags);
return this;
}
public void start() {
context_.startActivity(intent_);
}
public void startForResult(int requestCode) {
if (context_ instanceof Activity) {
((Activity) context_).startActivityForResult(intent_, requestCode);
} else {
context_.startActivity(intent_);
}
}
}
}
|
package control.developSystem.developerAspect.developInsurance;
import java.awt.event.ActionEvent;
import control.DynamicSystem;
import control.developSystem.DevelopSystem;
import control.developSystem.developerAspect.showInsurance.SelecInsuranceToWatchControl;
import view.insuranceSystemView.developView.developer.developInsurance.DevelopInsuranceSelectView;
import view.panel.BasicPanel;
public class DevelopeInsuranceSelectControl extends DevelopSystem {
@Override
public BasicPanel getView() {return new DevelopInsuranceSelectView(this.actionListener);}
@Override
public DynamicSystem processEvent(ActionEvent e) {
switch (DevelopInsuranceSelectView.EActionCommands.valueOf(e.getActionCommand())) {
case CarInsurance : return new DevelopCarInsuranceControl();
case DiseaseInsurance : return new DevelopDiseaseInsuranceControl();
case FireInsurance : return new DevelopFireInsuranceControl();
case InsuranceDesign : return new DevelopeInsuranceSelectControl();
case WatchInsuranceData : return new SelecInsuranceToWatchControl();
}
return null;
}
}
|
package com.wenyuankeji.spring.controller;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.wenyuankeji.spring.model.BaseAdmininfoModel;
import com.wenyuankeji.spring.model.BaseBusinessareaModel;
import com.wenyuankeji.spring.model.BaseCityModel;
import com.wenyuankeji.spring.model.BaseDistrictModel;
import com.wenyuankeji.spring.model.BaseProvinceModel;
import com.wenyuankeji.spring.model.StorePhotoMappingModel;
import com.wenyuankeji.spring.model.StoreinfoModel;
import com.wenyuankeji.spring.model.UserWalletModel;
import com.wenyuankeji.spring.service.IBaseBusinessareaService;
import com.wenyuankeji.spring.service.IBaseCityService;
import com.wenyuankeji.spring.service.IBaseDistrictService;
import com.wenyuankeji.spring.service.IBaseProvinceService;
import com.wenyuankeji.spring.service.IStorePhotoMappingService;
import com.wenyuankeji.spring.service.IStoreinfoService;
import com.wenyuankeji.spring.service.IUserWalletService;
import com.wenyuankeji.spring.util.BaseException;
import com.wenyuankeji.spring.util.MD5Util;
@Controller
public class StoreinfoController {
@Autowired
private IStoreinfoService storeinfoService;
@Autowired
private IStorePhotoMappingService storePhotoMappingService;
@Autowired
private IBaseProvinceService baseProvinceService;
@Autowired
private IBaseCityService baseCityService;
@Autowired
private IBaseDistrictService baseDistrictService;
@Autowired
private IBaseBusinessareaService baseBusinessareaService;
@Autowired
private IUserWalletService userWalletService;
/************ 管理端 ************/
@RequestMapping("goStoreinfoManage")
/**
* 跳转美发店登录
*
* @param request
* @param model
* @return
*/
public String goStoreinfoManage(HttpServletRequest request, Model model) {
HttpSession session = request.getSession();
BaseAdmininfoModel userinfo = (BaseAdmininfoModel) session.getAttribute("sessionUserinfo");
if(userinfo != null){
return "storeinfo_manage";
}else{
return "login";
}
}
@RequestMapping("StoreinfoManage")
/**
* 获取商户列表
* @param request
* @param model
* @param storeid
* @param startTime
* @param endTime
* @param state
* @param name
* @param page
* @param rows
* @return
* @throws BaseException
*/
public @ResponseBody Map<String, Object> StoreinfoManage(HttpServletRequest request, Model model,
String storeid, String startTime, String endTime, String state,String name, String page, String rows)
throws BaseException {
// 定义map
Map<String, Object> jsonMap = new HashMap<String, Object>();
// 当前页
int intPage = Integer.parseInt((page == null || page == "0") ? "1" : page);
// 每页显示条数
int intRows = Integer.parseInt((rows == null || rows == "0") ? "10" : rows);
List<StoreinfoModel> storeinfoModels = storeinfoService.searchStoreinfo(storeid, startTime, endTime, state, name, intPage, intRows);
// 存放总记录数,必须的
jsonMap.put("total", storeinfoService.searchStoreinfoCount(storeid, startTime, endTime, state, name));
// rows键 存放每页记录 list
jsonMap.put("rows", storeinfoModels);
return jsonMap;
}
@RequestMapping("StoreinfoUpdateState")
/**
* 修改用户状态
* @param model
* @return
*/
public @ResponseBody Map<String, Object> StoreinfoUpdateState(int storeid, int state,
Model model, HttpSession session) {
Map<String, Object> editInfoMap = new HashMap<String, Object>();
// 构造实体
StoreinfoModel storeinfoModel = new StoreinfoModel();
storeinfoModel.setStoreid(storeid);
storeinfoModel.setState(state);
if (storeinfoService.updateStoreinfoModel(storeinfoModel)) {
editInfoMap.put("editInfo", true);
editInfoMap.put("message", "审核状态修改成功!");
} else {
editInfoMap.put("editInfo", false);
editInfoMap.put("message", "审核状态修改失败!");
}
return editInfoMap;
}
@RequestMapping("initStoreInfo")
/**
* 商户生成
* @param model
* @return
*/
public @ResponseBody Map<String, Object> initStoreInfo(
Model model, HttpSession session) throws Exception {
Map<String, Object> editInfoMap = new HashMap<String, Object>();
// 构造实体
StoreinfoModel storeinfoModel = new StoreinfoModel();
int randomName = (int) (Math.random() * 1000000);
int randomPass = (int) (Math.random() * 1000000);
String defaultUserName = String.valueOf(randomName);
String defaultPassword = String.valueOf(randomPass);
storeinfoModel.setUsername(defaultUserName);//默认用户名为12345678900
storeinfoModel.setPassword(MD5Util.Encryption(defaultPassword));//默认密码为123456
storeinfoModel.setCreatetime(new Date()); //创建时间
storeinfoModel.setState(0);//默认未审核状态
int result = storeinfoService.addInitStoreinfo(storeinfoModel);
if (result > 0) {
//生成钱包
UserWalletModel o = new UserWalletModel();
o.setOwnerid(result);
o.setBalance(0);
//3商户
o.setOwnertype(3);
o.setCreatetime(new Date());
o.setUpdatetime(new Date());
//添加钱包
userWalletService.addUserWallet(o);
editInfoMap.put("editInfo", true);
editInfoMap.put("message", "初始化成功!用户名:" + defaultUserName
+ "密码:" + defaultPassword);
} else {
editInfoMap.put("editInfo", false);
editInfoMap.put("message", "初始化失败!");
}
return editInfoMap;
}
@RequestMapping("/getBaseProvinces")
/**
* 查询所有省份
* @param model
* @return
*/
public @ResponseBody Map<String, Object> getBaseProvinces(Model model,
HttpSession session) throws BaseException {
Map<String, Object> baseProvinceMap = new HashMap<String, Object>();
List<BaseProvinceModel> baseProvinceList = baseProvinceService
.searchBaseProvince();
BaseProvinceModel baseProvinceModel = new BaseProvinceModel();
baseProvinceModel.setProvinceid(0);
baseProvinceModel.setProvincename("请选择");
baseProvinceList.add(0, baseProvinceModel);
baseProvinceMap.put("selInfo", true);
baseProvinceMap.put("baseProvinceList", baseProvinceList);
return baseProvinceMap;
}
@RequestMapping("/getBaseBusinessareas/{city_id}")
/**
* 查根据城市ID询商圈
* @param model
* @return
*/
public @ResponseBody Map<String, Object> getBaseBusinessareas(
@PathVariable int city_id, Model model, HttpSession session)
throws BaseException {
List<BaseBusinessareaModel> baseBusinessareaList = baseBusinessareaService
.searchBaseBusinessarea(city_id);
Map<String, Object> baseBusinessareaMap = new HashMap<String, Object>();
BaseBusinessareaModel baseBusinessareaModel = new BaseBusinessareaModel();
baseBusinessareaModel.setAreaid(0);
baseBusinessareaModel.setAreaname("请选择");
baseBusinessareaList.add(0, baseBusinessareaModel);
baseBusinessareaMap.put("selInfo", true);
baseBusinessareaMap.put("baseBusinessareaList", baseBusinessareaList);
return baseBusinessareaMap;
}
@RequestMapping("/getBaseCitys/{province_id}")
/**
* 根据省份ID查询城市
* @param model
* @return
*/
public @ResponseBody Map<String, Object> getProfessions(
@PathVariable int province_id, Model model, HttpSession session)
throws BaseException {
List<BaseCityModel> baseCityList = baseCityService
.searchBaseCityByProvinceId(province_id);
Map<String, Object> baseCityMap = new HashMap<String, Object>();
BaseCityModel baseCityModel = new BaseCityModel();
baseCityModel.setCityid(0);
baseCityModel.setCityname("请选择");
baseCityList.add(0, baseCityModel);
baseCityMap.put("selInfo", true);
baseCityMap.put("baseCityList", baseCityList);
return baseCityMap;
}
@RequestMapping("/getBaseDistricts/{city_id}")
/**
* 根据城市ID查询区县
* @param model
* @return
*/
public @ResponseBody Map<String, Object> getBaseDistricts(
@PathVariable int city_id, Model model, HttpSession session)
throws BaseException {
List<BaseDistrictModel> baseDistrictList = baseDistrictService
.searchBaseDistrictByCityId(city_id);
Map<String, Object> baseDistrictMap = new HashMap<String, Object>();
BaseDistrictModel baseDistrictModel = new BaseDistrictModel();
baseDistrictModel.setCityid(0);
baseDistrictModel.setDistrictname("请选择");
baseDistrictList.add(0, baseDistrictModel);
baseDistrictMap.put("selInfo", true);
baseDistrictMap.put("baseDistrictList", baseDistrictList);
return baseDistrictMap;
}
/**
* 初始化页面数据
*
* @param request
* @param model
* @return
*/
public void setPageData(StoreinfoModel storeinfo, Model model)
throws BaseException {
// 省份
List<BaseProvinceModel> baseProvinceList = baseProvinceService
.searchBaseProvince();
BaseProvinceModel baseProvinceModel = new BaseProvinceModel();
baseProvinceModel.setProvinceid(0);
baseProvinceModel.setProvincename("请选择");
baseProvinceList.add(0, baseProvinceModel);
model.addAttribute("baseProvinceList", baseProvinceList);
model.addAttribute("provinceid", storeinfo.getProvinceid());
// 城市
List<BaseCityModel> baseCityList = baseCityService
.searchBaseCityByProvinceId(storeinfo.getProvinceid());
BaseCityModel baseCityModel = new BaseCityModel();
baseCityModel.setCityid(0);
baseCityModel.setCityname("请选择");
baseCityList.add(0, baseCityModel);
model.addAttribute("baseCityList", baseCityList);
model.addAttribute("cityid", storeinfo.getCityid());
// 区县
List<BaseDistrictModel> baseDistrictList = baseDistrictService
.searchBaseDistrictByCityId(storeinfo.getCityid());
BaseDistrictModel baseDistrictModel = new BaseDistrictModel();
baseDistrictModel.setCityid(0);
baseDistrictModel.setDistrictname("请选择");
baseDistrictList.add(0, baseDistrictModel);
model.addAttribute("baseDistrictList", baseDistrictList);
model.addAttribute("districtid", storeinfo.getDistrictid());
// 商圈
List<BaseBusinessareaModel> baseBusinessareaList = baseBusinessareaService
.searchBaseBusinessarea(storeinfo.getCityid());
BaseBusinessareaModel baseBusinessareaModel = new BaseBusinessareaModel();
baseBusinessareaModel.setAreaid(0);
baseBusinessareaModel.setAreaname("请选择");
baseBusinessareaList.add(0, baseBusinessareaModel);
model.addAttribute("baseBusinessareaList", baseBusinessareaList);
model.addAttribute("areaid", storeinfo.getAreaid());
// 营业时间
String businesshours = storeinfo.getBusinesshours();
if (businesshours != null && businesshours != "") {
String businesshoursStr[] = storeinfo.getBusinesshours().split("-");
String businesshoursStart = businesshoursStr[0].toString();
String businesshoursEnd = businesshoursStr[1].toString();
// 开始营业时间
model.addAttribute("businesshoursStart", businesshoursStart);
// 结束营业时间
model.addAttribute("businesshoursEnd", businesshoursEnd);
} else {
// 默认开始营业时间
model.addAttribute("businesshoursStart", "09:00");
// 默认营业时间
model.addAttribute("businesshoursEnd", "09:00");
}
StorePhotoMappingModel storePhotoMapping1 = storePhotoMappingService
.searchStorePhoto(storeinfo.getStoreid(), 3);
StorePhotoMappingModel storePhotoMapping2 = storePhotoMappingService
.searchStorePhoto(storeinfo.getStoreid(), 1);
StorePhotoMappingModel storePhotoMapping3 = storePhotoMappingService
.searchStorePhoto(storeinfo.getStoreid(), 2);
if (storePhotoMapping1 != null) {
model.addAttribute("fileName1", storePhotoMapping1.getBasePicture()
.getPicturepath());
} else {
model.addAttribute("fileName1", "images/defaultAvatar.png");
}
if (storePhotoMapping2 != null) {
model.addAttribute("fileName2", storePhotoMapping2.getBasePicture()
.getPicturepath());
} else {
model.addAttribute("fileName2", "images/defaultAvatar.png");
}
if (storePhotoMapping3 != null) {
model.addAttribute("fileName3", storePhotoMapping3.getBasePicture()
.getPicturepath());
} else {
model.addAttribute("fileName3", "images/defaultAvatar.png");
}
}
@RequestMapping("goStoreinfoValidateInfo/{storeid}")
/**
* 跳转美发店验证信息
* @param request
* @param model
* @return
*/
public String goStoreinfoValidateInfo(HttpServletRequest request,
Model model, @PathVariable int storeid) throws NumberFormatException, BaseException {
StoreinfoModel storeinfo = storeinfoService.searchStoreinfoModel(storeid);
setPageData(storeinfo, model);
model.addAttribute("storeinfo", storeinfo);
return "storeinfo_validateinfo";
}
@RequestMapping("/StoreinfoValidateInfo")
/**
* 美发店验证信息
* @param request
* @param model
* @param storeName 商户名称
* @param provinceid 省份ID
* @param cityid 城市ID
* @param districtid 区ID
* @param address 地址
* @param tel 电话
* @param carnumber 车位数
* @param businesshours 营业时间
* @param areaid 商圈ID
* @param empiricalmode 经营方式
* @param intro 简介
* @param bossname 负责人名字
* @param bossmobile 负责人手机
* @param storemanagername 店长名字
* @param storemanagermobile 店长手机
* @return
*/
public String StoreinfoValidateInfo(HttpServletRequest request,
Model model,String storeid, String storeName, String provinceid, String cityid,
String districtid, String address, String tel, String carnumber,
String businesshoursStart, String businesshoursEnd, String areaid,
String empiricalmode, String intro, String bossname,
String bossmobile, String storemanagername,
String storemanagermobile, String longitude, String latitude,
String ownername, String bank, String cardnumber, String fileName1,
String fileName2, String fileName3, String state, String allocation)
throws BaseException, IOException {
String storeId = storeid;
String serverPath = request.getServletContext()
.getRealPath("/userImg/");
if (!"images/defaultAvatar.png".equals(fileName1)) {
// 保存商户经营执照
if (!storePhotoMappingService.addOrUpdImg(
Integer.parseInt(storeId), 3, fileName1, serverPath)) {
model.addAttribute("message", "商户经营执照,更新失败");
}
}
if (!"images/defaultAvatar.png".equals(fileName2)) {
// 保存商户正面照
if (!storePhotoMappingService.addOrUpdImg(
Integer.parseInt(storeId), 1, fileName2, serverPath)) {
model.addAttribute("message", "商户正面照,更新失败");
}
}
if (!"images/defaultAvatar.png".equals(fileName3)) {
// 保存店内照
if (!storePhotoMappingService.addOrUpdImg(
Integer.parseInt(storeId), 2, fileName3, serverPath)) {
model.addAttribute("message", "店内照,更新失败");
}
}
// 构造店铺
StoreinfoModel storeinfo = new StoreinfoModel();
storeinfo.setStoreid(Integer.parseInt(storeId));
storeinfo.setName(storeName);
storeinfo.setProvinceid(Integer.parseInt(provinceid));
storeinfo.setCityid(Integer.parseInt(cityid));
storeinfo.setDistrictid(Integer.parseInt(districtid));
storeinfo.setAddress(address);
storeinfo.setTel(tel);
if (carnumber.equals("")) {
storeinfo.setCarnumber(0);
} else {
storeinfo.setCarnumber(Integer.parseInt(carnumber));
}
storeinfo.setBusinesshours(businesshoursStart + "-" + businesshoursEnd);
storeinfo.setAreaid(Integer.parseInt(areaid));
storeinfo.setEmpiricalmode(Integer.parseInt(empiricalmode));
storeinfo.setIntro(intro);
storeinfo.setBossname(bossname);
storeinfo.setBossmobile(bossmobile);
storeinfo.setStoremanagername(storemanagername);
storeinfo.setStoremanagermobile(storemanagermobile);
storeinfo.setLatitude(latitude);
storeinfo.setLongitude(longitude);
storeinfo.setOwnername(ownername);
storeinfo.setBank(bank);
storeinfo.setCardnumber(cardnumber);
storeinfo.setState(Integer.parseInt(state));
storeinfo.setAllocation(allocation);
// 美发店信息更新
if (storeinfoService.updateStore(storeinfo)) {
// 绑定页面数据
setPageData(storeinfo, model);
model.addAttribute("storeinfo", storeinfo);
model.addAttribute("message", "保存成功!");
} else {
model.addAttribute("message", "保存失败!");
}
return "storeinfo_validateinfo";
}
} |
package ehwaz.problem_solving.algorithm.greedy.maxsubarrray;
import java.io.*;
import java.util.*;
/**
* Created by Sangwook on 2016-05-06.
*/
public class MaxSubArray {
public static void solve(Scanner sc) {
int valNum = Integer.parseInt(sc.nextLine());
int start = 0;
int end = 0;
int curVal;
StringTokenizer st = new StringTokenizer(sc.nextLine(), " ");
int maxSoFar = Integer.parseInt(st.nextToken());
int maxEndingHere = maxSoFar;
for (int valCnt = 1; valCnt < valNum; valCnt++) {
curVal = Integer.parseInt(st.nextToken());
// Subproblem: maximum subarray of 0 ~ N is maximum subarray of 0 ~ (N-1) or,
// (value in N) + (maximum subarray ends in index N-1).
if (curVal < maxEndingHere + curVal) {
maxEndingHere = maxEndingHere + curVal;
} else {
maxEndingHere = curVal;
if (maxSoFar < maxEndingHere) {
start = valCnt;
}
}
if (maxSoFar < maxEndingHere) {
maxSoFar = maxEndingHere;
end = valCnt;
}
}
System.out.println("MaxVal: " + maxSoFar + ", Idx: " + start + " to " + end);
}
public static void runSolution(InputStream istream) {
Scanner sc = new Scanner(istream);
int testNum = Integer.parseInt(sc.nextLine());
for (int testCnt = 0; testCnt < testNum; testCnt++) {
solve(sc);
}
}
public static void main(String[] args) {
runSolution(System.in);
}
}
|
package com.coop.model;
public class FlagStatus {
private String ga_transaction_no;
private String ga_sender_accno;
private String ga_receiver_accno;
private String ga_transfer_amount;
private String ga_flag_status;
public String getGa_transaction_no() {
return ga_transaction_no;
}
public void setGa_transaction_no(String ga_transaction_no) {
this.ga_transaction_no = ga_transaction_no;
}
public String getGa_sender_accno() {
return ga_sender_accno;
}
public void setGa_sender_accno(String ga_sender_accno) {
this.ga_sender_accno = ga_sender_accno;
}
public String getGa_receiver_accno() {
return ga_receiver_accno;
}
public void setGa_receiver_accno(String ga_receiver_accno) {
this.ga_receiver_accno = ga_receiver_accno;
}
public String getGa_transfer_amount() {
return ga_transfer_amount;
}
public void setGa_transfer_amount(String ga_transfer_amount) {
this.ga_transfer_amount = ga_transfer_amount;
}
public String getGa_flag_status() {
return ga_flag_status;
}
public void setGa_flag_status(String ga_flag_status) {
this.ga_flag_status = ga_flag_status;
}
}
|
package com.darwinsys.roomdemo;
import android.arch.persistence.room.ColumnInfo;
import android.arch.persistence.room.Entity;
import android.arch.persistence.room.Ignore;
import android.arch.persistence.room.PrimaryKey;
import java.time.LocalDate;
@Entity
public class Expense {
@PrimaryKey(autoGenerate = true)
long id;
@ColumnInfo()
String date;
@ColumnInfo()
String description;
@ColumnInfo()
double amount;
public Expense() {
// empty
}
@Ignore
public Expense(LocalDate date, String description, double amount) {
this.date = date.toString();
this.description = description;
this.amount = amount;
}
@Ignore
public Expense(String date, String description, double amount) {
this.date = date;
LocalDate nDate;
this.description = description;
this.amount = amount;
}
@Ignore
public Expense(String description, double amount) {
this(LocalDate.now().toString(), description, amount);
}
public String toString() {
return String.format("%s %22s %.2f", date, description, amount);
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public void setDate(LocalDate date) {
this.date = date.toString();
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public double getAmount() {
return amount;
}
public void setAmount(double amount) {
this.amount = amount;
}
}
|
/*
* Copyright (c) 2020 Be The Match operated by National Marrow Donor Program (NMDP).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the License for
* the specific language governing permissions and limitations under the License.
*/
package org.nmdp.converter;
import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.parser.IParser;
import org.hl7.fhir.dstu3.model.*;
import org.json.*;
import java.util.ArrayList;
import java.util.List;
/**
* Parses the input bundle and manages generation of transaction bundle
*/
public class ParseInputBundle
{
/**
* Input JSONObject bundle
*/
private JSONObject myInputBundle;
/**
* String format of Fhir bundle
*/
private String myFhirOutput;
public String getMyFhirOutput() {
return myFhirOutput;
}
public void setMyFhirOutput(String myFhirOutput) {
this.myFhirOutput = myFhirOutput;
}
public JSONObject getMyInputBundle() {
return myInputBundle;
}
public void setMyInputBundle(JSONObject myInputBundle) {
this.myInputBundle = myInputBundle;
}
/**
* Parse input bundle
*/
public void parseInput() {
JSONArray aEntries = myInputBundle.getJSONArray("entry");
extractResources(aEntries);
}
/**
* Extract Resources from input bundle entries
* @param theEntries
*/
public void extractResources(JSONArray theEntries)
{
List<DomainResource> aDomainResources = new ArrayList<>();
FhirContext ctx = FhirContext.forDstu3();
IParser aParser = ctx.newJsonParser();
BundleGenerator aBG = new BundleGenerator();
for (int index = 0; index < theEntries.length(); index++)
{
JSONObject aEntry = theEntries.getJSONObject(index);
JSONObject aResource = (aEntry.keySet().contains("resource")) ? aEntry.getJSONObject("resource") : null;
DomainResource aDR = getFhirResource(aResource != null ? aResource : aEntry, aParser);
aDomainResources.add(aDR);
}
aBG.generateFhirBundle(aDomainResources);
setMyFhirOutput(ctx.newJsonParser().setPrettyPrint(true).encodeResourceToString(aBG.getMyBundleResource().getMyFhirBundle()));
}
/**
* Get FHIR DomainResource for each resource type
* @param theResource
* @param theParser
* @return
*/
private DomainResource getFhirResource(JSONObject theResource, IParser theParser)
{
switch(theResource.getString("resourceType"))
{
case "Observation" :
return theParser.parseResource(Observation.class, theResource.toString());
case "Patient" :
return theParser.parseResource(Patient.class, theResource.toString());
case "Provenance" :
return theParser.parseResource(Provenance.class, theResource.toString());
case "Device" :
return theParser.parseResource(Device.class, theResource.toString());
case "ValueSet":
return theParser.parseResource(ValueSet.class, theResource.toString());
case "CodeSystem":
return theParser.parseResource(CodeSystem.class, theResource.toString());
default:
return theParser.parseResource(DomainResource.class, theResource.toString());
}
}
}
|
package com.sandy.example.pilgrimService;
import com.sandy.example.pilgrimService.models.Outing;
import com.sandy.example.pilgrimService.models.Pilgrim;
import com.sandy.example.pilgrimService.models.YellowTShirt;
import com.sandy.example.pilgrimService.repositories.OutingRepository;
import com.sandy.example.pilgrimService.repositories.PilgrimRepository;
import com.sandy.example.pilgrimService.repositories.YellowTShirtRepository.YellowTShirtRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest
public class PilgrimServiceApplicationTests {
@Autowired
YellowTShirtRepository yellowTShirtRepository;
@Autowired
PilgrimRepository pilgrimRepository;
@Autowired
OutingRepository outingRepository;
@Test
public void contextLoads() {
}
@Test
public void canCreateAndSaveHelper(){
YellowTShirt yellowTShirt = new YellowTShirt("The Legend", "S");
yellowTShirtRepository.save(yellowTShirt);
}
@Test
public void canCreateAndSavePilgrim() {
Pilgrim pilgrim = new Pilgrim("Bert", 201);
pilgrimRepository.save(pilgrim);
}
@Test
public void canCreateAndSaveOuting() {
YellowTShirt yellowTShirt = new YellowTShirt("The Legend", "S");
yellowTShirtRepository.save(yellowTShirt);
Pilgrim pilgrim = new Pilgrim("Bert", 201);
pilgrimRepository.save(pilgrim);
Outing outing = new Outing(pilgrim);
outingRepository.save(outing);
outing.addYellowTShirt(yellowTShirt);
outingRepository.save(outing);
}
@Test
public void canReturnPilgrimAfterOuting() {
YellowTShirt yellowTShirt = new YellowTShirt("The Legend", "S");
yellowTShirtRepository.save(yellowTShirt);
Pilgrim pilgrim = new Pilgrim("Bert", 201);
pilgrimRepository.save(pilgrim);
Outing outing = new Outing(pilgrim);
outingRepository.save(outing);
outing.addYellowTShirt(yellowTShirt);
outingRepository.save(outing);
outing.markReturned();
outingRepository.save(outing);
}
@Test
public void canGetYellowTShirtsForGivenGroup() {
YellowTShirt legend = new YellowTShirt("The Legend", "S");
yellowTShirtRepository.save(legend);
YellowTShirt chief = new YellowTShirt("The Chief", "S");
yellowTShirtRepository.save(chief);
YellowTShirt jack = new YellowTShirt("Jack Jarvis", "D");
yellowTShirtRepository.save(jack);
YellowTShirt victor = new YellowTShirt("Victor McDade", "D");
yellowTShirtRepository.save(victor);
List<YellowTShirt> sGroup = yellowTShirtRepository.getYellowTShirtsForGroup("S");
}
}
|
package com.ranpeak.ProjectX.activity.lobby.forAuthorizedUsers.navigationFragment.profileNavFragment;
import android.Manifest;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.baoyz.widget.PullRefreshLayout;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.MultiplePermissionsReport;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.multi.MultiplePermissionsListener;
import com.ranpeak.ProjectX.R;
import com.ranpeak.ProjectX.activity.SettingsActivity;
import com.ranpeak.ProjectX.activity.editProfile.EditProfileActivity;
import com.ranpeak.ProjectX.activity.interfaces.Activity;
import com.ranpeak.ProjectX.activity.lobby.forAuthorizedUsers.navigationFragment.profileNavFragment.adapter.ProfileFragmentPagerAdapter;
import com.ranpeak.ProjectX.activity.lobby.forAuthorizedUsers.navigationFragment.profileNavFragment.viewModel.MyResumeViewModel;
import com.ranpeak.ProjectX.activity.lobby.forAuthorizedUsers.navigationFragment.profileNavFragment.viewModel.MyTaskViewModel;
import com.ranpeak.ProjectX.networking.IsOnline;
import com.ranpeak.ProjectX.networking.volley.Constants;
import com.ranpeak.ProjectX.networking.volley.request.VolleyMultipartRequest;
import com.ranpeak.ProjectX.settings.SharedPrefManager;
import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import de.hdodenhof.circleimageview.CircleImageView;
import io.reactivex.disposables.CompositeDisposable;
public class ProfileFragment extends Fragment implements Activity {
private View view;
private PullRefreshLayout swipeRefreshLayout;
private AppBarLayout appBarLayout;
private TabLayout tabLayout;
private ImageView editProfile;
private CircleImageView avatar;
private ImageView settings;
private ViewPager viewPager;
private TextView tasksCount;
private TextView resumesCount;
private MyTaskViewModel myTaskViewModel;
private MyResumeViewModel resumeViewModel;
// private View line;
private io.reactivex.disposables.CompositeDisposable mDisposable = new CompositeDisposable();
private final int[] imageResId = {
R.drawable.my_profile, R.drawable.my_task, R.drawable.my_resume
};
private int selectedTab = 0;
// user info
private TextView name;
private TextView login;
private TextView country;
private final int GALLERY = 1;
private RequestQueue rQueue;
private static final int REQUEST_PERMISSION = 200;
public ProfileFragment() {
}
@Override
public View onCreateView(@NotNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_profile, container, false);
findViewById();
typeRefresh();
onListener();
initData();
initFragments(viewPager);
requestMultiplePermissions();
// Спрашмвает пользователя разрешение на доступ к галерее(если он его не давал еще)
if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
REQUEST_PERMISSION);
}
return view;
}
@Override
public void findViewById() {
// line = view.findViewById(R.id.fragment_profile_view);
appBarLayout = view.findViewById(R.id.fragment_profile_main_appbar);
swipeRefreshLayout = view.findViewById(R.id.fragment_profile_swipeRefreshLayout);
tasksCount = view.findViewById(R.id.fragment_profile_task_count);
resumesCount = view.findViewById(R.id.fragment_profile_resumes_count);
viewPager = view.findViewById(R.id.fragment_profile_viewPager);
tabLayout = view.findViewById(R.id.fragment_profile_tabLayout);
editProfile = view.findViewById(R.id.fragment_profile_edit_profile);
settings = view.findViewById(R.id.fragment_profile_settings);
name = view.findViewById(R.id.fragment_profile_name);
login = view.findViewById(R.id.fragment_profile_login);
avatar = view.findViewById(R.id.fragment_profile_avatar);
country = view.findViewById(R.id.fragment_profile_country);
}
@Override
public void onListener() {
settings.setOnClickListener(v ->
startActivity(new Intent(getActivity(), SettingsActivity.class)));
editProfile.setOnClickListener(v ->
startActivity(new Intent(getActivity(), EditProfileActivity.class)));
avatar.setOnClickListener(v -> startActivityForResult(
new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI), GALLERY));
tabLayout.setupWithViewPager(viewPager);
swipeRefreshLayout.setOnRefreshListener(() -> {
// line.setVisibility(View.GONE);
final Handler handler = new Handler();
handler.postDelayed(() -> {
if (IsOnline.getInstance().isConnectingToInternet(Objects.requireNonNull(getContext()))) {
initData();
initFragments(viewPager);
} else {
Toast.makeText(getContext(), getString(R.string.no_internet), Toast.LENGTH_SHORT).show();
}
swipeRefreshLayout.setRefreshing(false);
// line.setVisibility(View.VISIBLE);
}, 1500);
});
appBarLayout.addOnOffsetChangedListener((appBarLayout, i) -> {
if ((appBarLayout.getHeight() - appBarLayout.getBottom()) != 0) {
selectedTab = tabLayout.getSelectedTabPosition();
swipeRefreshLayout.setEnabled(false);
} else {
swipeRefreshLayout.setEnabled(true);
}
});
}
private void typeRefresh() {
swipeRefreshLayout.setRefreshStyle(PullRefreshLayout.STYLE_SMARTISAN);
}
private void initData() {
myTaskViewModel = ViewModelProviders.of(this).get(MyTaskViewModel.class);
myTaskViewModel.getCountOfUsersTask(
String.valueOf(SharedPrefManager.getInstance(getContext()).getUserLogin())
).observe(this, integer -> {
tasksCount.setText(String.valueOf(integer));
});
resumeViewModel = ViewModelProviders.of(this).get(MyResumeViewModel.class);
resumeViewModel.getCountOfUsersResumes(
String.valueOf(SharedPrefManager.getInstance(getContext()).getUserLogin())
).observe(this, integer -> {
resumesCount.setText(String.valueOf(integer));
});
getSavedInfoAboutUser();
}
// Записывание данных о пользователе в нужные поля профиля
private void getSavedInfoAboutUser() {
login.setText(String.valueOf(SharedPrefManager.getInstance(getContext()).getUserLogin()));
name.setText(String.valueOf(SharedPrefManager.getInstance(getContext()).getUserName()));
country.setText(String.valueOf(SharedPrefManager.getInstance(getContext()).getUserCountry()));
avatar.setVisibility(View.VISIBLE);
if (!SharedPrefManager.getInstance(getContext()).getUserAvatar().equals("nullk")) {
byte[] decodedString = Base64.decode(String.valueOf(SharedPrefManager.getInstance(getContext()).getUserAvatar()), Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
avatar.setImageBitmap(decodedByte);
} else {
avatar.setVisibility(View.VISIBLE);
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == getActivity().RESULT_CANCELED) {
return;
}
if (requestCode == GALLERY) {
if (data != null) {
Uri contentURI = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContext().getContentResolver(), contentURI);
avatar.setImageBitmap(bitmap);
avatar.setVisibility(View.VISIBLE);
SharedPrefManager.getInstance(getContext()).userUpdateImage(encodeToBase64(bitmap));
uploadImage(bitmap);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getContext(), "Failed!", Toast.LENGTH_SHORT).show();
}
}
}
}
public static String encodeToBase64(Bitmap image) {
Bitmap image1 = image;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
image1.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);
Log.d("Image Log:", imageEncoded);
return imageEncoded;
}
// Преобразует картинку пользователя в массив байтов(для передачи на сервер)
public byte[] getFileDataFromDrawable(Bitmap bitmap) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 80, byteArrayOutputStream);
return byteArrayOutputStream.toByteArray();
}
// Запрашивает у пользователя разрешение на доступ к галерее
private void requestMultiplePermissions() {
Dexter.withActivity(getActivity())
.withPermissions(
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE)
.withListener(new MultiplePermissionsListener() {
@Override
public void onPermissionsChecked(MultiplePermissionsReport report) {
// check if all permissions are granted
if (report.areAllPermissionsGranted()) {
Toast.makeText(getContext(), "All permissions are granted by user!", Toast.LENGTH_SHORT).show();
}
// check for permanent denial of any permission
if (report.isAnyPermissionPermanentlyDenied()) {
// show alert dialog navigating to Settings
}
}
@Override
public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
token.continuePermissionRequest();
}
}).
withErrorListener(error ->
Toast.makeText(getContext(), "Some Error! ", Toast.LENGTH_SHORT).show())
.onSameThread()
.check();
}
// Запрос на загрузку, на сервер...
private void uploadImage(final Bitmap bitmap) {
VolleyMultipartRequest volleyMultipartRequest = new VolleyMultipartRequest(Request.Method.POST, Constants.URL.UPLOAD_AVATAR,
response -> {
Log.d("ressssssoo", new String(response.data));
rQueue.getCache().clear();
try {
JSONObject jsonObject = new JSONObject(new String(response.data));
Toast.makeText(getContext(), jsonObject.getString("message"), Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
},
error ->
Toast.makeText(getContext(), "Please on Internet", Toast.LENGTH_SHORT).show()) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("login", String.valueOf(SharedPrefManager.getInstance(getContext()).getUserLogin()));
return params;
}
@Override
protected Map<String, DataPart> getByteData() {
Map<String, DataPart> params = new HashMap<>();
long imageName = System.currentTimeMillis();
params.put("filename", new VolleyMultipartRequest.DataPart(imageName + ".png", getFileDataFromDrawable(bitmap)));
return params;
}
};
volleyMultipartRequest.setRetryPolicy(new DefaultRetryPolicy(
0,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
rQueue = Volley.newRequestQueue(getContext());
rQueue.add(volleyMultipartRequest);
}
private void initFragments(ViewPager viewPager) {
ProfileFragmentPagerAdapter adapter = new ProfileFragmentPagerAdapter(getFragmentManager());
viewPager.setAdapter(adapter);
for (int i = 0; i < imageResId.length; i++) {
Objects.requireNonNull(tabLayout.getTabAt(i)).setIcon(imageResId[i]);
}
}
}
|
package JPA_Mongo.tp3;
import java.util.List;
import org.bson.types.ObjectId;
import com.google.code.morphia.annotations.Embedded;
import com.google.code.morphia.annotations.Entity;
import com.google.code.morphia.annotations.Id;
@Entity("person")
public class Person {
@Id
private ObjectId id;
private String name;
@Embedded
private List<Address> address;
public Person() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Address> getAddress() {
return address;
}
public void setAddress(List<Address> address) {
this.address = address;
}
}
|
package in.jaaga.thebachaoproject;
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.RatingBar;
public class InfrastructureFragment extends Fragment {
private FragmentInfrastructureListener mListener;
RatingBar streetLighting;
RatingBar peopleAround;
EditText comments;
public InfrastructureFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_infrastructure, container, false);
streetLighting = (RatingBar) rootView.findViewById(R.id.rating_bar_street_lighting);
peopleAround = (RatingBar) rootView.findViewById(R.id.rating_bar_people_around);
comments = (EditText) rootView.findViewById(R.id.txt_comment_infra);
rootView.findViewById(R.id.btn_share_infra).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
postData();
}
});
return rootView;
}
private void postData() {
int street_lighting= (int) streetLighting.getRating();
int people_around= (int) peopleAround.getRating();
String comment = comments.getText().toString();
mListener.onInfrastructureFragmentInteraction(street_lighting,people_around,comment);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
//mListener.onInfrastructureFragmentInteraction(uri);
}
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (FragmentInfrastructureListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface FragmentInfrastructureListener {
// TODO: Update argument type and name
void onInfrastructureFragmentInteraction(int street_light,int people_around,String comments);
}
}
|
// Object 클래스 - clone() 사용법 III
package com.eomcs.corelib.ex01;
public class Exam0172 {
// 인스턴스 복제 기능을 활성화하려면 Cloneable 인터페이스를 구현해야 한다.
// => 이 인터페이스에는 메서드가 선언되어 있지 않다.
// => 따라서 클래스는 따로 메서드를 구현할 필요가 없다.
// => Cloneable을 구현하는 이유는
// JVM에게 이 클래스의 인스턴스를 복제할 수 있음을 표시하기 위함이다.
// 이 표시가 안된 클래스는 JVM이 인스턴스를 복제해 주지 않는다. 즉 clone()을 호출할 수 없다.
static class Score implements Cloneable {
String name;
int kor;
int eng;
int math;
int sum;
float aver;
public Score() {}
public Score(String name, int kor, int eng, int math) {
this.name = name;
this.kor = kor;
this.eng = eng;
this.math = math;
this.sum = this.kor + this.eng + this.math;
this.aver = this.sum / 3f;
}
@Override
public String toString() {
return "Score [name=" + name + ", kor=" + kor + ", eng=" + eng + ", math=" + math + ", sum="
+ sum + ", aver=" + aver + "]";
}
@Override
public Score clone() throws CloneNotSupportedException {
return (Score) super.clone();
}
}
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + Float.floatToIntBits(aver);
// result = prime * result + eng;
// result = prime * result + kor;
// result = prime * result + math;
// result = prime * result + ((name == null) ? 0 : name.hashCode());
// result = prime * result + sum;
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// Score other = (Score) obj;
// if (Float.floatToIntBits(aver) != Float.floatToIntBits(other.aver))
// return false;
// if (eng != other.eng)
// return false;
// if (kor != other.kor)
// return false;
// if (math != other.math)
// return false;
// if (name == null) {
// if (other.name != null)
// return false;
// } else if (!name.equals(other.name))
// return false;
// if (sum != other.sum)
// return false;
// return true;
// }
public static void main(String[] args) throws Exception {
Score s1 = new Score("홍길동", 100, 100, 100);
Score s2 = s1.clone(); // 이제 예외가 발생하지 않는다!
// 복제 실행 오류가 발생하지 않는 이유?
// => Score 클래스의 복제 기능을 활성화시켰기 때문이다.
// class Score implements Cloneable {...}
//
System.out.println(s1 == s2);
System.out.println(s1);
System.out.println(s2);
System.out.println(s1.equals(s2));
}
}
|
package com.example.cape_medics;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import org.json.JSONObject;
public class ItemsHanded extends Fragment {
ListView itemsHanded;
JSONObject itemsHandedOver;
public ItemsHanded(){}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_items_handed,container,false);
itemsHandedOver = new JSONObject();
itemsHanded = view.findViewById(R.id.items);
itemsHanded.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
String[] items = {"Refferal Letter", "X-Rays", "WCA Forms", "Medications", "Patient Valuables", "Cell-Phone",
"No items Handed Over"};
ArrayAdapter<String> ItemsAdapter = new ArrayAdapter<String>(getContext(),
R.layout.custom_checked_list,items);
itemsHanded.setAdapter(ItemsAdapter);
return view;
//add recording mechanism
}
public JSONObject createJson(){
itemsHandedOver = new JSONObject();
for (int i = 0; i < itemsHanded.getChildCount(); i++) {
if (itemsHanded.isItemChecked(i)){
try{
itemsHandedOver.put(itemsHanded.getItemAtPosition(i).toString(),itemsHanded.getItemAtPosition(i).toString());
}catch (Exception e){}
}
}
return itemsHandedOver;
}
public void skip(View v){
}
}
|
package cttd.cryptography.demo;
import org.junit.Test;
import static org.junit.Assert.*;
public class DesTests {
private String plaintext = "stackjava.com";
private String ciphertext = "xvHjRlZOjIxmi+R3h4/gUw==";
@Test
public void encryptTest() {
assertEquals(ciphertext, Des.encrypt(plaintext));
}
@Test
public void decryptTest() {
assertEquals(plaintext, Des.decrypt(ciphertext));
}
}
|
package com.lenovohit.ssm.payment.manager;
public abstract class WxpayManager implements PayBaseManager{
}
|
package com.rocktech.hospitalrms;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class UserReportAdapter extends RecyclerView.Adapter<UserReportAdapter.ViewHolder> {
private Context context;
private ArrayList <Report> reports;
public UserReportAdapter(Context context, ArrayList<Report> reports) {
this.context = context;
this.reports = reports;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.user_report, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, final int position) {
holder.txtDate.setText(reports.get(position).getReportDate());
holder.txtDesc.setText(reports.get(position).getReportDesc());
holder.txtAttendance.setText(reports.get(position).getAttendance());
holder.txtDiagnosis.setText(reports.get(position).getDiagnosis());
holder.txtTest.setText(reports.get(position).getTest());
holder.txtDrug.setText(reports.get(position).getDrug());
holder.txtOutcome.setText(reports.get(position).getOutcome());
}
@Override
public int getItemCount() {
return reports.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView txtDate,txtDesc,txtAttendance,txtDiagnosis,txtTest,txtDrug,txtOutcome;
public ViewHolder(@NonNull View itemView) {
super(itemView);
txtDesc = itemView.findViewById(R.id.textDesc);
txtDate = itemView.findViewById(R.id.textDate);
txtAttendance = itemView.findViewById(R.id.textAttendance);
txtDiagnosis = itemView.findViewById(R.id.textDiagnosis);
txtTest = itemView.findViewById(R.id.textTest);
txtDrug = itemView.findViewById(R.id.textDrug);
txtOutcome = itemView.findViewById(R.id.textOutcome);
}
}
}
|
import java.util.Scanner;
public class CalendarPrinter {
private final static String[] DAYS_OF_WEEK = {"MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN"};
private final static String[] MONTHS_OF_YEAR = {"JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP",
"OCT", "NOV", "DEC"};
/**
* Calculates the number of centuries (rounded down) that is represented by the
* specified year (ie. the integer part of year/100).
*
* @param year to compute the century of (based on the Gregorian Calendar AD)
* String must contain the digits of a single non-negative int for
* year.
* @return number of centuries in the specified year
*/
public static int getCentury(String year) {
return (int) Math.floor(Integer.parseInt(year) / 100);
}
/**
* Calculates the number of years between the specified year, and the first year
* in the specified year's century. This number is always between 0 - 99.
*
* @param year to compute the year within century of (Gregorian Calendar AD)
* String must contain the digits of a single non-negative int for
* year.
* @return number of years since first year in the current century
*/
public static int getYearWithinCentury(String year) {
return Integer.parseInt(year) % 100;
}
/**
* This method computes whether the specified year is a leap year or not.
*
* @param yearString is the year that is being checked for leap-years String
* must contain the digits of a single non-negativt for
* year.
* @return true when the specified year is a leap year, and false otherwise
*/
public static boolean getIsLeapYear(String yearString) {
// Note implementation tips in Appendix I below.
/////////////////////////Pseudocode for the leap year/////////////////////////
// if (year is not divisible by 4) then (it is a common year) //
// else if (year is not divisible by 100) then (it is a leap year) //
// else if (year is not divisible by 400) then (it is a common year) //
// else (it is a leap year) //
//////////////////////////////////////////////////////////////////////////////
int getYear = Integer.parseInt(yearString);
if (getYear % 4 != 0) {
return false; // common year
} else if (getYear % 100 != 0) {
return true; // leap year
} else if (getYear % 400 != 0) {
return false; // common year
} else {
return true; // leap year otherwise
}
}
/**
* Converts the name or abbreviation for any month into the index of that
* month's abbreviation within MONTHS_OF_YEAR. Matches the specified month based
* only on the first three characters, and is case in-sensitive.
*
* @param month which may or may not be abbreviated to 3 or more characters
* @return the index within MONTHS_OF_YEAR that a match is found at and returns
* -1, when no match is found
*/
public static int getMonthIndex(String month) {
String abbMon = month.substring(0, 3)/*.toUpperCase()*/;
for (int i = 0; i < MONTHS_OF_YEAR.length; i++) { // visit all the elements in the array
if (MONTHS_OF_YEAR[i].equalsIgnoreCase(abbMon)) { // [] for array, list;
return i;
}
}
return -1; // if MONTHS_OF_YEAR[i] != abbMon;
// for each??
// int count = 0;
// for(String mon : MONTHS_OF_YEAR) {
//
// if (mon.equalsIgnoreCase(abbMon)) {
// return count;
// }
// count++;
// }
}
/**
* Calculates the number of days in the specified month, while taking into
* consideration whether or not the specified year is a leap year.
*
* @param month which may or may not be abbreviated to 3 or more characters
* @param year of month that days are being counted for (Gregorian Calendar AD)
* String must contain the digits of a single non-negative int for
* year.
* @return the number of days in the specified month (between 28-31)
*/
public static int getNumberOfDaysInMonth(String month, String year) { // 31days: 1, 3, 5, 7, 8, 10, 12
// 30 days: 4, 6, 9, 11
// affected by leap year: 2
boolean isLeapYear = getIsLeapYear(year); // check if it is leap year or not
int monthIndex = getMonthIndex(month); // get a value = Mon - 1;
if (monthIndex == 0 || monthIndex == 2 || monthIndex == 4 || monthIndex == 6 || monthIndex == 7 || monthIndex == 9 || monthIndex == 11) {
return 31;
} else if (monthIndex == 1) { // check if it is February
if (isLeapYear) // check if it is a leap year or not
return 29; // because of the leap year
else
return 28;
} else {
return 30;
}
}
/**
* Calculates the index of the first day of the week in a specified month. The
* index returned corresponds to position of this first day of the week within
* the DAYS_OF_WEEK class field.
*
* @param month which may or may not be abbreviated to 3 or more characters
* @param year of month to determine the first day from (Gregorian Calendar AD)
* String must contain the digits of a single non-negative int for
* year.
* @return index within DAYS_OF_WEEK of specified month's first day
*/
public static int getFirstDayOfWeekInMonth(String month, String year) {
// Note implementation tips in Appendix I below.
int yearInt = Integer.parseInt(year);
int q = 1; // First day
int m; // The number of days in the month, 3 = March, 4 = April, 5 = May, ..., 14 = February
int checkMonthIndex = getMonthIndex(month);
if (checkMonthIndex < 2) {
m = checkMonthIndex + 13; // January = 13, February = 14
yearInt--; // For January and February, we need to check the previous year
}
else
m = checkMonthIndex + 1; // March = 3, April = 4, ..., December = 12
int k = getYearWithinCentury("" + yearInt); // the year of the century (year % 100)
int j = getCentury("" + yearInt); // the zero based century (year / 100)
// System.out.printf("m=%d, k=%d, j=%d%n", m, k, j);
// int daysOfTheWeek; // 0 = Saturday, 1 = Sunday, 2 = Monday, ..., 6 = Friday
// if (m < 13) // March to December
// daysOfTheWeek = (q + Math.floorDiv(13 * (m + 1), 5) + k + Math.floorDiv(k, 4) + Math.floorDiv(j, 4) + 5 * j) % 7;
// else // January and February
// daysOfTheWeek = (q + Math.floorDiv(13 * (m + 1), 5) + k - 1 + Math.floorDiv(k - 1, 4) + Math.floorDiv(j, 4) + 5 * j) % 7;
int daysOfTheWeek = (q + Math.floorDiv(13 * (m + 1), 5) + k + Math.floorDiv(k, 4) + Math.floorDiv(j, 4) + 5 * j) % 7;
// 0 = Saturday, 1 = Sunday, 2 = Monday, ..., 6 = Friday
return (daysOfTheWeek + 5) % 7; // 5 = Sat, 6 = Sun, 0 = Mon, ...
}
/**
* Creates and initializes a 2D String array to reflect the specified month. The
* first row of this array [0] should contain labels representing the days of
* the week, starting with Monday, as abbreviated in DAYS_OF_WEEK. Every later
* row should contain dates under the corresponding days of week. Entries with
* no corresponding date in the current month should be filled with a single
* period. There should not be any extra rows that are either blank, unused, or
* completely filled with periods. For example, the contents for September of
* 2019 should look as follows, where each horizontal row is stored in different
* array within the 2d result:
* <p>
* MON TUE WED THU FRI SAT SUN
* . . . . . . 1
* 2 3 4 5 6 7 8
* 9 10 11 12 13 14 15
* 16 17 18 19 20 21 22
* 23 24 25 26 27 28 29
* 30 . . . . . .
*
* @param month which may or may not be abbreviated to 3 or more characters
* @param year of month generate calendar for (Gregorian Calendar AD) String
* must contain the digits of a single non-negative int for year.
* @return 2d array of strings depicting the contents of a calendar
*/
public static String[][] generateCalendar(String month, String year) {
int firstDate = getFirstDayOfWeekInMonth(month, year);
int lastDay = getNumberOfDaysInMonth(month, year);
String[][] calendar;
if (firstDate > 5/*Only Sunday*/ && lastDay >= 30) {
calendar = new String[7][7];
} else if (firstDate > 4/*Saturday*/ && lastDay >= 31) {
calendar = new String[7][7];
} else if(!getIsLeapYear(year) && getMonthIndex(month) == 1 && firstDate == 0) { // Not leap year, February, started from monday
calendar = new String[5][7];
} else {
calendar = new String[6][7];
}
for (int i = 0; i < DAYS_OF_WEEK.length; i++) { // fill the first line
calendar[0][i] = DAYS_OF_WEEK[i];
}
int days = 1;
for (int i = 1; i < calendar.length; i++) {
for (int j = 0; j < calendar[0].length; j++){
if (i == 1 && j < firstDate) { // before the day 1
calendar[i][j] = ".";
} else if (days > getNumberOfDaysInMonth(month, year)) { // after the max day i.e. after 31
calendar[i][j] = ".";
} else {
calendar[i][j] = "" + days;
days++;
}
}
}
return calendar;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to the Calendar Printer.");
System.out.println("================================");
System.out.println("Enter the month to print: ");
String month = sc.next();
System.out.println("Enter the year to print: ");
String year = sc.next();
String[][] calendar = generateCalendar(month, year);
for (int i = 0; i < calendar.length; i++) {
for (int j = 0; j < calendar[0].length; j++) {
if (calendar[i][j].length() == 1) {
System.out.printf(" %s ", calendar[i][j]);
} else if (calendar[i][j].length() == 2) {
System.out.printf(" %s ", calendar[i][j]);
} else {
System.out.printf("%s ", calendar[i][j]);
}
}
System.out.println();
}
}
} |
package dev.sim0n.caesium.mutator.impl.crasher;
import dev.sim0n.caesium.mutator.ClassMutator;
import dev.sim0n.caesium.util.wrapper.impl.ClassWrapper;
import org.objectweb.asm.tree.ClassNode;
/**
* This inserts a class that will crash almost every gui based RE tool
*/
public class ImageCrashMutator extends ClassMutator {
@Override
public void handle(ClassWrapper wrapper) { }
public ClassWrapper getCrashClass() {
ClassNode classNode = new ClassNode();
classNode.name = String.format("<html><img src=\"https:%s", getRandomName());
classNode.access = ACC_PUBLIC;
classNode.version = V1_5;
return new ClassWrapper(classNode, false);
}
@Override
public void handleFinish() {
logger.info("Inserted crash class");
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package service.config;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.Consumes;
import javax.ws.rs.Produces;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PUT;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.MediaType;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
@Path("artiste")
public class ArtisteOperations {
@Context
private UriInfo context;
public ArtisteOperations() {
}
//**************************insertion dans la table Artiste**********************************
@GET
@Path("insert&{id}&{biographie}")
@Produces(javax.ws.rs.core.MediaType.APPLICATION_JSON)
public String InsertArtiste(@PathParam("id") int artisteid,
@PathParam("biographie") String biographie){
JSONObject reponse = new JSONObject();
reponse.accumulate("Status", "Error");
reponse.accumulate("Message", "Insertion échoué");
reponse.clear();
try{
Connection cn = utils.DBOperation.connectionBd();
String sql = "insert into artiste values (?,?) ";
PreparedStatement stm = cn.prepareStatement(sql);
stm.setInt(1,artisteid);
stm.setString(2,biographie);
int rows = stm.executeUpdate();
if (rows > 0) {
reponse.accumulate("Status", "OK");
reponse.accumulate("Message", "Insertion réussi");
}
stm.close();
cn.close();
}
catch(SQLException e) {
System.out.println(e.getMessage());
}
return reponse.toString();
}
//***********************modification de l'Artiste******************************
@GET
@Path("update&{id}&{biographie}")
@Produces(javax.ws.rs.core.MediaType.APPLICATION_JSON)
public String updateArtiste(@PathParam("id") int artisteid,
@PathParam("biographie") String biographie){
JSONObject reponse = new JSONObject();
reponse.accumulate("Status", "Error");
reponse.accumulate("Message", "Modification échoué");
reponse.clear();
try{
Connection cn = utils.DBOperation.connectionBd();
String sql = "update artiste set biographie = ? where artisteidutilisateur = ? ";
PreparedStatement stm = cn.prepareStatement(sql);
stm.setString(1,biographie);
stm.setInt(2,artisteid);
int rows = stm.executeUpdate();
if (rows > 0) {
reponse.accumulate("Status", "OK");
reponse.accumulate("Message", "Modification réussi");
}
stm.close();
cn.close();
}
catch(SQLException e) {
System.out.println(e.getMessage());
}
return reponse.toString();
}
//**************************Afficher la liste des Artiste*****************************
@GET
@Path("allArtiste")
@Produces(javax.ws.rs.core.MediaType.APPLICATION_JSON)
public String selectAllArtiste() {
JSONArray mainJSON = new JSONArray();
try{
Connection cn = utils.DBOperation.connectionBd();
Statement stm = cn.createStatement();
String sql = "select * from artiste";
ResultSet rs = stm.executeQuery(sql);
JSONObject art = new JSONObject();
int idArtiste;
String biographie;
while (rs.next()) {
idArtiste = rs.getInt("artisteidutilisateur");
biographie = rs.getString("biographie");
art.accumulate("id", idArtiste);
art.accumulate("biographie", biographie);
mainJSON.add(art);
art.clear();
}
rs.close();
stm.close();
cn.close();
}
catch(SQLException e) {
System.out.println(e.getMessage());
}
return mainJSON.toString();
}
//************************Afficher un artiste par son ID****************************
@GET
@Path("singleArtiste&{id}")
@Produces(javax.ws.rs.core.MediaType.APPLICATION_JSON)
public String singleArtiste(@PathParam("id") int artisteid){
JSONObject singleArtiste = new JSONObject();
singleArtiste.accumulate("Status", "Error");
singleArtiste.accumulate("Message", "Artiste inexistant");
try{
Connection cn = utils.DBOperation.connectionBd();
String sql = "select * from artiste where artisteidutilisateur = ? ";
PreparedStatement stm = cn.prepareStatement(sql);
stm.setInt(1,artisteid);
ResultSet rs = stm.executeQuery();
int idArtiste;
String biographie;
while (rs.next()) {
idArtiste = rs.getInt("artisteidutilisateur");
biographie = rs.getString("biographie");
singleArtiste.clear();
singleArtiste.accumulate("id", idArtiste);
singleArtiste.accumulate("biographie", biographie);
}
rs.close();
stm.close();
cn.close();
}
catch(SQLException e) {
System.out.println(e.getMessage());
}
return singleArtiste.toString();
}
/// ******************Suprimer un Artiste****************************
@GET
@Path("delete&{id}")
@Produces(javax.ws.rs.core.MediaType.APPLICATION_JSON)
public String deleteIntoClients(@PathParam("id") int artisteid){
JSONObject reponse = new JSONObject();
reponse.accumulate("Status", "Error");
reponse.accumulate("Message", "Suppression échoué");
reponse.clear();
try{
Connection cn = utils.DBOperation.connectionBd();
String sql = "delete from Artiste where artisteidutilisateur = ? ";
PreparedStatement stm = cn.prepareStatement(sql);
stm.setInt(1,artisteid);
int rows = stm.executeUpdate();
if (rows > 0) {
reponse.accumulate("Status", "OK");
reponse.accumulate("Message", "Suppression réussi");
}
stm.close();
cn.close();
}
catch(SQLException e) {
System.out.println(e.getMessage());
}
return reponse.toString();
}
//************************** cas d'utilisation:Envoyer Message*****************
@GET
@Path("envoyer&{idMessage}&{dateMsg}&{objetMsg}&{texte}&{sender}&{receiver}")
@Produces(javax.ws.rs.core.MediaType.APPLICATION_JSON)
public String envoyerMessage(@PathParam("idMessage") int idMsg,
@PathParam("dateMsg") Date dateM,
@PathParam("objetMsg") String objetM,
@PathParam("texte") String txt,
@PathParam("sender") int utiSender,
@PathParam("receiver") int utiReceiver){
JSONObject reponse = new JSONObject();
reponse.accumulate("Status", "Error");
reponse.accumulate("Message", "Envoi échoué");
reponse.clear();
try{
Connection cn = utils.DBOperation.connectionBd();
String sql = "insert into message values (?,?,?,?,?,?) ";
PreparedStatement stm = cn.prepareStatement(sql);
stm.setInt(1,idMsg);
stm.setDate(2,dateM);
stm.setString(3, objetM);
stm.setString(4, txt);
stm.setInt(5, utiSender);
stm.setInt(6,utiReceiver);
int rows = stm.executeUpdate();
if (rows > 0) {
reponse.accumulate("Status", "OK");
reponse.accumulate("Message", "Envoi réussi");
}
stm.close();
cn.close();
}
catch(SQLException e) {
System.out.println(e.getMessage());
}
return reponse.toString();
}
}
|
package com.zs.ui.device.holder;
import android.content.Context;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;
import java.util.List;
import butterknife.BindView;
import com.zs.R;
import com.zs.common.AppUtils;
import com.zs.common.recycle.LiteViewHolder;
import com.zs.models.device.bean.DevicePlayerBean;
/**
* author: admin
* date: 2018/05/07
* version: 0
* mail: secret
* desc: DomainHolder
*/
public class DeviceChooseHolder extends LiteViewHolder {
@BindView(R.id.tv_device_name)
TextView tv_device_name;
@BindView(R.id.tv_status)
TextView tv_status;
@BindView(R.id.view_divider)
View view_divider;
@BindView(R.id.cb_status)
CheckBox cb_status;
public DeviceChooseHolder(Context context, View view, View.OnClickListener ocl, Object obj) {
super(context, view, ocl, obj);
itemView.setOnClickListener(ocl);
}
@Override
public void bindData(Object holder, int position, Object data, int size, List datas, Object extr) {
DevicePlayerBean bean = (DevicePlayerBean) data;
itemView.setTag(bean);
tv_device_name.setText(bean.strChannelName + AppUtils.getString(R.string.device_name));
cb_status.setChecked(bean.isSelected);
if (bean.nOnlineState == 1) {
tv_status.setText(AppUtils.getString(R.string.online));
} else {
tv_status.setText(AppUtils.getString(R.string.offline));
}
if (position == datas.size() - 1) {
view_divider.setVisibility(View.GONE);
} else {
view_divider.setVisibility(View.VISIBLE);
}
}
}
|
package com.lyl.mybatis;
import com.lyl.core.dao.domain.Test;
import com.lyl.core.dao.domain.TestExample;
import com.lyl.core.service.TestService;
import org.junit.runner.RunWith;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.Resource;
import java.util.List;
/**
* Created by lyl
* Date 2018/12/7
*/
@RunWith(SpringRunner.class)
@SpringBootTest
//或者在mapper.class 中加注解:@Mapper
@MapperScan("com.lyl.core.dao.mapper")
public class SpringMybatisExecuteTest {
@Resource
TestService testService;
@org.junit.Test
public void testSelectTest(){
TestExample testExample = new TestExample();
List<Test> list = testService.selectTestList(testExample);
System.out.println(list);
}
}
|
package io.javac.manybluesample.ui.scanner;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import java.util.ArrayList;
import java.util.List;
import io.javac.ManyBlue.ManyBlue;
import io.javac.ManyBlue.bean.UUIDMessage;
import io.javac.ManyBlue.interfaces.BaseNotifyListener;
import io.javac.manybluesample.R;
import io.javac.manybluesample.adapter.BlueDeviceAdapter;
import io.javac.manybluesample.base.BaseActivity;
public class ScannerActivity extends BaseActivity implements BaseNotifyListener.DeviceListener {
private RecyclerView recyclerView;
private BlueDeviceAdapter adapter;
@Override
public void initView() {
super.initView();
setContentView(R.layout.act_scanner);
recyclerView = (RecyclerView) findViewById(R.id.act_scanner_recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
adapter = new BlueDeviceAdapter(new ArrayList<BluetoothDevice>(), this);
recyclerView.setAdapter(adapter);
}
@Override
public void initData() {
super.initData();
// ManyBlue.blueStartScaner();//启动蓝牙扫描 不延迟返回 扫到一个返回一个
ManyBlue.blueStartScaner(3000);//延迟3秒返回一次列表
}
@Override
public void onClick(View view) {
super.onClick(view);
switch (view.getId()) {
case android.R.id.text1: {
String address = view.getTag().toString();
setDialog("正在连接该设备");
ManyBlue.blueConnectDevice(address, address);//连接该设备 并且以该设备的mac地址作为标识
}
break;
}
}
/**
* 扫描到蓝牙设备
*
* @param device
*/
@Override
public void onDeviceScanner(BluetoothDevice device) {
adapter.addDevice(device);
}
/**
* 扫描到的蓝牙设备列表
*
* @param device
*/
@Override
public void onDeviceScanner(List<BluetoothDevice> device) {
adapter.onRefresh(device);
}
/**
* 蓝牙设备连接活着断开
*
* @param state true为连接 false为断开
*/
@Override
public void onDeviceConnectState(boolean state, Object tag) {
if (!state) {
appToast("连接失败");
dismissDialog();
} else setDialog("连接成功 正在发现服务");
}
@Override
public void onDeviceServiceDiscover(List<BluetoothGattService> services, Object tag) {
setDialog("正在注册服务");
//services 这是该设备中所有的服务 在这里找到需要的服务 然后再进行注册
// services.get(0).getUuid().toString();//这是获取UUID的方法
//找到需要的UUID服务 然后进行连接 比如说我需要的服务UUID是00003f00-0000-1000-8000-00805f9b34fb UUID的话 一般设备厂家会提供文档 都有写的
UUIDMessage uuidMessage = new UUIDMessage();//创建UUID的配置类
// uuidMessage.setCharac_uuid_service("00003f00-0000-1000-8000-00805f9b34fb");//需要注册的服务UUID
// uuidMessage.setCharac_uuid_write("00003f02-0000-1000-8000-00805f9b34fb");//写出数据的通道UUID
// uuidMessage.setCharac_uuid_read("00003f01-0000-1000-8000-00805f9b34fb");//读取通道的UUID
// uuidMessage.setDescriptor_uuid_notify("00002902-0000-1000-8000-00805f9b34fb");//这是读取通道当中的notify通知
uuidMessage.setCharac_uuid_service("0000b0f0-0000-1000-8000-00805f9b34fb");
uuidMessage.setCharac_uuid_write("0000b0f7-0000-1000-8000-00805f9b34fb");
uuidMessage.setCharac_uuid_read("0000b0f6-0000-1000-8000-00805f9b34fb");
uuidMessage.setDescriptor_uuid_notify("00002902-0000-1000-8000-00805f9b34fb");
/**
* 这里简单说一下 如果设备返回数据的方式不是Notify的话 那就意味着向设备写出数据之后 再自己去获取数据
* Notify的话 是如果蓝牙设备有数据传递过来 能接受到通知
* 使用场景中如果没有notify的话 notify uuid留空即可
*/
ManyBlue.blueRegisterDevice(uuidMessage, tag);//注册设备
}
@Override
public void onDeviceRegister(boolean state, Object tag) {
dismissDialog();
appToast(state ? "设备注册成功" : "设备注册失败");
if (state)ManyBlue.setBlueWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE,tag);
}
@Override
protected void onDestroy() {
super.onDestroy();
ManyBlue.blueStopScaner();//关闭蓝牙扫描
}
} |
package com.codingchili.instance.model.events;
/**
* @author Robin Duda
*/
public enum Broadcast {
// publish to entities in the same grid cell: interaction etc.
ADJACENT,
// publish to entities on the cells that are in the same network partition: spells, CHAT.
PARTITION,
// publish to all entities in the instance: join/leave events.
GLOBAL,
// event will not be broadcast at all - use if event is only used for direct messages.
NONE
}
|
import java.io.*;
import java.util.*;
public class kosaraju {
/**
Strongly connected components.
You are given a graph with N nodes and M directed edges. Find the number of Strongly connected components in the graph.
*/
private static void dfsStack(ArrayList<ArrayList<Integer>> graph, int src, boolean[] vis, Stack<Integer> st){
vis[src] = true;
for(int nbr: graph.get(src)){
if(vis[nbr] == false){
dfsStack(graph, nbr, vis, st);
}
}
st.push(src);
}
private static void dfsCount(ArrayList<ArrayList<Integer>> graph, int src, boolean[] vis){
vis[src] = true;
for(int nbr: graph.get(src)){
if(vis[nbr] == false){
dfsCount(graph, nbr, vis);
}
}
}
private static int stronglyConnectedComponents(ArrayList<ArrayList<Integer>> graph){
// STEP 1: Iterate on vertex and add vertex in stack while backtracking.
Stack<Integer> st = new Stack<>();
boolean[] vis = new boolean[graph.size()];
for(int v=0; v<graph.size(); v++){
if(vis[v] == false){
dfsStack(graph, v, vis, st);
}
}
// STEP 2: Reverse all edge
ArrayList<ArrayList<Integer>> revGraph = new ArrayList<>();
for(int i=0; i<graph.size(); i++){
revGraph.add(new ArrayList<>());
}
for(int v=0; v<graph.size(); v++){
for(int u: graph.get(v)){
revGraph.get(u).add(v);
}
}
// STEP 3: Iterate on vertex in order of stack and count no of calls
int count = 0;
vis = new boolean[graph.size()];
while(st.size() > 0){
int v = st.pop();
if(vis[v] == false){
count++;
dfsCount(revGraph, v, vis);
}
}
return count;
}
public static void main(String args[]) throws Exception {
Scanner scn = new Scanner(System.in);
int n = scn.nextInt();
int m = scn.nextInt();
ArrayList<ArrayList<Integer>> graph = new ArrayList<>();
for(int i=0; i<n; i++){
graph.add(new ArrayList<>());
}
for(int i=0; i<m; i++){
int v1 = scn.nextInt() - 1;
int v2 = scn.nextInt() - 1;
// add directed edge
graph.get(v1).add(v2);
}
System.out.println(stronglyConnectedComponents(graph));
}
}
|
package com.example.projet_makbal_mounir;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.Scanner;
public class MainActivity extends AppCompatActivity {
EditText name;
EditText password;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void Login(View view) {
Scanner scan;
name=(EditText)findViewById(R.id.name);
password=(EditText)findViewById(R.id.password);
String nom=name.getText().toString();
String mdp=password.getText().toString();
scan = new Scanner(getResources().openRawResource(R.raw.pwd));
int j=0;
while (scan.hasNextLine()) {
String data = scan.nextLine();
String[] strArray = data.split(",");
if (strArray[0].equals(nom) && strArray[1].equals(mdp)){
j++;
scan.close();
Intent i=new Intent();
i.setAction("prof.choix");
i.putExtra("nomprof",nom);
startActivity(i);
break;
}
}
scan.close();
if(j==0){
Toast.makeText(this, "Logon Denied !", Toast.LENGTH_SHORT).show();
}
}
}
|
package com.egova.eagleyes.view;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.egova.baselibrary.activity.PhotoPreviewActivity;
import com.egova.baselibrary.base.EgovaFragment;
import com.egova.baselibrary.model.BaseResponse;
import com.egova.baselibrary.model.Lcee;
import com.egova.baselibrary.model.Paging;
import com.egova.baselibrary.model.QueryModel;
import com.egova.baselibrary.util.ActivityLaunchUtil;
import com.egova.baselibrary.util.CommonConstants;
import com.egova.baselibrary.util.ToastUtil;
import com.egova.eagleyes.R;
import com.egova.eagleyes.adapter.DispositionAlarmListAdapter;
import com.egova.eagleyes.constants.Constants;
import com.egova.eagleyes.databinding.FragmentDispositionAlarmBinding;
import com.egova.eagleyes.databinding.TitleBackBarBinding;
import com.egova.eagleyes.model.request.PoliceCondition;
import com.egova.eagleyes.model.respose.DispositionAlarm;
import com.egova.eagleyes.vm.PoliceControlViewModel;
import java.util.ArrayList;
import java.util.List;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;
/**
* 报警管理车辆列表
*/
public class DispositionAlarmListFragment extends EgovaFragment<FragmentDispositionAlarmBinding, PoliceControlViewModel> {
private TitleBackBarBinding titleBackBarBinding;
private int dispositionAlarmSize = 0;
private ArrayList<DispositionAlarm> dataList;
private QueryModel<PoliceCondition> queryModel;
private DispositionAlarmListAdapter adapter;
private int selectPosition = 0;
@Override
public int initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return R.layout.fragment_disposition_alarm;
}
@Override
public void initView() {
initTitleBar();
initRecyclerView();
}
private void initTitleBar() {
titleBackBarBinding = binding.titleBar;
titleBackBarBinding.tvTitle.setText(getString(R.string.police_control) + "(" + dispositionAlarmSize + "条)");
titleBackBarBinding.leftBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getActivity().finish();
}
});
}
@Override
public void initData() {
dispositionAlarmSize = getArguments().getInt(Constants.BUNDLE_VEHICLE_SIZE);
dataList = (ArrayList<DispositionAlarm>) getArguments().getSerializable(Constants.BUNDLE_VEHICLE_LIST);
queryModel = (QueryModel<PoliceCondition>) getArguments().getSerializable(Constants.BUNDLE_VEHICLE_QUERY);
}
@Override
public void addVMObserver() {
//查询报警
viewModel.getAlarmSearchData().observe(this, new Observer<Lcee<BaseResponse<List<DispositionAlarm>>>>() {
@Override
public void onChanged(Lcee<BaseResponse<List<DispositionAlarm>>> responseLcee) {
updateData(responseLcee);
}
});
//处理报警
viewModel.getAlarmHandlerData().observe(this, new Observer<Lcee<BaseResponse<Boolean>>>() {
@Override
public void onChanged(Lcee<BaseResponse<Boolean>> baseResponseLcee) {
updateHandlerData(baseResponseLcee);
}
});
}
private void initRecyclerView() {
binding.recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
adapter = new DispositionAlarmListAdapter(R.layout.item_disposition_alarm, dataList);
adapter.openLoadAnimation(BaseQuickAdapter.SCALEIN);
adapter.isFirstOnly(false);
binding.recyclerView.setAdapter(adapter);
adapter.setOnItemClickListener(onItemClickListener);
adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
@Override
public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
if (view.getId() == R.id.carImage) {
//点击查看大图
Bundle bundle = new Bundle();
ArrayList<String> images = new ArrayList<>();
images.add(dataList.get(position).getPicture());
bundle.putStringArrayList("images", images);
bundle.putInt("position", 0);
bundle.putBoolean("isNetworkPath", true);
bundle.putBoolean("isShowDeleteButton", false);
ActivityLaunchUtil.launchActivity(getActivity(), PhotoPreviewActivity.class, bundle);
} else if (view.getId() == R.id.handleBtn) {
if (dataList.get(position).getHandled()) {
ToastUtil.showNormal("该车辆已处理");
} else {
showLoadingDialog("正在处理中...");
adapter.closeLoadAnimation();
selectPosition = position;
viewModel.handlerAlarm(dataList.get(position).getId());
}
}
}
});
//加载更多
adapter.setEnableLoadMore(true);
adapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
@Override
public void onLoadMoreRequested() {
loadData();
}
}, binding.recyclerView);
}
private void loadData() {
Paging paging = queryModel.getPaging();
paging.setPageIndex(paging.getPageIndex() + 1);
viewModel.loadDispositionAlarm(queryModel);
}
//报警查询
private void updateData(Lcee<BaseResponse<List<DispositionAlarm>>> response) {
switch (response.status) {
case Content:
adapter.addData(response.data.getResult());
if (response.data.getResult().size() < CommonConstants.PAGE_SIZE) {
adapter.loadMoreEnd();
} else {
adapter.loadMoreComplete();
}
break;
case Error:
Paging paging = queryModel.getPaging();
paging.setPageIndex(paging.getPageIndex() - 1);
adapter.loadMoreFail();
break;
}
}
//报警处理
private void updateHandlerData(Lcee<BaseResponse<Boolean>> response) {
dismissLoadingDialog();
switch (response.status) {
case Error:
ToastUtil.showError(response.error.getMessage());
break;
case Content:
dataList.get(selectPosition).setHandled(true);
adapter.notifyItemChanged(selectPosition);
ToastUtil.showNormal(response.data.getMessage());
break;
}
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
}
});
handler.sendEmptyMessageDelayed(1, 300);
}
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == 1)
adapter.openLoadAnimation();
}
};
private BaseQuickAdapter.OnItemClickListener onItemClickListener = new BaseQuickAdapter.OnItemClickListener() {
@Override
public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
DispositionAlarm item = dataList.get(position);
Bundle bundle = new Bundle();
bundle.putSerializable(Constants.BUNDLE_VEHICLE, item);
ActivityLaunchUtil.launchContainerActivity(getActivity(), DispositionAlarmDetailFragment.class.getCanonicalName(), bundle);
}
};
}
|
package kz.greetgo.file_storage.impl;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import javax.sql.DataSource;
import kz.greetgo.file_storage.FileDataReader;
import kz.greetgo.file_storage.FileStorage;
import kz.greetgo.file_storage.FileStoringOperation;
import kz.greetgo.file_storage.FileUpdatingOperation;
import kz.greetgo.file_storage.errors.NoFileData;
import kz.greetgo.file_storage.errors.NoFileWithId;
import kz.greetgo.file_storage.errors.NoParam;
import kz.greetgo.file_storage.errors.TableIsAbsent;
import kz.greetgo.file_storage.impl.jdbc.insert.Insert;
import kz.greetgo.file_storage.impl.jdbc.structure.Field;
import kz.greetgo.file_storage.impl.jdbc.structure.FieldType;
import kz.greetgo.file_storage.impl.jdbc.structure.Table;
import static kz.greetgo.file_storage.impl.IdGeneratorType.STR13;
import static kz.greetgo.file_storage.impl.LocalUtil.readAll;
public class FileStorageMultiDbLogic implements FileStorage {
private final FileStorageBuilderImpl parent;
private final FileStorageBuilderMultiDbImpl builder;
private final MultiDbOperations operations;
public FileStorageMultiDbLogic(FileStorageBuilderImpl parent,
FileStorageBuilderMultiDbImpl builder,
MultiDbOperations operations) {
this.parent = parent;
this.builder = builder;
this.operations = operations;
}
@Override
public FileStoringOperation storing() {
//noinspection DuplicatedCode
return new FileStoringOperation() {
final CreateNewParams params = new CreateNewParams();
@Override
public FileStoringOperation name(String name) {
params.name = name;
{
Function<String, String> mimeTypeExtractor = parent.mimeTypeExtractor;
if (mimeTypeExtractor != null) {
params.mimeType = mimeTypeExtractor.apply(name);
}
}
return this;
}
@Override
public FileStoringOperation createdAt(Date createdAt) {
params.createdAt = createdAt;
return this;
}
@Override
public FileStoringOperation mimeType(String mimeType) {
params.mimeType = mimeType;
return this;
}
byte[] data = null;
InputStream inputStream = null;
@Override
public FileStoringOperation data(byte[] data) {
checkSetData();
this.data = data == null ? new byte[0] : data;
return this;
}
private void checkSetData() {
if (data != null || inputStream != null) {
throw new IllegalStateException("data already defined");
}
}
@Override
public FileStoringOperation data(InputStream inputStream) {
if (inputStream == null) {
throw new IllegalArgumentException("inputStream == null");
}
checkSetData();
this.inputStream = inputStream;
return this;
}
private byte[] getData() {
if (data != null) {
return data;
}
if (inputStream != null) {
return readAll(inputStream);
}
throw new NoFileData();
}
@Override
public FileStoringOperation presetId(String presetFileId) {
params.presetFileId = presetFileId;
return this;
}
@Override
public FileStoringOperation param(String paramName, String paramValue) {
if (paramName.isEmpty() || paramValue.isEmpty()) {
throw new NoParam();
}
params.param.put(paramName, paramValue);
return this;
}
@Override
public String store() {
builder.parent.checkName(params.name);
builder.parent.checkMimeType(params.mimeType);
String fileId = params.presetFileId;
if (fileId == null) {
fileId = parent.idGenerator(STR13).get();
}
try {
createNew(getData(), params, fileId);
return fileId;
} catch (TableIsAbsent e) {
createTableQuiet(fileId);
createNew(getData(), params, fileId);
return fileId;
}
}
};
}
@Override
public FileUpdatingOperation updating() {
return new FileUpdatingOperation() {
boolean isNameSet = false;
String newName = null;
Map<String, String> newParam;
@Override
public FileUpdatingOperation name(String name) {
isNameSet = true;
newName = name;
return this;
}
@Override
public FileUpdatingOperation param(String name, String newValue) {
if(newParam == null){
newParam = new HashMap<>();
}
newParam.put(name, newValue);
return this;
}
@Override
public void store(String fileId) {
if(newParam != null) {
TablePosition tablePosition = builder.tableSelector.selectTable(fileId);
DataSource dataSource = extractDataSource(tablePosition);
String paramTableName = tableNameForParam(tablePosition);
TableFieldNamesForParam names = new TableFieldNamesForParam();
names.id = FIELD_ID;
names.name = FIELD_PARAM_NAME;
names.value = FIELD_PARAM_VALUE;
operations.updateParam(fileId, newParam, dataSource, paramTableName, names);
}
}
};
}
@Override
public FileDataReader read(String fileId) throws NoFileWithId {
FileDataReader reader = readOrNull(fileId);
if (reader == null) {
throw new NoFileWithId(fileId);
}
return reader;
}
@Override
public FileDataReader readOrNull(String fileId) {
if (fileId == null || fileId.length() == 0) {
throw new IllegalArgumentException("fileId = " + fileId);
}
FileParams params = loadFileParams(fileId);
if (params == null) {
return null;
}
return new FileDataReader() {
@Override
public String name() {
return params.name;
}
final Object sync = new Object();
byte[] data = null;
@Override
public byte[] dataAsArray() {
{
byte[] data = this.data;
if (data != null) {
return data;
}
}
synchronized (sync) {
{
byte[] data = this.data;
if (data != null) {
return data;
}
}
return data = loadData(fileId);
}
}
@Override
public Date createdAt() {
return params.createdAt;
}
@Override
public String mimeType() {
return params.mimeType;
}
@Override
public String paramValue(String paramName) {
return getFileParameter(fileId, paramName);
}
@Override
public Map<String, String> allParams() {
return getFileParameters(fileId);
}
@Override
public String id() {
return params.id;
}
@Override
public void writeTo(OutputStream out) {
try {
out.write(dataAsArray());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
};
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
private static final String FIELD_ID = "id";
private static final String FIELD_NAME = "name";
private static final String FIELD_CREATED_AT = "created_at";
private static final String FIELD_MIME_TYPE = "mime_type";
private static final String FIELD_FILE_CONTENT = "file_content";
private static final String FIELD_PARAM_NAME = "name";
private static final String FIELD_PARAM_VALUE = "value";
private String tableName(TablePosition tablePosition) {
return builder.tableName + "_" + LocalUtil.toStrLen(tablePosition.tableIndex, builder.tableIndexLength);
}
private String tableNameForParam(TablePosition tablePosition) {
return builder.paramTableName + "_" + LocalUtil.toStrLen(tablePosition.tableIndex, builder.tableIndexLength);
}
private void createTableQuiet(String fileId) {
TablePosition tablePosition = builder.tableSelector.selectTable(fileId);
Table table = new Table(tableName(tablePosition));
{
Field f = table.addField();
f.primaryKey = true;
f.type = FieldType.STR;
f.valueLen = parent.fileIdLength;
f.name = FIELD_ID;
f.notNull = true;
}
{
Field f = table.addField();
f.primaryKey = false;
f.type = FieldType.STR;
f.valueLen = 255;
f.name = FIELD_NAME;
f.notNull = parent.mandatoryName;
}
{
Field f = table.addField();
f.primaryKey = false;
f.type = FieldType.TIMESTAMP;
f.defaultCurrentTimestamp = true;
f.name = FIELD_CREATED_AT;
f.notNull = true;
}
{
Field f = table.addField();
f.primaryKey = false;
f.type = FieldType.STR;
f.name = FIELD_MIME_TYPE;
f.valueLen = 255;
f.notNull = parent.mandatoryMimeType;
}
{
Field f = table.addField();
f.primaryKey = false;
f.type = FieldType.BLOB;
f.name = FIELD_FILE_CONTENT;
f.notNull = false;
}
DataSource dataSource = extractDataSource(tablePosition);
operations.createTableQuiet(dataSource, table);
{
Table tableParam = new Table(tableNameForParam(tablePosition));
{
Field f = tableParam.addField();
f.primaryKey = true;
f.type = FieldType.STR;
f.valueLen = parent.fileIdLength;
f.name = FIELD_ID;
f.notNull = true;
}
{
Field f = tableParam.addField();
f.primaryKey = true;
f.type = FieldType.STR;
f.valueLen = 255;
f.name = FIELD_PARAM_NAME;
f.notNull = false;
}
{
Field f = tableParam.addField();
f.primaryKey = false;
f.type = FieldType.STR;
f.valueLen = 255;
f.name = FIELD_PARAM_VALUE;
f.notNull = false;
}
DataSource dataSourceParam = extractDataSource(tablePosition);
operations.createTableQuiet(dataSourceParam, tableParam);
}
}
private DataSource extractDataSource(TablePosition tablePosition) {
return builder.dataSourceList.get(tablePosition.dbIndex);
}
private void createNew(byte[] data, CreateNewParams params, String fileId) throws TableIsAbsent {
TablePosition tablePosition = builder.tableSelector.selectTable(fileId);
DataSource dataSource = extractDataSource(tablePosition);
Insert insert = new Insert(tableName(tablePosition));
insert.add(FIELD_ID, fileId);
insert.add(FIELD_FILE_CONTENT, data);
if (params.mimeType != null) {
insert.add(FIELD_MIME_TYPE, params.mimeType);
}
if (params.name != null) {
insert.add(FIELD_NAME, params.name);
}
operations.insert(dataSource, insert, tablePosition);
params.param.forEach((key, value) -> {
Insert insertParam = new Insert(tableNameForParam(tablePosition));
insertParam.add(FIELD_ID, fileId);
insertParam.add(FIELD_PARAM_NAME, key);
insertParam.add(FIELD_PARAM_VALUE, value);
operations.insert(dataSource, insertParam, tablePosition);
});
}
@Override
public void delete(String fileId) throws NoFileWithId {
TablePosition tablePosition = builder.tableSelector.selectTable(fileId);
DataSource dataSource = extractDataSource(tablePosition);
String tableName = tableName(tablePosition);
String paramTableName = tableNameForParam(tablePosition);
operations.delete(dataSource, tableName, FIELD_ID, fileId, tablePosition, true);
operations.delete(dataSource, paramTableName, FIELD_ID, fileId, tablePosition, false);
}
private byte[] loadData(String fileId) {
TablePosition tablePosition = builder.tableSelector.selectTable(fileId);
String tableName = tableName(tablePosition);
DataSource dataSource = extractDataSource(tablePosition);
return operations.loadData(dataSource, tableName, FIELD_ID, fileId, FIELD_FILE_CONTENT);
}
private FileParams loadFileParams(String fileId) {
TablePosition tablePosition = builder.tableSelector.selectTable(fileId);
DataSource dataSource = extractDataSource(tablePosition);
String tableName = tableName(tablePosition);
TableFieldNames names = new TableFieldNames();
names.id = FIELD_ID;
names.name = FIELD_NAME;
names.mimeType = FIELD_MIME_TYPE;
names.createdAt = FIELD_CREATED_AT;
return operations.loadFileParams(dataSource, tableName, fileId, names);
}
private String getFileParameter(String fileId, String paramName) {
TablePosition tablePosition = builder.tableSelector.selectTable(fileId);
DataSource dataSource = extractDataSource(tablePosition);
String tableName = tableNameForParam(tablePosition);
TableFieldNamesForParam names = new TableFieldNamesForParam();
names.id = FIELD_ID;
names.name = FIELD_PARAM_NAME;
names.value = FIELD_PARAM_VALUE;
return operations.loadFileParameter(dataSource, tableName, fileId, paramName, names);
}
private Map<String, String> getFileParameters(String fileId) {
TablePosition tablePosition = builder.tableSelector.selectTable(fileId);
DataSource dataSource = extractDataSource(tablePosition);
String tableName = tableNameForParam(tablePosition);
TableFieldNamesForParam names = new TableFieldNamesForParam();
names.id = FIELD_ID;
names.name = FIELD_PARAM_NAME;
names.value = FIELD_PARAM_VALUE;
return operations.loadFileParameters(dataSource, tableName, fileId, names);
}
}
|
package com.github.spocot.mythra;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
public class MythraPanel extends AnimationPanel{
private Block[][] blocks;
private Map map;
private Player player = new Player(100,100);
//Movement variablees
private volatile boolean wPressed = false;
private volatile boolean aPressed = false;
private volatile boolean sPressed = false;
private volatile boolean dPressed = false;
public MythraPanel(int pWidth, int pHeight) {
super(pWidth, pHeight);
map = new Map();
}
@Override
public void mouseDraggedEvents(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseMovedEvents(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseClickedEvents(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseEnteredEvents(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseExitedEvents(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mousePressedEvents(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleasedEvents(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyPressedEvents(KeyEvent e) {
int keyCode = e.getKeyCode();
switch(keyCode){
case KeyEvent.VK_W:{
wPressed = true;
if(aPressed)
player.setDirection(Direction.NORTH_WEST);
else if(dPressed)
player.setDirection(Direction.NORTH_EAST);
else if(sPressed)
player.setDirection(Direction.NEUTRAL);
else
player.setDirection(Direction.NORTH);
}break;
case KeyEvent.VK_A:{
aPressed = true;
if(wPressed)
player.setDirection(Direction.NORTH_WEST);
else if(sPressed)
player.setDirection(Direction.SOUTH_WEST);
else if(dPressed)
player.setDirection(Direction.NEUTRAL);
else
player.setDirection(Direction.WEST);
}break;
case KeyEvent.VK_S:{
sPressed = true;
if(aPressed)
player.setDirection(Direction.SOUTH_WEST);
else if(dPressed)
player.setDirection(Direction.SOUTH_EAST);
else if(wPressed)
player.setDirection(Direction.NEUTRAL);
else
player.setDirection(Direction.SOUTH);
}break;
case KeyEvent.VK_D:{
dPressed = true;
if(wPressed)
player.setDirection(Direction.NORTH_EAST);
else if(sPressed)
player.setDirection(Direction.SOUTH_EAST);
else if(aPressed)
player.setDirection(Direction.NEUTRAL);
else
player.setDirection(Direction.EAST);
}break;
}
}
@Override
public void keyReleasedEvents(KeyEvent e) {
int keyCode = e.getKeyCode();
switch(keyCode){
case KeyEvent.VK_W:{
wPressed = false;
Direction direction = player.getDirection();
switch(direction){
case NORTH_WEST:player.setDirection(Direction.WEST);break;
case NORTH_EAST:player.setDirection(Direction.EAST);break;
}
}break;
case KeyEvent.VK_A:{
aPressed = false;
Direction direction = player.getDirection();
switch(direction){
case NORTH_WEST:player.setDirection(Direction.NORTH);break;
case SOUTH_WEST:player.setDirection(Direction.SOUTH);break;
}
}break;
case KeyEvent.VK_S:{
sPressed = false;
Direction direction = player.getDirection();
switch(direction){
case SOUTH_WEST:player.setDirection(Direction.WEST);break;
case SOUTH_EAST:player.setDirection(Direction.EAST);break;
}
}break;
case KeyEvent.VK_D:{
dPressed = false;
Direction direction = player.getDirection();
switch(direction){
case SOUTH_EAST:player.setDirection(Direction.SOUTH);break;
case NORTH_EAST:player.setDirection(Direction.NORTH);break;
}
}break;
}
if(!wPressed && !aPressed && !sPressed && !dPressed)
player.setDirection(Direction.NEUTRAL);
}
@Override
public void updateGame() {
blocks = map.getBlocks();
int prevX = player.getX();
int prevY = player.getY();
player.update();
if(map.checkCollide(player))
player.setPosition(prevX, prevY);
}
@Override
public void drawGame(Graphics g) {
map.render(g);
player.render(g);
}
}
|
package com.usta.cmapp.control;
import java.io.IOException;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.enterprise.context.SessionScoped;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import org.primefaces.event.FlowEvent;
import com.covidapp_mysql.model.Ciudade;
import com.covidapp_mysql.model.Empresa;
import com.covidapp_mysql.model.Enfermedade;
import com.covidapp_mysql.model.Persona;
import com.covidapp_mysql.model.Registro;
import com.covidapp_mysql.model.TipoDocumento;
import com.usta.cmapp.constants.EnumDataBase;
import com.usta.cmapp.constants.EnumRhBlood;
import com.usta.covidApp_ejb.service.ServicesDao;
@ManagedBean(name = "regis")
@SessionScoped
public class RegisterController implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private Properties properties;
private Registro registerPerson;
private String usLoged;
private String userAccess;
private Persona personRegis;
private List<Enfermedade> listaEnfermedades;
private List<Empresa> listaEmpresa;
private String document;
private boolean visiblePanel;
private Float imc;
private String resultaImc;
@EJB
private ServicesDao<Object> servicesDao;
/**
* Constructor class
*/
public RegisterController() {
properties = new Properties();
userAccess = null;
registerPerson = new Registro();
listaEnfermedades = new ArrayList<Enfermedade>();
listaEmpresa = new ArrayList<Empresa>();
document = null;
visiblePanel = false;
imc = 0.0F;
resultaImc = null;
personRegis = new Persona();
chargeProperties();
}
/**
* Init variables
*/
private void chargeProperties() {
try {
properties.load(RegisterController.class.getResourceAsStream("messages.properties"));
userAccess = ((String) FacesContext.getCurrentInstance().getExternalContext().getSessionMap()
.get(LoginController.USER_AUTENTICH)).toUpperCase();
usLoged = ((String) FacesContext.getCurrentInstance().getExternalContext().getSessionMap()
.get(LoginController.AUTH_KEY)).toUpperCase();
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
properties.getProperty("errorGeneral"), properties.getProperty("errorCargaPropiedades")));
}
}
/**
* Este metodo se inicializa tan pronto se carga la clase y despues que crea el
* constructor No recibe invocacion de ningun cliente, el cliente es el mismo
* servidor cuando la aplicacion es inicializada
*/
@PostConstruct
public void chargeData() {
try {
List<Object> d = servicesDao.findAll(Enfermedade.class, EnumDataBase.MYSQL.getId());
for (Object o : d) {
listaEnfermedades.add((Enfermedade) o);
}
List<Object> c = servicesDao.findAll(Empresa.class, EnumDataBase.MYSQL.getId());
for (Object o : c) {
listaEmpresa.add((Empresa) o);
}
} catch (Exception e) {
// TODO
}
}
/**
* valida los registros que sean de caracter obligatorio y valida que la fecha
* de nacimiento sea menor a la dia de hoy
*
* @return
*/
public void validatePerson() {
try {
if (document != null && !document.equals("") && (registerPerson.getIdEnfermedad() > 0)
&& (registerPerson.getIdEmpresa() > 0)) {
personRegis = (Persona) servicesDao.searchPersonByDocument(document, EnumDataBase.MYSQL.getId());
if (personRegis != null && !personRegis.equals("")) {
registerPerson.setIdPersona(personRegis.getIdPersona());
visiblePanel = true;
} else {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN,
properties.getProperty(""), properties.getProperty("")));
}
}
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
properties.getProperty(""), properties.getProperty("")));
}
}
public void regisInto() {
try {
if (personRegis.getPeso() > 0 && registerPerson.getTemperatura() > 0) {
if (registerPerson.getTemperatura() < 38 && registerPerson.getTemperatura() > 35) {
registerPerson.setIngreso(Byte.valueOf("0"));
registerPerson.setFechaIngreso(new Date());
registerPerson.setSintomas(Byte.valueOf("0"));
servicesDao.create(registerPerson, EnumDataBase.MYSQL.getId());
imc = Float.valueOf(personRegis.getPeso())
/ Float.valueOf((float) Math.pow(Double.valueOf(personRegis.getEstatura()), 2));
resultaImc = personRegis.getGenero().equals("male")
? (imc > 25 ? "SOBREPESO".concat(imc.toString()) : "NORMAL".concat(imc.toString()))
: (imc > 24 ? "SOBREPESO".concat(imc.toString()) : "NORMAL".concat(imc.toString()));
}
}
} catch (Exception e) {
}
}
public Properties getProperties() {
return properties;
}
public void setProperties(Properties properties) {
this.properties = properties;
}
public Registro getRegisterPerson() {
return registerPerson;
}
public void setRegisterPerson(Registro registerPerson) {
this.registerPerson = registerPerson;
}
public String getUsLoged() {
return usLoged;
}
public void setUsLoged(String usLoged) {
this.usLoged = usLoged;
}
public String getUserAccess() {
return userAccess;
}
public void setUserAccess(String userAccess) {
this.userAccess = userAccess;
}
public Persona getPersonRegis() {
return personRegis;
}
public void setPersonRegis(Persona personRegis) {
this.personRegis = personRegis;
}
public List<Enfermedade> getListaEnfermedades() {
return listaEnfermedades;
}
public void setListaEnfermedades(List<Enfermedade> listaEnfermedades) {
this.listaEnfermedades = listaEnfermedades;
}
public List<Empresa> getListaEmpresa() {
return listaEmpresa;
}
public void setListaEmpresa(List<Empresa> listaEmpresa) {
this.listaEmpresa = listaEmpresa;
}
public String getDocument() {
return document;
}
public void setDocument(String document) {
this.document = document;
}
public boolean isVisiblePanel() {
return visiblePanel;
}
public void setVisiblePanel(boolean visiblePanel) {
this.visiblePanel = visiblePanel;
}
public Float getImc() {
return imc;
}
public void setImc(Float imc) {
this.imc = imc;
}
public String getResultaImc() {
return resultaImc;
}
public void setResultaImc(String resultaImc) {
this.resultaImc = resultaImc;
}
public ServicesDao<Object> getServicesDao() {
return servicesDao;
}
public void setServicesDao(ServicesDao<Object> servicesDao) {
this.servicesDao = servicesDao;
}
}
|
/*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.servlet;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import org.springframework.lang.Nullable;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.util.Assert;
import org.springframework.web.servlet.FlashMap;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.support.RequestContextUtils;
/**
* A simple implementation of {@link MvcResult} with setters.
*
* @author Rossen Stoyanchev
* @author Rob Winch
* @since 3.2
*/
class DefaultMvcResult implements MvcResult {
private static final Object RESULT_NONE = new Object();
private final MockHttpServletRequest mockRequest;
private final MockHttpServletResponse mockResponse;
@Nullable
private Object handler;
@Nullable
private HandlerInterceptor[] interceptors;
@Nullable
private ModelAndView modelAndView;
@Nullable
private Exception resolvedException;
private final AtomicReference<Object> asyncResult = new AtomicReference<>(RESULT_NONE);
@Nullable
private CountDownLatch asyncDispatchLatch;
/**
* Create a new instance with the given request and response.
*/
public DefaultMvcResult(MockHttpServletRequest request, MockHttpServletResponse response) {
this.mockRequest = request;
this.mockResponse = response;
}
@Override
public MockHttpServletRequest getRequest() {
return this.mockRequest;
}
@Override
public MockHttpServletResponse getResponse() {
return this.mockResponse;
}
public void setHandler(@Nullable Object handler) {
this.handler = handler;
}
@Override
@Nullable
public Object getHandler() {
return this.handler;
}
public void setInterceptors(@Nullable HandlerInterceptor... interceptors) {
this.interceptors = interceptors;
}
@Override
@Nullable
public HandlerInterceptor[] getInterceptors() {
return this.interceptors;
}
public void setResolvedException(Exception resolvedException) {
this.resolvedException = resolvedException;
}
@Override
@Nullable
public Exception getResolvedException() {
return this.resolvedException;
}
public void setModelAndView(@Nullable ModelAndView mav) {
this.modelAndView = mav;
}
@Override
@Nullable
public ModelAndView getModelAndView() {
return this.modelAndView;
}
@Override
public FlashMap getFlashMap() {
return RequestContextUtils.getOutputFlashMap(this.mockRequest);
}
public void setAsyncResult(Object asyncResult) {
this.asyncResult.set(asyncResult);
}
@Override
public Object getAsyncResult() {
return getAsyncResult(-1);
}
@Override
public Object getAsyncResult(long timeToWait) {
if (this.mockRequest.getAsyncContext() != null && timeToWait == -1) {
long requestTimeout = this.mockRequest.getAsyncContext().getTimeout();
timeToWait = requestTimeout == -1 ? Long.MAX_VALUE : requestTimeout;
}
if (!awaitAsyncDispatch(timeToWait)) {
throw new IllegalStateException("Async result for handler [" + this.handler + "]" +
" was not set during the specified timeToWait=" + timeToWait);
}
Object result = this.asyncResult.get();
Assert.state(result != RESULT_NONE, () -> "Async result for handler [" + this.handler + "] was not set");
return this.asyncResult.get();
}
/**
* True if the latch count reached 0 within the specified timeout.
*/
private boolean awaitAsyncDispatch(long timeout) {
Assert.state(this.asyncDispatchLatch != null,
"The asyncDispatch CountDownLatch was not set by the TestDispatcherServlet.");
try {
return this.asyncDispatchLatch.await(timeout, TimeUnit.MILLISECONDS);
}
catch (InterruptedException ex) {
return false;
}
}
void setAsyncDispatchLatch(CountDownLatch asyncDispatchLatch) {
this.asyncDispatchLatch = asyncDispatchLatch;
}
}
|
/*
* Copyright © 2020-2022 ForgeRock AS (obst@forgerock.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.forgerock.sapi.gateway.ob.uk.common.datamodel.account;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonValue;
import com.forgerock.sapi.gateway.ob.uk.common.datamodel.common.FRAccountIdentifier;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.joda.time.DateTime;
import java.util.List;
import java.util.stream.Stream;
/**
* Represents {@code OBAccount6} in the OB data model. It is stored within mongo (instead of the OB object),
* in order to make it easier to introduce new versions of the Read/Write API.
*
* <p>
* Note that this object is used across multiple versions of the Read/Write API, meaning that some values won't be
* populated. For this reason it is a mutable {@link Data} rather than an immutable {@link lombok.Value} one.
* </p>
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class FRFinancialAccount {
private String accountId;
private FRAccountStatusCode status;
private DateTime statusUpdateDateTime;
private String currency;
private FRAccountTypeCode accountType;
private FRAccountSubTypeCode accountSubType;
private String description;
private String nickname;
private DateTime openingDate;
private DateTime maturityDate;
private List<FRAccountIdentifier> accounts;
private FRAccountServicer servicer;
@JsonIgnore
public FRAccountIdentifier getFirstAccount() {
if(this.accounts == null || this.accounts.size()==0)
return null;
return this.accounts.get(0);
}
public enum FRAccountStatusCode {
DELETED("Deleted"),
DISABLED("Disabled"),
ENABLED("Enabled"),
PENDING("Pending"),
PROFORMA("ProForma");
private String value;
FRAccountStatusCode(String value) {
this.value = value;
}
public String getValue() {
return value;
}
@JsonValue
public String toString() {
return value;
}
@JsonCreator
public static FRAccountStatusCode fromValue(String value) {
return Stream.of(values())
.filter(type -> type.getValue().equals(value))
.findFirst()
.orElse(null);
}
}
public enum FRAccountTypeCode {
BUSINESS("Business"),
PERSONAL("Personal");
private String value;
FRAccountTypeCode(String value) {
this.value = value;
}
public String getValue() {
return value;
}
@JsonValue
public String toString() {
return value;
}
@JsonCreator
public static FRAccountTypeCode fromValue(String value) {
return Stream.of(values())
.filter(type -> type.getValue().equals(value))
.findFirst()
.orElse(null);
}
}
public enum FRAccountSubTypeCode {
CHARGECARD("ChargeCard"),
CREDITCARD("CreditCard"),
CURRENTACCOUNT("CurrentAccount"),
EMONEY("EMoney"),
LOAN("Loan"),
MORTGAGE("Mortgage"),
PREPAIDCARD("PrePaidCard"),
SAVINGS("Savings");
private String value;
FRAccountSubTypeCode(String value) {
this.value = value;
}
public String getValue() {
return value;
}
@JsonValue
public String toString() {
return value;
}
@JsonCreator
public static FRAccountSubTypeCode fromValue(String value) {
return Stream.of(values())
.filter(type -> type.getValue().equals(value))
.findFirst()
.orElse(null);
}
}
}
|
package kr.co.flyingturtle.repository.vo;
import java.util.List;
import org.springframework.web.multipart.MultipartFile;
public class Files{
private List<MultipartFile> attach;
private MultipartFile[] attach2;
private int fileNo;
private String oriName;
private String sysName;
private String path; //파일이 저장될 경로
private int size;
private int fileGroupNo;
private String CKEditorFuncNum; //CKEditor가 이미지 첨부할때 보내는 데이터
public String getCKEditorFuncNum() {
return CKEditorFuncNum;
}
public void setCKEditorFuncNum(String cKEditorFuncNum) {
CKEditorFuncNum = cKEditorFuncNum;
}
public MultipartFile[] getAttach2() {
return attach2;
}
public void setAttach2(MultipartFile[] attach2) {
this.attach2 = attach2;
}
public List<MultipartFile> getAttach() {
return attach;
}
public void setAttach(List<MultipartFile> attach) {
this.attach = attach;
}
public int getFileNo() {
return fileNo;
}
public void setFileNo(int fileNo) {
this.fileNo = fileNo;
}
public String getOriName() {
return oriName;
}
public void setOriName(String oriName) {
this.oriName = oriName;
}
public String getSysName() {
return sysName;
}
public void setSysName(String sysName) {
this.sysName = sysName;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public int getFileGroupNo() {
return fileGroupNo;
}
public void setFileGroupNo(int fileGroupNo) {
this.fileGroupNo = fileGroupNo;
}
}
|
/*
* 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 cocktail.cbr;
/**
*
* @author visaac
*/
public enum Garnishing {
None,
Ananas_Slice,
Anise_Basil,
Berry,
Blackcurrent,
Brown_Sugar,
Clementine_Orange,
Hazalnut_Powder,
Lemon_Slice,
Lemongrass,
Litchie,
Mint,
Pineapple,
Poppy_Seed,
Rasberry,
Shredded_Coconut,
Sugar,
Lime,
}
|
package com.helloimcole.reactor;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.*;
import com.badlogic.gdx.math.Rectangle;
/**
* Created by Cole on 6/2/2015.
*/
public class Art {
private static SpriteBatch batch;
public static OrthographicCamera camera;
//login
public static Texture sevrunImg;
public static Sprite sevrunSprite;
public static Texture lineImg;
public static void load(){
batch = new SpriteBatch();
sevrunImg = new Texture("2wkNYVF.png");
sevrunSprite = new Sprite(sevrunImg);
sevrunSprite.setOriginCenter();
sevrunSprite.setPosition(0,0);
lineImg = new Texture("line.png");
}
public static Batch getBatch(){
return batch;
}
}
|
package se.eskilson.projecteuler;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class Files {
public static String read(String name) throws IOException {
return read(new File(name));
}
private static String read(File file) throws IOException {
FileReader reader = new FileReader(file);
int fileLen = (int) file.length();
char buf[] = new char[fileLen];
reader.read(buf);
return new String(buf);
}
}
|
package com.example.tdemo;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
//http://blog.csdn.net/lanhuzi9999/article/details/31520547
public class SaveImageActivity extends Activity {
private final static String ALBUM_PATH = Environment.getExternalStorageDirectory() + "/download_test/";
private ImageView mImageView;
private Button mBtnSave;
private Bitmap mBitmap;
private String mFileName;
private Thread connectThread;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.save);
mImageView = (ImageView) findViewById(R.id.imgSource);
mBtnSave = (Button) findViewById(R.id.btnSave);
connectThread = new Thread(connect);
connectThread.start();
mBtnSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
try {
saveFile(mBitmap, mFileName);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
private Runnable connect=new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
String filePath="http://img.my.csdn.net/uploads/201402/24/1393242467_3999.jpg";
mFileName="text.jpg";
try {
mBitmap=BitmapFactory.decodeStream(getImageStream(filePath));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
connectHandler.sendEmptyMessage(0);
}
};
private Handler connectHandler=new Handler(){
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
if(mBitmap!=null) mImageView.setImageBitmap(mBitmap);
}
};
protected InputStream getImageStream(String path)throws Exception{
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(10 * 1000);
conn.setRequestMethod("GET");
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
return conn.getInputStream();
}
return null;
}
protected void saveFile(Bitmap bm, String fileName) throws IOException {
File dirFile = new File(ALBUM_PATH);
if (!dirFile.exists()) {
dirFile.mkdir();
}
File myCaptureFile = new File(ALBUM_PATH + fileName);
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(myCaptureFile));
bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
bos.flush();
bos.close();
}
}
|
package com.fajar.employeedataapi;
import java.net.URISyntaxException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.WebApplicationContext;
import lombok.extern.slf4j.Slf4j;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = App.class )
@TestPropertySource(locations = { "classpath:application.properties" })
@Slf4j
public class DogIntegrationTest {
@MockBean
private RestTemplate restTemplate;
@Autowired
private WebApplicationContext webApplicationContext;
private MockMvc mvc;
DogServiceTest test = new DogServiceTest();
@Before
public void setup() throws RestClientException, URISyntaxException {
mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
test.setRestTemplate(restTemplate);
test.init();
}
@Test
public void allBreeds() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/dogs")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.status().isOk());
}
@Test
public void breedDetail() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/dogs/"+DogServiceTest.SAMPLE_BREED)
.contentType(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.status().isOk());
}
}
|
package pro.likada.dao;
import org.hibernate.HibernateException;
import pro.likada.model.TelegramBot;
import pro.likada.model.TelegramConversation;
import pro.likada.model.TelegramUser;
import java.util.List;
/**
* Created by Yusupov on 4/2/2017.
*/
public interface TelegramConversationDAO {
TelegramConversation findById(Long id) throws HibernateException;
TelegramConversation findByChatId(Long chatId) throws HibernateException;
List<TelegramConversation> findByTelegramUser(TelegramUser telegramUser);
List<TelegramConversation> findByTelegramBot(TelegramBot telegramBot);
TelegramConversation findByTelegramUserAndTelegramBot(TelegramUser telegramUser, TelegramBot telegramBot) throws HibernateException;
List<TelegramConversation> findAll();
void save(TelegramConversation telegramConversation) throws HibernateException;
void delete(TelegramConversation telegramConversation) throws HibernateException;
void deleteById(Long id) throws HibernateException;
}
|
package NLP;
import simplenlg.features.Feature;
import simplenlg.features.Tense;
import simplenlg.framework.InflectedWordElement;
import simplenlg.framework.LexicalCategory;
import simplenlg.framework.NLGFactory;
import simplenlg.framework.WordElement;
import simplenlg.lexicon.Lexicon;
import simplenlg.phrasespec.*;
import simplenlg.realiser.english.Realiser;
public class TenseModifier {
SPhraseSpec p;
Lexicon lexicon;
NLGFactory nlgFactory;
Realiser realiser;
public TenseModifier () {
lexicon = Lexicon.getDefaultLexicon();
nlgFactory = new NLGFactory(lexicon);
realiser = new Realiser(lexicon);
}
public String changeTense(String verb, Tense tense) {
WordElement word = lexicon.getWordFromVariant(verb);
InflectedWordElement infl = new InflectedWordElement(word);
infl.setFeature(Feature.TENSE, tense);
Realiser realiser = new Realiser(lexicon);
String present = realiser.realise(infl).getRealisation();
return present;
}
}
|
package Bendispository.Abschlussprojekt.service;
import Bendispository.Abschlussprojekt.model.Request;
import Bendispository.Abschlussprojekt.model.transactionModels.ProPayAccount;
import Bendispository.Abschlussprojekt.model.transactionModels.Reservation;
import Bendispository.Abschlussprojekt.repos.PersonsRepo;
import Bendispository.Abschlussprojekt.repos.transactionRepos.LeaseTransactionRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.util.UriComponentsBuilder;
import reactor.core.publisher.Mono;
import java.net.URI;
import java.time.Duration;
@Component
public class ProPaySubscriber {
final PersonsRepo personsRepo;
final LeaseTransactionRepo leaseTransactionRepo;
private static final String SCHEME = "http";
private static final String HOST = "propay";
private static final int PORT = 8888;
@Autowired
public ProPaySubscriber(PersonsRepo personsRepo, LeaseTransactionRepo leaseTransactionRepo) {
super();
this.personsRepo = personsRepo;
this.leaseTransactionRepo = leaseTransactionRepo;
}
public int makeDeposit(Request request) {
Reservation reservation =
makeReservation(
request.getRequester().getUsername(),
request.getRequestedItem().getOwner().getUsername(),
(double) request.getRequestedItem().getDeposit());
if (reservation == null) return -1;
return reservation.getId();
}
protected Reservation makeReservation(String leaserName, String lenderName, double deposit) {
try {
final Mono<Reservation> mono = WebClient
.create()
.post()
.uri(builder ->
builder.scheme(SCHEME)
.host(HOST)
.port(PORT)
.pathSegment("reservation", "reserve", leaserName, lenderName)
.queryParam("amount", deposit)
.build())
.accept(MediaType.APPLICATION_JSON_UTF8)
.retrieve()
.bodyToMono(Reservation.class)
.timeout(Duration.ofSeconds(2L))
.retry(4L);
return mono.block();
} catch (Exception e) {
return null;
}
}
public ProPayAccount releaseReservation(String username, int id) {
try {
final Mono<ProPayAccount> mono = WebClient
.create()
.post()
.uri(builder ->
builder.scheme(SCHEME)
.host(HOST)
.port(PORT)
.pathSegment("reservation", "release", username)
.queryParam("reservationId", id)
.build())
.accept(MediaType.APPLICATION_JSON_UTF8)
.retrieve()
.bodyToMono(ProPayAccount.class)
.timeout(Duration.ofSeconds(2L))
.retry(4L);
return mono.block();
} catch (Exception e) {
return null;
}
}
public ProPayAccount releaseReservationAndPunishUser(String username, int id) {
try {
final Mono<ProPayAccount> mono = WebClient
.create()
.post()
.uri(builder ->
builder.scheme(SCHEME)
.host(HOST)
.port(PORT)
.pathSegment("reservation", "punish", username)
.queryParam("reservationId", id)
.build())
.accept(MediaType.APPLICATION_JSON_UTF8)
.retrieve()
.bodyToMono(ProPayAccount.class)
.timeout(Duration.ofSeconds(2L))
.retry(4L);
return mono.block();
} catch (Exception e) {
return null;
}
}
public boolean checkDeposit(double requiredDeposit, String username) {
ProPayAccount account = getAccount(username);
if (account == null || account.getAmount() < requiredDeposit)
return false;
return true;
}
public ProPayAccount getAccount(String username) {
try {
final Mono<ProPayAccount> mono = WebClient
.create()
.get()
.uri(builder ->
builder.scheme(SCHEME)
.host(HOST)
.port(PORT)
.pathSegment("account", username)
.build())
.accept(MediaType.APPLICATION_JSON_UTF8)
.retrieve()
.bodyToMono(ProPayAccount.class)
.timeout(Duration.ofSeconds(2L))
.retry(4L);
return mono.block();
} catch (Exception e) {
return null;
}
}
public ProPayAccount chargeAccount(String username, double value) {
try {
final Mono<ProPayAccount> mono = WebClient
.create()
.post()
.uri(builder ->
builder.scheme(SCHEME)
.host(HOST)
.port(PORT)
.pathSegment("account", username)
.queryParam("amount", value)
.build())
.accept(MediaType.APPLICATION_JSON_UTF8)
.retrieve()
.bodyToMono(ProPayAccount.class)
.timeout(Duration.ofSeconds(2L))
.retry(4L);
return mono.block();
} catch (Exception e) {
return null;
}
}
public boolean transferMoney(String leaserName, String lenderName, double amount) {
return executeTransfer(leaserName, lenderName, amount);
}
protected boolean executeTransfer(String leaserName, String lenderName, double value) {
URI uri = UriComponentsBuilder
.newInstance()
.scheme(SCHEME)
.host(HOST)
.port(PORT)
.pathSegment("account", leaserName, "transfer", lenderName)
.queryParam("amount", value)
.build()
.toUri();
try {
final Mono<HttpHeaders> mono = WebClient
.create()
.post()
.uri(uri)
.accept(MediaType.APPLICATION_JSON_UTF8)
.retrieve()
.bodyToMono(HttpHeaders.class)
.timeout(Duration.ofSeconds(2L))
.retry(4L);
mono.block();
return true;
} catch (Exception e) {
return false;
}
}
}
|
package com.cisc181.core;
import com.cisc181.eNums.eTitle;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.Date;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
public class Staff_Test {
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void main() throws PersonException {
Date date = new Date();
Staff Mascaro = new Staff("Bret", "James", "Mascaro", date, "House", "(610)-888-5643", "email@mail.com", "6-9",
9, 1.0, date, eTitle.Professor);
Staff Sarver = new Staff("Heidi", "I", "Sarver", date, "House", "(610)-888-5643", "email@mail.com", "6-9", 9,
2.0, date, eTitle.Professor);
Staff Benton = new Staff("Robert", "James", "Benton", date, "House", "(610)-888-5643", "email@mail.com", "6-9",
9, 3.0, date, eTitle.Professor);
Staff Leonard = new Staff("Brian", "James", "Leonard", date, "House", "(610)-888-5643", "email@mail.com", "6-9",
9, 4.0, date, eTitle.Professor);
Staff Bugosh = new Staff("Bri", "Jamie", "Bugosh", date, "House", "(610)-888-5643", "email@mail.com", "6-9", 9,
5.0, date, eTitle.Professor);
ArrayList<Staff> Staff = new ArrayList<Staff>();
Staff.add(Mascaro);
Staff.add(Sarver);
Staff.add(Benton);
Staff.add(Leonard);
Staff.add(Bugosh);
double sal = 0;
int counter = 0;
for (int i = 0; i < Staff.size(); i++) {
counter++;
sal = Staff.get(i).getSalary() + sal;
}
double average = sal / counter;
System.out.print(average);
assertTrue(average == 3.0);
}
@Test(expected = PersonException.class)
public void ExceptionTest1() throws PersonException {
Date date = new Date();
date.setYear(date.getYear()-120);
Staff Mascaro = new Staff("Bret", "James", "Mascaro", date, "House", "(610)-888-5643", "email@mail.com", "6-9",
9, 1.0, date, eTitle.Professor);
}
@Test(expected = PersonException.class)
public void ExceptionTest2() throws PersonException {
Date date = new Date();
Staff Mascaro = new Staff("Bret", "James", "Mascaro", date, "House", "610877885643", "email@mail.com", "6-9",
9, 1.0, date, eTitle.Professor);
}
}
|
package org.jre.sandbox.webcalc.mvc;
import javax.validation.constraints.NotNull;
public class CalcModel {
@NotNull
private String expression;
private String result;
public String getExpression() {
return expression;
}
public void setExpression(String expression) {
this.expression = expression;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
}
|
package factoring.trial.playgound;
import java.util.Collection;
/**
* This implementation is generating a list of all primes up to a limit.
* Beside of storing the prime itself, it also store the reciprocal value.
* When checking a number if it is dividable by the prime, we will not divide
* the number by the prime, we will multiply by the inverse, since this is faster.
* Due to precision we have to check for a given range near an Integer.
* And then do a Long division.
* This implementation is around two times faster then a version based on long numbers.
* Since Double only has 52 bis for the remainder, this can only work for numbers below 2^52.
* We can only factorize numbers up to maxFactor^2
* When calling it with bigger numbers only prime factors below
* maxFactor were added to the factors. {@link #findPrimeFactors(long, Collection)} then might return a
* composite number.
**
* Created by Thilo Harich on 02.03.2017.
*/
public class Trial2WayFact {
// The number of values to be printed
private static final int PRINT_NUM = 20000;
// for printing we need a value a little bit above 1
public static final double PRINT_CONST = 1.0000001;
private int maxFactor = 65535;
double[] primesInv;
int[] primes;
int maxFactorIndex = 0;
/**
* finds the prime factors up to maxFactor by the sieve of eratosthenes.
* Not optimized, since this is only called once when initializing.
*/
void initPrimesEratosthenes()
{
final double logMaxFactor = Math.log(maxFactor);
final int maxPrimeIndex = (int) ((maxFactor) / (logMaxFactor - 1.1)) + 1;
primesInv = new double [maxPrimeIndex]; //the 6542 primesInv up to 65536=2^16, then sentinel 65535 at end
primes = new int [maxPrimeIndex]; //the 6542 primesInv up to 65536=2^16, then sentinel 65535 at end
final boolean [] noPrimes = new boolean [maxFactor];
for (int i = 2; i <= Math.sqrt(maxFactor); i++) {
if (!noPrimes[i]) {
primes[maxFactorIndex] = i;
primesInv[maxFactorIndex++] = 1.0 / i;
}
for (int j = i * i; j < maxFactor; j += i) {
noPrimes[j] = true;
}
}
for (int i = (int) (Math.sqrt(maxFactor)+1); i < maxFactor; i++) {
if (!noPrimes[i]) {
primes[maxFactorIndex] = i;
primesInv[maxFactorIndex++] = 1.0 / i;
}
}
for (int i = maxFactorIndex; i < primes.length; i++) {
primes[i] = Integer.MAX_VALUE;
}
System.out.println("Prime table built max factor '" + maxFactor + "' bytes used : " + maxFactorIndex * 12);
}
public Trial2WayFact(int maxFactor) {
// if (maxFactor > 65535)
// throw new IllegalArgumentException("the maximal factor has to be lower then 65536");
this.maxFactor = maxFactor;
// initPrimes();
initPrimesEratosthenes();
}
public long findPrimeFactors(long n, Collection<Long> factors, float rangeBegin, float rangeEnd) {
for (int primeIndex = (int)(maxFactorIndex * rangeBegin); primeIndex < maxFactorIndex * rangeEnd; primeIndex++) {
// look for small primes -> high chance to find factor for random numbers
n = findPrimeFactor(n, factors, primeIndex);
// look for high primes -> for numbers around n^1/3 which is the worst case, this helps a lot
n = findPrimeFactor(n, factors, maxFactorIndex - primeIndex);
}
return n;
}
public long findPrimeFactor(long n, Collection<Long> factors, int primeIndex) {
double nDivPrime = n*primesInv[primeIndex];
// TODO choose the precision factor with respect to the maxFactor!?
if (primes[primeIndex] == 0)
System.out.println();
while (Math.abs(Math.round(nDivPrime) - nDivPrime) < 0.01 && n > 1 && n % primes[primeIndex] == 0) {
factors.add((long) primes[primeIndex]);
n = Math.round(nDivPrime);
nDivPrime = n*primesInv[primeIndex];
}
return n;
}
public void setMaxFactor(int maxTrialFactor) {
maxFactor = maxTrialFactor;
}
}
|
package aplication;
import javax.swing.JOptionPane;
import factories.AbstractFactoryMaze;
import factories.EnchantedFactoryMaze;
import factories.FactoryMaze;
public class Player {
private static MazeGame createMaze(String type) {
MazeGame game = null;
AbstractFactoryMaze factory = null;
if (type.equalsIgnoreCase("Encantado")) {
factory = new EnchantedFactoryMaze();
game = new MazeGame(factory);
} else {
factory = new FactoryMaze();
game = new MazeGame(factory);
}
return game;
}
public static void main(String[] args) {
String [] jogo = {"Encantado", "Simples"};
String input = (String) JOptionPane.showInputDialog(null, "Selecione seu tipo de jogo","Modo de jogo", JOptionPane.QUESTION_MESSAGE, null, jogo, jogo[0]);
MazeGame game = createMaze(input);
game.create();
}
}
|
package com.example.administrator.panda_channel_app.MVP_Framework.config;
import de.greenrobot.daogenerator.DaoGenerator;
import de.greenrobot.daogenerator.Entity;
import de.greenrobot.daogenerator.Schema;
/**
* Created by ASUS on 2017/7/20.
*/
public class CustomDAOGenerater {
public static void main(String[] args) throws Exception {
// 第一个参数为数据库版本
//第二个参数为数据库的包名
Schema schema = new Schema(1, "com.example.administrator.panda_channel_app.histroy");// 生成的文件夹
// 创建表,参数为表名
Entity entity = schema.addEntity("Histroy");//生成类,类名
// 为表添加字段
entity.addIdProperty();// 该字段为id
entity.addStringProperty("title");// 标题
entity.addStringProperty("img");//图片
entity.addStringProperty("time");// 时间
entity.addStringProperty("url");
// 生成数据库相关类
//第二个参数指定生成文件的本次存储路径,AndroidStudio工程指定到当前工程的java路径
new DaoGenerator().generateAll(schema, "E:\\Program Files\\ShiXun\\Panda_channel_App\\app\\src\\main\\java");
}
}
|
public class SimpleRemoteControl {
Command slot; // 커맨드를 집어넣을 슬롯은 하나밖에 없다. 이것으로 장비를 제어
public SimpleRemoteControl() {}
// 슬롯을 가지고 제어할 명령을 설정하기 위한 메소드. 이 코드를 사용하는 클라이언트에서 리모컨 버튼의 기능을 바꾸고 싶다면 이 메소드를 이용해서 얼마든지 변경 가능
public void setCommand(Command command) {
slot = command;
}
// 버튼이 눌려지면 이 메소드 호출. 지금 슬롯에 연결된 커맨드 객체의 execute()메소드만 호출하면 된다.
public void buttonWasPressed() {
slot.execute();
}
}
|
package com.miage.lesouk;
import com.miage.lesouk.entite.Annonce;
import com.miage.lesouk.entite.Commentaire;
import com.miage.lesouk.entite.Utilisateur;
import com.miage.lesouk.repository.AnnonceRepository;
import com.miage.lesouk.repository.CommentaireRepository;
import com.miage.lesouk.repository.UtilisateurRepository;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
/**
* Initialisation des données de test
* @author Youssef DARRAB - Manon FABAREZ - Aurore QUEILLE
*/
@SpringBootApplication
public class LesoukApplication implements CommandLineRunner {
/**
* Lancement de l'application
* @param args
*/
public static void main(String[] args) {
SpringApplication.run(LesoukApplication.class, args);
}
// Repository de Commentaire
@Autowired
private CommentaireRepository commentaireRepository;
// Repository de Utilisateur
@Autowired
private UtilisateurRepository utilisateurRepository;
// Repository de Annonce
@Autowired
private AnnonceRepository annonceRepository;
/**
* Run de l'application
* @param strings
* @throws Exception
*/
@Override
public void run(String... strings) throws Exception {
/** Initialisation des données de Utilisateurs ********************************************************************************/
System.out.println("[JavaDB] Initialisation des utilisateurs");
System.out.println("---- Suppression de tous les utilisateurs ----");
utilisateurRepository.deleteAll();
System.out.println("---- Ajout des utilisateurs ----");
PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
Utilisateur utilisateur1 = new Utilisateur("Fabarez", "Manon", "simplette", "simplette@bordeaux.fr", passwordEncoder.encode("s123"), "bordeaux", "france");
utilisateurRepository.save(utilisateur1);
Utilisateur utilisateur2 = new Utilisateur("Darrab", "Youssef", "dormeur", "dormeur@maroc.fr", passwordEncoder.encode("d123"), "tournefeuille", "france");
utilisateurRepository.save(utilisateur2);
Utilisateur utilisateur3 = new Utilisateur("Queille", "Aurore", "grincheuse", "grincheuse@toulouse.fr", passwordEncoder.encode("g123"), "toulouse", "france");
utilisateurRepository.save(utilisateur3);
Utilisateur utilisateur4 = new Utilisateur("Vierge", "User", "vierge", "vierge@user.fr", passwordEncoder.encode("v123"), "paris", "france");
utilisateurRepository.save(utilisateur4);
System.out.println("---- Données insérées (FindAll) ----");
for (Utilisateur utilisateur : utilisateurRepository.findAll()) {
System.out.println("id : " + utilisateur.getId() + " - Nom : " + utilisateur.getNom() + " - Prenom : " + utilisateur.getPrenom() + " - Mail : "+ utilisateur.getMail() + " - Pseudo : " + utilisateur.getPseudo() + " - Mdp : " + utilisateur.getMdp() + " - ville : "+utilisateur.getCity() + " - pays : "+utilisateur.getCountry());
}
System.out.println("---- Fin de l'initialisation de Utilisateurs ----");
/** Initialisation des données de Annonces ********************************************************************************/
System.out.println("[JavaDB] Initialisation des Annonces");
System.out.println("---- Suppression de tous les annonces ----");
annonceRepository.deleteAll();
System.out.println("---- Ajout des annonces ----");
Annonce annonce1= new Annonce("TV 4K", "Neuve, 4K", 450.00, utilisateur3, new Date(System.currentTimeMillis()-900000000));
annonce1.setCandidat(utilisateur1);
annonce1.setPrixCandidat(300.00);
annonce1.setDateCandidat(new Date());
annonce1.setEtatA("Cloturée");
annonceRepository.save(annonce1);
Annonce annonce2= new Annonce("Canard de bain", "Jaune, flotte", 3.00, utilisateur1, new Date(System.currentTimeMillis()-800000000));
annonce2.setCandidat(utilisateur2);
annonce2.setPrixCandidat(2.50);
annonce2.setEtatA("Optionnée");
annonce2.setDateCandidat(new Date());
annonceRepository.save(annonce2);
Annonce annonce3= new Annonce("Table + chaises", "Table blanche avec 4 chaises laquees", 100.00, utilisateur2, new Date(System.currentTimeMillis()-700000000));
annonce3.setCandidat(utilisateur3);
annonce3.setPrixCandidat(80.00);
annonce3.setEtatA("Optionnée");
annonce3.setDateCandidat(new Date());
annonceRepository.save(annonce3);
annonceRepository.save(new Annonce("Audi A3", "Audi A 3 - II (2) Sportback 2.0 TDI 140 S Line 7CV", 13900.00, utilisateur3, new Date(System.currentTimeMillis()-600000000)));
annonceRepository.save(new Annonce("Tableau NY", "Tableau New York, Neuf", 10.00, utilisateur1, new Date(System.currentTimeMillis()-500000000)));
annonceRepository.save(new Annonce("Hand Spinner", "Hand Spinner, vert, neuf", 6.00, utilisateur2, new Date(System.currentTimeMillis()-400000000)));
Annonce annonce7 = new Annonce("Lego Star Wars", "Lego vaisseau Star wars neuf, avec boite scéllée", 75.00, utilisateur3, new Date(System.currentTimeMillis()-300000000));
annonce7.setEtatA("Cloturée");
annonceRepository.save(annonce7);
Annonce annonce8 = new Annonce("Livre C++", "Livre usé : Comment réussir son partiel de C++ haut la main !", 10.00, utilisateur1, new Date(System.currentTimeMillis()-200000000));
annonce8.setEtatA("Cloturée");
annonceRepository.save(annonce8);
Annonce annonce9 = new Annonce("iPhone 6S", "iPhone 6S 64GO pour pièces détachées ou comme boomrang", 500.00, utilisateur2, new Date(System.currentTimeMillis()-100000000));
annonce9.setEtatA("Cloturée");
annonce9.setCandidat(utilisateur2);
annonce9.setPrixCandidat(2.50);
annonce9.setDateCandidat(new Date());
annonceRepository.save(annonce9);
System.out.println("---- Données insérées (FindAll) ----");
for (Annonce annonce : annonceRepository.findAll()) {
System.out.println("id : " + annonce.getIdA() + " - Nom : " + annonce.getNomA() + " - description : " + annonce.getDescriptionA() + " - prix : " + annonce.getPrixA() + " - Créateur : " + annonce.getCreateur().getPseudo() + " - Date Création : " + annonce.getDateCreaA() + " - Candidat : " + ((annonce.getCandidat()==null) ? null : annonce.getCandidat().getPseudo()) + " - Prix candidat : " + annonce.getPrixCandidat() + " - Date Candidat : " + annonce.getDateCandidat() + " - Etat : " + annonce.getEtatA());
}
System.out.println("---- Fin de l'initialisation de Annonces ----");
/** Initialisation des données de MongoDB --> Commentaires ********************************************************************************/
System.out.println("[MongoDB] Initialisation des données");
System.out.println("---- Suppression de tous les commentaires ----");
commentaireRepository.deleteAll();
System.out.println("---- Ajout des commentaires ----");
commentaireRepository.save(new Commentaire(1, 2, "On peut être livré par la poste ?", new Date(System.currentTimeMillis()-900000000)));
commentaireRepository.save(new Commentaire(1, 3, "On peut le faire, mais je ne rembourse pas les dégats lors de la livraison.", new Date(System.currentTimeMillis()-800000000)));
commentaireRepository.save(new Commentaire(1, 2, "La télécommande est fournie ?", new Date(System.currentTimeMillis()-700000000)));
commentaireRepository.save(new Commentaire(2, 2, "Jolie petit canard", new Date(System.currentTimeMillis()-600000000)));
commentaireRepository.save(new Commentaire(2, 3, "Déjà utilisé je pense...", new Date(System.currentTimeMillis()-500000000)));
commentaireRepository.save(new Commentaire(3, 1, "Pouvez-vous m'envoyer une photo par mail à 4ever@bordeaux.fr ?", new Date(System.currentTimeMillis()-400000000)));
commentaireRepository.save(new Commentaire(3, 3, "Les chaises sont de quelle couleur ?", new Date(System.currentTimeMillis()-300000000)));
commentaireRepository.save(new Commentaire(4, 1, "La carte grise est avec ?", new Date(System.currentTimeMillis()-200000000)));
System.out.println("---- Données insérées (FindAll) ----");
for (Commentaire commentaire : commentaireRepository.findAll()) {
System.out.println("idC : " + commentaire.getIdC() + " - idA : " + commentaire.getIdA() + " - idU : " + commentaire.getIdU() + " - texte : " + commentaire.getTexte() + " - dateCreation : " + commentaire.getDateCreation());
}
System.out.println("---- Fin de l'initialisation de MongoDB ----");
}
}
|
package cjy.njit.nj.snake;
public enum Direction {
UP, DOWN, LEFT, RIGHT;
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.gmail.iqbalsalman.Model;
/**
*
* @author iqbal
*/
import com.gmail.iqbalsalman.Dao.NasabahDao;
import com.gmail.iqbalsalman.Controller.Nasabah;
import java.sql.Connection;
import java.sql.SQLException;
import org.apache.commons.dbcp2.BasicDataSource;
/**
*
* @author iqbal
*/
public class KoneksiDB {
public static Connection koneksi() {
BasicDataSource ds = new BasicDataSource();
ds.setUsername("hr");
ds.setPassword("salman");
ds.setUrl("jdbc:postgresql://localhost:5432/hr");
ds.setDriverClassName("org.postgresql.Driver");
Connection connection = null;
try {
// membuka koneksi ke database
// System.out.println("berhasil koneksi ke database");
// NasabahDao dao = new NasabahDao(connection);
connection = ds.getConnection();
connection.setAutoCommit(false);
// dao.update(new Department(3004, "Sistem Analis", 1000, null));
// dao.delete(3003);
// untuk ambil nilainya
} catch (SQLException sqle) {
sqle.printStackTrace();
// try {
// if (connection != null) {
// connection.close();
//
// }
// }
// catch (SQLException ex) {
// ex.printStackTrace();
// }
//System.err.printf("tidak dapat koneksi ke databas!");
}
return connection;
}
}
|
package home.test.gae1;
import home.test.gae1.dataobj.TestBean;
import home.test.gae1.vmengine.VelocityEngineManager;
import java.io.IOException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletResponse;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import com.googlecode.objectify.ObjectifyService;
/**
*
* @author houdg
*
*/
public abstract class HttpAction extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 3909635295489103436L;
static {
ObjectifyService.register(TestBean.class);
}
ThreadLocal<HttpServletResponse> threadResponse = new ThreadLocal<HttpServletResponse>();
protected void init(HttpServletResponse response) {
threadResponse.set(response);
}
protected synchronized void out(String text) throws IOException {
if (threadResponse.get() == null) {
log("output error");
return;
}
threadResponse.get().getWriter().print(text);
}
protected void output(HttpServletResponse resp, VelocityContext context, String template) throws IOException {
Template t = VelocityEngineManager.getTemplate(template);
t.merge( context, resp.getWriter() );
}
} |
/*
* Copyright © 2018 www.noark.xyz All Rights Reserved.
*
* 感谢您选择Noark框架,希望我们的努力能为您提供一个简单、易用、稳定的服务器端框架 !
* 除非符合Noark许可协议,否则不得使用该文件,您可以下载许可协议文件:
*
* http://www.noark.xyz/LICENSE
*
* 1.未经许可,任何公司及个人不得以任何方式或理由对本框架进行修改、使用和传播;
* 2.禁止在本项目或任何子项目的基础上发展任何派生版本、修改版本或第三方版本;
* 3.无论你对源代码做出任何修改和改进,版权都归Noark研发团队所有,我们保留所有权利;
* 4.凡侵犯Noark版权等知识产权的,必依法追究其法律责任,特此郑重法律声明!
*/
package xyz.noark.core.annotation.controller;
import xyz.noark.core.event.Event;
import xyz.noark.core.event.FixedTimeEvent;
import java.lang.annotation.*;
/**
* 事件监听器.
*
* @author 小流氓[176543888@qq.com]
* @since 3.0
*/
@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface EventListener {
/**
* 监听的事件源类型.
* <p>
* 处理方法可以是此事件源的父类或接口,此参数优先级高于参数<br>
* 如果没有配置,默认使用事件参数的类型作为事件源类型判定<br>
* 如果事件处理方法参数为空,此处申明就是很有必需的
*
* @return 事件对象的Class类型
*/
Class<? extends Event> value() default Event.class;
/**
* 是否异步执行
* <p>
* 默认就是异步执行的,当需要同步时可以设计false<br>
* 当事件源为{@link FixedTimeEvent}类型时,同步无效
*
* @return 如果为true异步执行, 否则同步执行
*/
boolean async() default true;
/**
* 是否需要打印协议相关的日志.
*
* @return 默认为输出日志
*/
boolean printLog() default true;
} |
package com.fhsoft.model;
/**
*
* @Classname com.fhsoft.model.Zsd
* @Description
*
* @author lw
* @Date 2015-10-23 上午9:06:02
*
*/
public class Zsd {
private int id;
private int parent_id;
private String name;
private String subject;
private String code;
private String pcode;
private String is_leaf;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getParent_id() {
return parent_id;
}
public void setParent_id(int parent_id) {
this.parent_id = parent_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getPcode() {
return pcode;
}
public void setPcode(String pcode) {
this.pcode = pcode;
}
public String getIs_leaf() {
return is_leaf;
}
public void setIs_leaf(String is_leaf) {
this.is_leaf = is_leaf;
}
}
|
package fundamentos;
public class TiposPrimitivos {
public static void main(String[] args) {
//informações do funcionario
//Tipos númerico inteiros
byte anosDeEmpresa = 23;
short numeroDeVoos = 542;
int id = 56789;
long pontosAcumulados = 3_134_845_233L;
//Tipos numéricos reais
float salario = 11_445.44F;
double vendasAcumuladas = 2_991_797_103.01;
//Tipo booleano
boolean estaDeFerias = false; //true
//Tipo caractere
char status ='A'; // ativo
//Dias de empresa
System.out.println(anosDeEmpresa * 365);
//Número de viagens
System.out.println(numeroDeVoos/2);
//Pontos por real
System.out.println(pontosAcumulados/vendasAcumuladas);
System.out.println(id+": ganha -> "+ salario);
System.out.println("ferias?"+estaDeFerias);
System.out.println("Status:"+status);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.