text
stringlengths 10
2.72M
|
|---|
package antColony;
import java.util.Iterator;
import java.util.LinkedList;
/***********************************************************************************************
* Esta e a classe para as formigas.Cada formiga deve ter associada a si um caminho (path), o total
* do custo do seu caminho.
* Um agente mantem uma lista: - uma lista de historico para acompanhar o caminho que cobriu
* ate agora;
* @author Grupo 11
*
**********************************************************************************************/
public class Ant {
/* ===== ATRIBUTOS ===== */
/*****************************************************************
* Lista ligada do caminho da formiga tendo em conta os custos.
****************************************************************/
private LinkedList<pathw> p;
/* ===== CONSTRUTOR ===== */
/***************************************************************
* Construtor cujo objetivo e criar um objeto formiga com o seu
* caminho a comecar no nestnode -- ponto de partida.
*
* @param nest Ponto de Partida no grafo
**************************************************************/
public Ant(int nest)
{
pathw aux= new pathw(nest,0);
p= new LinkedList<pathw>();
p.add(aux);
}
/* ===== METODOS ==== */
/**********************************************
* Getter do caminho da formiga pelo grafo
* ja considerando os custos.
* @return p - path (caminho) da formiga
**********************************************/
public LinkedList<pathw> getP() {
return p;
}
/********************************************
* Armazenamento (setter) do caminho da formiga
* @param path - path (caminho) da formiga
********************************************/
public void setP(LinkedList<pathw> path) {
p = path;
}
/*********************************************
* Getter do caminho da formiga pelo grafo
* Usado para imprimir o caminho no fim.
* @return n - path (caminho) da formiga
********************************************/
public LinkedList<Integer> getPath()
{
Iterator<pathw> it= p.iterator();
LinkedList<Integer> n= new LinkedList<Integer>();
while(it.hasNext())
{
n.add(it.next().path);
}
return n;
}
/**********************************************
* Getter do custo do caminho da formiga.
*
* @return n - custo do caminho da formiga
**********************************************/
public LinkedList<Integer> getCost()
{
Iterator<pathw> it= p.iterator();
LinkedList<Integer> n= new LinkedList<Integer>();
while(it.hasNext())
{
n.add(it.next().Cost);
}
return n;
}
/*********************************************
*
* @return o caminho da formiga como string
* para ser impresso.
*********************************************/
public String toString()
{
return p.toString();
}
}
|
package Exception;
import java.util.Scanner;
public class Test {
private static String userName="admin";
private static String password="123456";
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入用户名:");
String sn=scanner.next();
System.out.println("请输入密码:");
String sp=scanner.next();
try {
login(sn,sp);
} catch (UserError | PasswordError e) {
e.printStackTrace();
}
}
public static void login(String userName, String password) throws UserError,
PasswordError {
if (!Test.userName.equals(userName)) {
throw new UserError("用户名错误");
}
if (!Test.password.equals(password)) {
throw new PasswordError("密码错误");
}
System.out.println("登陆成功");
}
}
|
import java.util.Scanner;
public class Fuck{
public static void main (String[] args){
double radius;
final double pi=3.14;
double area;
Scanner s = new Scanner(System.in);
System.out.print("원 반지름: ");
radius = s.nextDouble();
System.out.format("원 넓이: %.2f\n", radius*radius*pi); //이까지 했을 때 원반지름: 다음에 왜 한칸 내려가지나?
area = radius*radius*pi;
System.out.println("원 반지름: "+radius+ " 원 넓이: "+area);
System.out.printf("원 반지름: %.2f 원 넓이: %.2f\n", radius, area);
}
}
|
package com.tencent.mm.plugin.setting.ui.setting;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
class SettingsTrustFriendUI$3 implements OnClickListener {
final /* synthetic */ SettingsTrustFriendUI mUl;
SettingsTrustFriendUI$3(SettingsTrustFriendUI settingsTrustFriendUI) {
this.mUl = settingsTrustFriendUI;
}
public final void onClick(DialogInterface dialogInterface, int i) {
SettingsTrustFriendUI.h(this.mUl);
}
}
|
package com.home.closematch.entity.dto;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.home.closematch.entity.JobSeeker;
import com.home.closematch.entity.SeekerSchool;
import lombok.Data;
import java.util.Date;
/**
* admin:
* 最初版本
* 一次性获取:
* seeker账户信息
* seeker个人信息
* seeker学校信息
*/
@Data
public class SeekerAccountSchoolDTO {
// account
private Long accountId;
private String username;
// seeker
private Long seekerId;
private String name;
private Integer age;
private Integer userIdentity; // 用户身份 用户身份 0 -> 应届生 || 1 -> 职场人士
/**
* 当前状态
* 职场人
* 离职找工作
* 在职找工作
* 在职看机会
* 暂时不找工作
* 应届生
* 不用选
*/
private Integer currentStatus; // 当前用户状态
private String expectPosition;
private String expectCity;
private Integer isDelete;
// ss.school_name, ss.education, ss.start_time, ss.end_time
private String schoolName;
private Integer education;
private String domain;
@JsonFormat(pattern = "yyyy-MM-dd", timezone="GMT+8")
private Date startTime;
@JsonFormat(pattern = "yyyy-MM-dd", timezone="GMT+8")
private Date endTime;
public void setSeeker(JobSeeker jobSeeker){
// this.seekerId = jobSeeker.getId();
this.name = jobSeeker.getName();
this.age = jobSeeker.getAge();
this.userIdentity = jobSeeker.getUserIdentity();
this.currentStatus = jobSeeker.getCurrentStatus();
}
public void setSchool(SeekerSchool seekerSchool){
this.schoolName = seekerSchool.getSchoolName();
this.education = seekerSchool.getEducation();
this.domain = seekerSchool.getDomain();
}
}
|
package cn.czfshine.network.im.dto;
import lombok.Data;
import java.io.Serializable;
/**
* @author:czfshine
* @date:2019/6/9 15:02
*/
@Data
public class FileAck extends Message implements Serializable {
private String filename;
}
|
package net.sourceforge.vrapper.eclipse.ui;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.graphics.Rectangle;
/**
* A PaintListener which paints a line of text at the bottom of a component.
*
* @author Matthias Radig
*/
public class StatusLine implements PaintListener {
private final static int COMMAND_CHAR_INDENT = 5;
private int horScroll = 0;
private int verScroll = 0;
private String content = "";
private final StyledText parent;
private Rectangle currentRect;
private int position = 0;
public StatusLine(StyledText textWidget) {
this.parent = textWidget;
parent.addPaintListener(this);
}
public void paintControl(PaintEvent e) {
if ("".equals(content.trim())) {
return;
}
StyledText parent = (StyledText) e.widget;
e.gc.setForeground(parent.getForeground());
e.gc.setBackground(parent.getBackground());
int bottom = parent.getBounds().height
- parent.getHorizontalBar().getSize().y;
int right = parent.getBounds().width
- parent.getVerticalBar().getSize().x;
int height = (int) (e.gc.getFontMetrics().getHeight() * 1.5);
int offset = (int) (height / 6.0);
Rectangle rect = new Rectangle(0, bottom - height, right-1, height-1);
// if the scrollbar changed, the whole component must be repaint
if (horScroll == parent.getHorizontalBar().getSelection()
&& verScroll == parent.getVerticalBar().getSelection()) {
e.gc.setLineWidth(1);
e.gc.fillRectangle(rect);
e.gc.drawRectangle(rect);
int x1 = COMMAND_CHAR_INDENT;
e.gc.drawString(content, x1, bottom - height + offset);
// draw the caret
int y1 = bottom - height + offset;
int y2 = y1 + e.gc.getFontMetrics().getHeight();
for (int i = 0; i < position; i++) {
x1 += e.gc.getAdvanceWidth(content.charAt(i));
}
if(position == content.length()) {
//if cursor is on last position, draw a rectangle
//(matches vim behavior)
e.gc.setBackground(parent.getForeground()); //black rectangle
e.gc.fillRectangle(x1, y1, e.gc.getFontMetrics().getAverageCharWidth(), e.gc.getFontMetrics().getHeight());
}
else { //draw a caret between characters
e.gc.drawLine(x1, y1, x1, y2);
}
} else {
parent.redraw();
horScroll = parent.getHorizontalBar().getSelection();
verScroll = parent.getVerticalBar().getSelection();
}
}
/**
* @return the string that is currently displayed by this instance.
*/
public String getContent() {
return content;
}
/**
* @param content the string this instance should display.
*/
public void setContent(String content) {
this.content = content;
if (currentRect != null) {
parent.redraw(currentRect.x, currentRect.y, currentRect.width,
currentRect.height, true);
} else {
parent.redraw();
}
}
/** Set the position of the caret in characters.
*
* @param position the position of the caret in characters.
*/
public void setCaretPosition(int position) {
this.position = position;
}
/**
* Controls whether the status line will be painted into the parent component.
* @param enabled whether the status line will be painted.
*/
public void setEnabled(boolean enabled) {
if (enabled) {
parent.addPaintListener(this);
} else {
parent.removePaintListener(this);
setContent("");
currentRect = null;
}
}
}
|
// 中介模式
// 为对象构架出一个互动平台,通过减少对象间的依赖程度以达到解耦的目的
// eg.以聊天室为例
public class User {
private String name;
private ChatRoom = chatRoom;
public User(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public void login(ChatRoom chatRoom) {
this.chatRoom = chatRoom;
this.chatRoom.register(this);
}
public void talk(String msg) {
chatRoom.sendMsg(this, msg);
}
public void listen(User fromWhom, String msg) {
System.out.print("[" + this.name + "]");
System.out.println(fromWhom.getName() + "说: " + msg);
}
}
public class ChatRoom {
private String name;
public ChatRoom(String name) {
this.name = name;
}
List<User> users = new ArrayList<>();
public void register(User user) {
this.users.add(user);
System.out.println("系统消息:欢迎[" + user.getName + "]加入聊天室" + this.name);
}
public void sendMsg(User fromWhom, String msg) {
users.stream().forEach(toWhom -> toWhom.listen(fromWhom, msg));
}
}
public class Client {
public static void main(String[] args) {
ChatRoom chatRoom = new ChatRoom("NOGI");
User user = new User("akashi");
User user1 = new User("asuka");
User user2 = new User("shiori");
user.login(chatRoom);
user1.login(chatRoom);
user.talk("hi!");
user1.talk("asuu desi");
user2.login(chatRoom);
user2.talk("woooooow!");
}
}
|
package com.herbet.ffm.repository;
import com.herbet.ffm.entity.Address;
import org.springframework.data.repository.CrudRepository;
/**
* CRUD Repository for Address used as DAO.
*/
public interface AddressRepository extends CrudRepository<Address, Long> {
}
|
package com.example.pokedex;
import java.io.Serializable;
public class Pokemon implements Serializable {
private String id;
private String nom;
private Tipo tipo1;
private Tipo tipo2;
private int foto;
private String anteEvo;
private String proxEvo;
public Pokemon (String id, String nom, Tipo tipo1, Tipo tipo2, int foto, String anteEvo, String proxEvo) {
this.id = id;
this.nom = nom;
this.tipo1 = tipo1;
this.tipo2 = tipo2;
this.foto = foto;
this.anteEvo = anteEvo;
this.proxEvo = proxEvo;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public Tipo getTipo1() {
return tipo1;
}
public void setTipo1(Tipo tipo1) {
this.tipo1 = tipo1;
}
public Tipo getTipo2() {
return tipo2;
}
public void setTipo2(Tipo tipo2) {
this.tipo2 = tipo2;
}
public int getFoto() {
return foto;
}
public void setFoto(int foto) {
this.foto = foto;
}
public String getAnteEvo() {
return anteEvo;
}
public void setAnteEvo(String anteEvo) {
this.anteEvo = anteEvo;
}
public String getProxEvo() {
return proxEvo;
}
public void setProxEvo(String proxEvo) {
this.proxEvo = proxEvo;
}
}
|
package com.spbsu.flamestream.example.labels;
import com.spbsu.flamestream.core.Graph;
import com.spbsu.flamestream.core.TrackingComponent;
import com.spbsu.flamestream.example.graph_search.BreadthSearchGraph;
import com.spbsu.flamestream.runtime.FlameRuntime;
import com.spbsu.flamestream.runtime.LocalRuntime;
import com.spbsu.flamestream.runtime.acceptance.FlameAkkaSuite;
import com.spbsu.flamestream.runtime.edge.akka.AkkaFront;
import com.spbsu.flamestream.runtime.edge.akka.AkkaFrontType;
import com.spbsu.flamestream.runtime.edge.akka.AkkaRearType;
import com.spbsu.flamestream.runtime.utils.AwaitResultConsumer;
import org.testng.annotations.Test;
import scala.util.Either;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.testng.Assert.assertEquals;
public class MaterializerTest extends FlameAkkaSuite {
@Test
public void testForkAndJoinWithLabels() {
final Operator.Input<Integer> input = new Operator.Input<>(Integer.class);
final Operator.LabelSpawn<Integer, Integer> label = input.spawnLabel(Integer.class, i -> i);
final Operator.Input<Integer> union =
new Operator.Input<>(Integer.class, Collections.singleton(label))
.link(label.map(Integer.class, i -> i))
.link(label.map(Integer.class, i -> i));
final Flow<Integer, Either> flow = new Flow<>(input, union.labelMarkers(label).map(Either.class, i -> i));
final Map<Operator<?>, Materializer.StronglyConnectedComponent> stronglyConnectedComponents =
Materializer.buildStronglyConnectedComponents(flow);
assertEquals(new HashSet<>(stronglyConnectedComponents.values()).size(), stronglyConnectedComponents.size());
final Map<Materializer.StronglyConnectedComponent, TrackingComponent> trackingComponents =
Materializer.buildTrackingComponents(stronglyConnectedComponents.get(flow.output));
final Map<TrackingComponent, Set<Materializer.StronglyConnectedComponent>> trackingComponentStrongComponents =
trackingComponents.entrySet().stream().collect(Collectors.groupingBy(
Map.Entry::getValue,
Collectors.mapping(Map.Entry::getKey, Collectors.toSet())
));
assertEquals(trackingComponentStrongComponents.size(), 2);
assertEquals(
trackingComponentStrongComponents.get(
trackingComponents.get(stronglyConnectedComponents.get(flow.output))
).size(),
1
);
}
@Test
public void testImmutableBreadthSearch() throws InterruptedException {
final Flow<BreadthSearchGraph.Request, Either<BreadthSearchGraph.RequestOutput, BreadthSearchGraph.Request.Identifier>> flow =
BreadthSearchGraph.immutableFlow(__ -> new BreadthSearchGraph.HashedVertexEdges() {
@Override
public Stream<BreadthSearchGraph.VertexIdentifier> apply(BreadthSearchGraph.VertexIdentifier vertexIdentifier) {
return Stream.of(new BreadthSearchGraph.VertexIdentifier(1));
}
@Override
public int hash(BreadthSearchGraph.VertexIdentifier vertexIdentifier) {
return 0;
}
});
final Graph graph = Materializer.materialize(flow);
assertEquals(
graph.components()
.flatMap(Function.identity())
.map(graph::trackingComponent)
.collect(Collectors.toSet())
.size(),
2
);
try (final LocalRuntime runtime = new LocalRuntime.Builder().maxElementsInGraph(2)
.millisBetweenCommits(500)
.build()) {
try (final FlameRuntime.Flame flame = runtime.run(graph)) {
final BreadthSearchGraph.VertexIdentifier vertexIdentifier = new BreadthSearchGraph.VertexIdentifier(0);
final BreadthSearchGraph.Request.Identifier requestIdentifier = new BreadthSearchGraph.Request.Identifier(0);
final Queue<BreadthSearchGraph.Request> input = new ConcurrentLinkedQueue<>();
input.add(new BreadthSearchGraph.Request(requestIdentifier, vertexIdentifier, 2));
final AwaitResultConsumer<Either<BreadthSearchGraph.RequestOutput, BreadthSearchGraph.Request.Identifier>> awaitConsumer =
new AwaitResultConsumer<>(5);
flame.attachRear("wordCountRear", new AkkaRearType<>(runtime.system(), BreadthSearchGraph.OUTPUT_CLASS))
.forEach(r -> r.addListener(awaitConsumer));
final List<AkkaFront.FrontHandle<BreadthSearchGraph.Request>> handles = flame
.attachFront("wordCountFront", new AkkaFrontType<BreadthSearchGraph.Request>(runtime.system()))
.collect(Collectors.toList());
applyDataToAllHandlesAsync(input, handles);
awaitConsumer.await(200, TimeUnit.SECONDS);
}
}
}
@Test
public void testMutableBreadthSearch() {
final Flow<BreadthSearchGraph.Input, Either<BreadthSearchGraph.RequestOutput, BreadthSearchGraph.Request.Identifier>> flow =
BreadthSearchGraph.mutableFlow(__ -> new BreadthSearchGraph.HashedVertexEdges() {
@Override
public Stream<BreadthSearchGraph.VertexIdentifier> apply(BreadthSearchGraph.VertexIdentifier vertexIdentifier) {
return Stream.empty();
}
@Override
public int hash(BreadthSearchGraph.VertexIdentifier vertexIdentifier) {
return 0;
}
});
final Graph graph = Materializer.materialize(flow);
assertEquals(
graph.components()
.flatMap(Function.identity())
.map(graph::trackingComponent)
.collect(Collectors.toSet())
.size(),
2
);
}
}
|
package StockMarket;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestFactory;
import org.omg.CORBA.portable.UnknownException;
import javax.sound.sampled.Port;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.*;
import static org.junit.jupiter.api.Assertions.*;
class SimulatorTest {
Simulator simulator;
@org.junit.jupiter.api.BeforeEach
void setUp() {
simulator = new Simulator();
}
@Test
void runSimulation() {
}
@Test
void getNetWorth() {
// At initialisation:
assertEquals(simulator.getNetWorth("Pear Computing"), 32500000);
}
@Test
void getTime() {
// At initialisation:
assertEquals(simulator.getTime(), "09:00:00");
}
@Test
void getDate() {
// At initialisation:
assertEquals(simulator.getDate(), "02-01-2017");
}
@Test
void getEvent() {
// At initialisation:
assertNull(simulator.getEvent());
}
@Test
void getShareIndex() {
// At initialisation:
assertEquals(simulator.getShareIndex(), 239.5);
}
@Test
void getMarketType() {
// At initialisation:
assertEquals(simulator.getMarketType(), "Stable");
}
@Test
void getWealth() {
//Initialisation:
try {
ArrayList<Double> wealth = new ArrayList<>();
wealth.add(2.7578586E7);
wealth.add(2.1968611E7);
wealth.add(2.3219572E7);
wealth.add(3.0846637E7);
wealth.add(2.0290926E7);
wealth.add(2.4105229E7);
wealth.add(2.1926594E7);
wealth.add(2.6121013E7);
wealth.add(3.1583543E7);
wealth.add(3.3436761E7);
assertEquals(simulator.getTotalWorth(), wealth); //Should not exist
System.out.println(simulator.getTotalWorth());
} catch (IllegalArgumentException e) {
throw (e);
}
}
@Test
void getIncorrectWealth() {
//Initialisation:
try {
ArrayList<Double> wealth = new ArrayList<>();
wealth.add(2.7578586E7);
wealth.add(2.1968611E7);
wealth.add(2.3219572E7);
wealth.add(3.0846637E7);
wealth.add(2.0290926E7);
wealth.add(2.4105229E7);
wealth.add(2.1);
wealth.add(2.6121013E7);
wealth.add(3.1583543E7);
wealth.add(3.3436761E7);
assertNotSame(simulator.getTotalWorth(), wealth, "Wealth does not match - Correct"); //Should not exist
} catch (IllegalArgumentException e) {
throw (e);
}
}
@Test
void getSharePrice() throws IOException {
// At initialisation:
Iterator<String> companyNames = simulator.getCompanyNames().iterator(); // Tests getCompanyNames.
int i = 0;
HashMap<String, Integer> sharePrices = new HashMap<>();
BufferedReader br = new BufferedReader(new FileReader("InitialDataV2.csv"));
String line;
while ((line = br.readLine()) != null) {
String[] row = line.split(",");
if (row.length == Simulator.SIZE_DATA && row[0].length() != 0) {
sharePrices.put(row[0], Integer.parseInt(row[3]));
}
}
while (companyNames.hasNext()) {
String companyName = companyNames.next();
assertEquals((int) simulator.getSharePrice(companyName), (int) sharePrices.get(companyName));
i++;
}
}
@Test
void getTotalNetworth() {
List<String> companyNames = new ArrayList<>();
Set<String> companyNames1 = simulator.getCompanyNames();
companyNames.addAll(companyNames1);
for (String s : companyNames) {
int x = (int) simulator.getNetWorth(s);
assertEquals(simulator.getNetWorth(s), x);
}
}
@Test
void getIncorrectTotalNetWorth() {
List<String> companyNames = new ArrayList<>();
Set<String> companyNames1 = simulator.getCompanyNames();
companyNames.addAll(companyNames1);
for (String s : companyNames) {
int x = (int) (simulator.getNetWorth(s) + 1);
assertNotSame(simulator.getNetWorth(s), x, "Wealth does not match with false data ");
}
}
@Test
void clientLeavesSimulation() {
ArrayList clientNames = new ArrayList<String>();
clientNames.addAll(simulator.getClientNames());
for (Object s : clientNames) {
Portfolio p = new Portfolio((String) s.toString());
simulator.leaveSimulation((String) s.toString()); //set the sell all method to true in the clients portfolio
//Sell the clients shares ..assert true.
}
}
@Test
void getCashHolding() {
List<Double> cashHolding = new ArrayList<>();
cashHolding.addAll(simulator.getCashHolding());
List<Double> sampleCashHoldingData = new ArrayList<>();
sampleCashHoldingData.add(1.0E7);
sampleCashHoldingData.add(5000000.0);
sampleCashHoldingData.add(1.0E7);
sampleCashHoldingData.add(1.0E7);
sampleCashHoldingData.add(1.0E7);
sampleCashHoldingData.add(1.0E7);
sampleCashHoldingData.add(5000000.0);
sampleCashHoldingData.add(5000000.0);
sampleCashHoldingData.add(5000000.0);
sampleCashHoldingData.add(5000000.0);
assertEquals(cashHolding,sampleCashHoldingData );
}
@Test
void checkIsEndOFDay(){
assertEquals(simulator.getEndOfDay(),"Mon Jan 02 16:00:00 GMT 2017");
}
@Test
void getPortfolios(){
System.out.println(simulator.getPortfolios());
}
@Test
void testTotalSharesInPortfolio(){
assertEquals(simulator.totalSharesInPortfolios(),640188);
}
@Test
void testTotalSharesInCompany(){
System.out.println(simulator.totalSharesForCompanies());
assertEquals(simulator.totalSharesInPortfolios(),640188);
}
@Test
void testIfClientMakingMoney(){
ArrayList clientPoor = new ArrayList();
clientPoor.addAll(simulator.getTotalWorth());
double a = Double.parseDouble(String.valueOf(clientPoor.get(0)));
double b = Double.parseDouble(String.valueOf(clientPoor.get(clientPoor.size()-1)));
if(a > b ){
System.out.println("The client has lost money!");
}
if(a < b) {
System.out.println("The client has gained money!");
}
if(a == b){
System.out.println("The client has lost/gained money!");
}
}
}
|
package me.ductrader.javapractice;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Scanner;
public class Main {
public static boolean isNumeral(String param) {
try {
Integer.parseInt(param);
} catch(NumberFormatException e) {
return false;
}
return true;
}
public static int getIndex(int[] array, int element) {
for(int k = 0; k < array.length; k++) {
if(array[k] == element) {
return k;
}
}
return 0;
}
public static int getIndex(String[] array, String element) {
for(int k = 0; k < array.length; k++) {
if(array[k].equalsIgnoreCase(element)) {
return k;
}
}
return 0;
}
public static void main(String[] args) {
File in = new File("equation.in");
File out = new File("equation.out");
Calendar cal = Calendar.getInstance();
SimpleDateFormat sf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
String currentTime = sf.format(cal.getTime());
try {
in.createNewFile(); out.createNewFile();
System.out.println("Files generated!");
System.out.println("Input file: " + in.getAbsolutePath());
System.out.println("Output file: " + out.getAbsolutePath());
} catch(IOException e) {
System.out.println("An error occurred while creating files...");
e.printStackTrace();
System.out.println("Files already created, skipping...");
}
try {
Scanner sc = new Scanner(in);
FileWriter writer = new FileWriter(out);
writer.write("Output file, where results are written\n");
writer.write("Displaying all equations calculated...\n");
writer.write("Created on: " + currentTime + "\n");
while(sc.hasNextLine()) {
String s = sc.nextLine();
List<Integer> indexes = new ArrayList<Integer>();
if(!(s.isEmpty())) {
String[] p = s.split(" ");
if(p.length < 2) {
System.out.println("Invalid length!");
} else {
int val = 0;
for(String q: p) {
if(isNumeral(q)) {
val++;
indexes.add(getIndex(p, q));
}
if(val == 2) {
break;
}
}
if(val != 2) {
System.out.println("Not enough valid values!");
} else {
int a = Integer.parseInt(p[indexes.get(0)]);
int b = Integer.parseInt(p[indexes.get(1)]);
if(b == 0) {
if(a == 0) {
writer.write("Infinite values of x\n\n");
} else {
writer.write("x has a value of 0\n\n");
}
} else {
if(a == 0) {
writer.write("x has no possible value!\n\n");
} else {
writer.write("x has a value of: " + (b * -1) / a + "\n\n");
}
}
}
}
}
}
writer.flush();
writer.close();
} catch(IOException e) {
System.out.println("An error occurred!");
e.printStackTrace();
}
}
}
|
// Generated from C:/Users/Jaan/Documents/furry-dubstep/src/akt/aktk/parser\AKTK.g4 by ANTLR 4.x
package akt.aktk.parser;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.misc.NotNull;
import org.antlr.v4.runtime.tree.ErrorNode;
import org.antlr.v4.runtime.tree.TerminalNode;
/**
* This class provides an empty implementation of {@link AKTKListener},
* which can be extended to create a listener which only needs to handle a subset
* of the available methods.
*/
public class AKTKBaseListener implements AKTKListener {
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterKlassideJada(@NotNull AKTKParser.KlassideJadaContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitKlassideJada(@NotNull AKTKParser.KlassideJadaContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterFunktsioon(@NotNull AKTKParser.FunktsioonContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitFunktsioon(@NotNull AKTKParser.FunktsioonContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterKlass(@NotNull AKTKParser.KlassContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitKlass(@NotNull AKTKParser.KlassContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterKoodirida(@NotNull AKTKParser.KoodiridaContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitKoodirida(@NotNull AKTKParser.KoodiridaContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterProgramm(@NotNull AKTKParser.ProgrammContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitProgramm(@NotNull AKTKParser.ProgrammContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterMeetod(@NotNull AKTKParser.MeetodContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitMeetod(@NotNull AKTKParser.MeetodContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterSisu(@NotNull AKTKParser.SisuContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitSisu(@NotNull AKTKParser.SisuContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterCode(@NotNull AKTKParser.CodeContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitCode(@NotNull AKTKParser.CodeContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterEveryRule(@NotNull ParserRuleContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitEveryRule(@NotNull ParserRuleContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void visitTerminal(@NotNull TerminalNode node) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void visitErrorNode(@NotNull ErrorNode node) { }
}
|
package com.fancy.ownparking.ui.company.detail;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.fancy.ownparking.R;
import com.fancy.ownparking.data.local.entity.Company;
import com.fancy.ownparking.ui.base.basedetail.preview.PreviewFragment;
import com.fancy.ownparking.utils.TextUtils;
public class CompanyPreviewFragment extends PreviewFragment<Company> {
private TextView mName;
private TextView mAddress;
private TextView mComment;
private TextView mUsersCount;
public static CompanyPreviewFragment getInstance(Company company) {
Bundle args = new Bundle();
args.putParcelable(EXTRA_PREVIEW, company);
CompanyPreviewFragment companyPreviewFragment = new CompanyPreviewFragment();
companyPreviewFragment.setArguments(args);
return companyPreviewFragment;
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_company_preview, container, false);
}
@Override
public void bind(View view) {
mName = view.findViewById(R.id.text_company_name);
mAddress = view.findViewById(R.id.text_company_address);
mComment = view.findViewById(R.id.text_company_comment);
updateData(mPreviewItem);
}
@Override
public void updateData(Company item) {
mName.setText(item.getName());
TextUtils.setText(mAddress, item.getAddress(), R.string.msg_address_not_specified);
TextUtils.setText(mComment, item.getComment(), R.string.msg_comment_not_specified);
}
}
|
package com.tencent.mm.wallet_core.ui.formview;
import com.tencent.mm.wallet_core.ui.formview.a.b;
public class a$a extends b {
private int uZl;
private WalletFormView uZm;
public final /* bridge */ /* synthetic */ boolean bqk() {
return super.bqk();
}
public final /* bridge */ /* synthetic */ boolean c(WalletFormView walletFormView, String str) {
return super.c(walletFormView, str);
}
public final /* bridge */ /* synthetic */ boolean d(WalletFormView walletFormView, String str) {
return super.d(walletFormView, str);
}
public final /* bridge */ /* synthetic */ String e(WalletFormView walletFormView, String str) {
return super.e(walletFormView, str);
}
public a$a(WalletFormView walletFormView) {
this(walletFormView, (byte) 0);
}
public a$a(WalletFormView walletFormView, byte b) {
super((byte) 0);
this.uZl = 1;
this.uZm = walletFormView;
this.uZl = 1;
cDR();
}
public final void Hf(int i) {
this.uZl = i;
cDR();
}
private void cDR() {
if (this.uZl == 1) {
if (this.uZm != null) {
this.uZm.setKeyListener(new 1(this));
}
} else if (this.uZm != null) {
this.uZm.setInputType(1);
}
}
public final boolean a(WalletFormView walletFormView) {
return walletFormView.uZy == null ? false : walletFormView.uZy.isAreaIDCardNum(this.uZl);
}
}
|
package com.company.tencent;
import java.io.*;
import java.util.*;
class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
TreeNode(int v){ val = v; }
public static String printNode(TreeNode root){
Deque<TreeNode> queue = new LinkedList<>();
queue.add(root);
StringBuilder res = new StringBuilder("");
while (!queue.isEmpty()) {
int sz = queue.size();
for (int i = 0; i < sz; i++) {
TreeNode tmp = queue.pollFirst();
res.append(tmp.val+" ");
if (tmp.left != null) {
queue.add(tmp.left);
}
if (tmp.right != null) {
queue.add(tmp.right);
}
}
}
return res.toString();
}
}
public class Main {
public static void main(String[] args) throws FileNotFoundException {
// Scanner sc = new Scanner(new File("/Users/sunyindong/Downloads/quit/ShuaTi/src/main/resources/input
// .txt"));
// Scanner sc = new Scanner(System.in);
Main mymain = new Main();
TreeNode root = new TreeNode(1);
TreeNode left = new TreeNode(2);
TreeNode right = new TreeNode(3);
// root.left = left;
// System.out.println("------------");
// System.out.println(TreeNode.printNode(root));
// System.out.println(TreeNode.printNode(mymain.solve(root)));
//
// root.left = left;
// root.right = right;
// System.out.println("------------");
// System.out.println(TreeNode.printNode(root));
// System.out.println(TreeNode.printNode(mymain.solve(root)));
TreeNode four = new TreeNode(4);
TreeNode five= new TreeNode(5);
root.left = left;
root.right = right;
root.left.left = four;
root.left.right = five;
System.out.println("------------");
System.out.println(TreeNode.printNode(root));
System.out.println(TreeNode.printNode(mymain.solve(root)));
TreeNode six= new TreeNode(6);
TreeNode seven = new TreeNode(7);
root.left = left;
root.right = right;
root.left.left = four;
root.left.right = five;
root.right.left = six;
System.out.println("------------");
System.out.println(TreeNode.printNode(root));
System.out.println(TreeNode.printNode(mymain.solve(root)));
root.left = left;
root.right = right;
root.left.left = four;
root.left.right = five;
root.right.left = six;
root.right.right = seven;
System.out.println("------------");
System.out.println(TreeNode.printNode(root));
System.out.println(TreeNode.printNode(mymain.solve(root)));
TreeNode eight = new TreeNode(8);
root.left = left;
root.right = right;
root.left.left = four;
root.left.right = five;
root.right.left = six;
root.right.right = seven;
root.left.left.left = eight;
System.out.println("------------");
System.out.println(TreeNode.printNode(root));
System.out.println(TreeNode.printNode(mymain.solve(root)));
}
public TreeNode solve(TreeNode root) {
// write code here
Deque<TreeNode> queue = new LinkedList<>();
queue.add(root);
boolean isFrist = true;
int lavel = 1;
int whichLavelShouldBeRetain = 1;
int currentNeed = 1;
while (!queue.isEmpty()) {
int sz = queue.size();
if(lavel>1) currentNeed *= 2;
if (!isFrist && sz!= currentNeed) {
whichLavelShouldBeRetain = lavel - 1;
break;
}
for (int i = 0; i < sz; i++) {
TreeNode tmp = queue.pollFirst();
if (tmp.left != null) {
queue.add(tmp.left);
}
if (tmp.right != null) {
queue.add(tmp.right);
}
}
whichLavelShouldBeRetain = lavel;
lavel++;
// 接下来要遍历 lavel
isFrist = false;
}
queue.clear();
queue.add(root);
lavel = 1;
while (!queue.isEmpty()) {
int sz = queue.size();
for (int i = 0; i < sz; i++) {
if (lavel == whichLavelShouldBeRetain) {
// 到达指定层次
TreeNode tmp = queue.pollFirst();
tmp.left = null;
tmp.right = null;
} else {
TreeNode tmp = queue.pollFirst();
if (tmp.left != null) {
queue.add(tmp.left);
}
if (tmp.right != null) {
queue.add(tmp.right);
}
}
}
lavel++;
}
return root;
}
}
|
package main;
public class Calcul {
public int Somme (int a , int b){
int result = a + b;
return result;
}
public int Multiplie (int a , int b){
int result = a * b;
return result;
}
public int Soustrait (int a , int b){
int result = a - b;
return result;
}
public int Divise (int a , int b){
int result = 0;
if (b != 0) {
result = a / b;
}
return result;
}
}
|
package model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
@Entity
@Table(name="PurchaseRecord")
public class PurchaseRecordBean {
@Id
@Column(name="RecordNo")
@SequenceGenerator(name="PurchaseRecord", allocationSize=1)
@GeneratedValue(strategy = GenerationType.IDENTITY, generator="PurchaseRecord")
private int recordNo;
@Column(name="Date")
private java.util.Date date;
@Column(name="Type")
private String type;
@Column(name="Notes")
private String notes;
@Column(name="ProductId")
private String productId;
@Column(name="Number")
private String number;
@Column(name="Prize")
private String prize;
public int getRecordNo() {
return recordNo;
}
public void setRecordNo(int recordNo) {
this.recordNo = recordNo;
}
public java.util.Date getDate() {
return date;
}
public void setDate(java.util.Date date) {
this.date = date;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getPrize() {
return prize;
}
public void setPrize(String prize) {
this.prize = prize;
}
}
|
package hello.agh.edu.bazy.model;
import java.util.List;
/**
* Created by mar on 27.01.15.
*/
public class Poly {
private List<Point> polygon;
private String description;
public List<Point> getPolygon() {
return polygon;
}
public void setPolygon(List<Point> polygon) {
this.polygon = polygon;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
|
package com.tencent.mm.plugin.multitalk.a;
import android.content.Context;
import com.tencent.mm.ab.e;
import com.tencent.mm.ab.l;
import com.tencent.mm.compatible.e.q;
import com.tencent.mm.e.b.c.a;
import com.tencent.mm.model.au;
import com.tencent.mm.sdk.platformtools.ad;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.pb.talkroom.sdk.b;
import com.tencent.pb.talkroom.sdk.d;
import com.tencent.smtt.sdk.TbsListener$ErrorCode;
public final class c implements e {
a bEs = new a() {
public final void s(byte[] bArr, int i) {
if (i <= 0) {
x.e("MicroMsg.MT.MultiTalkEngine", "pcm data len <= 0");
} else if (c.this.ltd != null) {
c.this.ltd.V(bArr, i);
}
}
public final void aN(int i, int i2) {
x.i("MicroMsg.MT.MultiTalkEngine", "OnPcmRecListener onRecError %d %d", new Object[]{Integer.valueOf(i), Integer.valueOf(i2)});
}
};
public d lta;
b ltb;
com.tencent.mm.e.b.c ltc;
com.tencent.pb.talkroom.sdk.c ltd;
b lte;
com.tencent.mm.plugin.voip.model.a ltf = new 3(this);
static /* synthetic */ void a(c cVar) {
byte[] bArr = new byte[]{(byte) 0};
byte[] bArr2 = new byte[2];
if (q.deN.dci >= 0) {
bArr2[0] = (byte) q.deN.dci;
cVar.lta.setAppCmd(TbsListener$ErrorCode.INFO_MISS_SDKEXTENSION_JAR_OLD, bArr2, 1);
} else if (q.deN.dci == -2) {
cVar.lta.setAppCmd(TbsListener$ErrorCode.INFO_CAN_NOT_LOAD_X5, bArr, 1);
}
if (q.deN.dcl >= 0) {
byte[] bArr3 = new byte[5];
if (q.deN.dcm >= 0 && q.deN.dcn >= 0) {
bArr3[0] = (byte) q.deN.dcm;
bArr3[1] = (byte) q.deN.dcn;
if (q.deN.dco >= 0) {
bArr3[2] = (byte) q.deN.dco;
bArr3[3] = (byte) q.deN.dcl;
bArr3[4] = (byte) q.deN.dcp;
cVar.lta.setAppCmd(TbsListener$ErrorCode.INFO_DISABLE_X5, bArr3, 5);
} else {
cVar.lta.setAppCmd(TbsListener$ErrorCode.INFO_DISABLE_X5, bArr3, 2);
}
}
} else if (q.deN.dcl == -2) {
cVar.lta.setAppCmd(TbsListener$ErrorCode.INFO_CAN_NOT_LOAD_TBS, bArr, 1);
}
if (q.deN.dcj >= 0) {
bArr2[0] = (byte) q.deN.dcj;
cVar.lta.setAppCmd(TbsListener$ErrorCode.INFO_CAN_NOT_DISABLED_BY_CRASH, bArr2, 1);
} else if (q.deN.dcj == -2) {
cVar.lta.setAppCmd(TbsListener$ErrorCode.INFO_CAN_NOT_USE_X5_TBS_AVAILABLE, bArr, 1);
}
if (q.deN.dcu[0] > (short) 0 || q.deN.dcu[1] > (short) 0) {
bArr2[0] = (byte) 0;
bArr2[1] = (byte) 0;
if (q.deN.dcu[0] > (short) 0 && q.deN.dcu[0] < (short) 10000) {
bArr2[0] = (byte) q.deN.dcu[0];
}
if (q.deN.dcu[1] > (short) 0 && q.deN.dcu[1] < (short) 10000) {
bArr2[1] = (byte) q.deN.dcu[1];
}
cVar.lta.setAppCmd(423, bArr2, 2);
}
if (q.deN.dbL >= 0 || q.deN.dbN >= 0) {
bArr2[0] = (byte) -1;
bArr2[1] = (byte) -1;
if (q.deN.dbL >= 0) {
bArr2[0] = (byte) q.deN.dbL;
}
if (q.deN.dbN >= 0) {
bArr2[1] = (byte) q.deN.dbN;
}
cVar.lta.setAppCmd(TbsListener$ErrorCode.INFO_SDKINIT_IS_SYS_FORCED, bArr2, 2);
}
if (q.deN.dbM >= 0 || q.deN.dbO >= 0) {
bArr2[0] = (byte) -1;
bArr2[1] = (byte) -1;
if (q.deN.dbM >= 0) {
bArr2[0] = (byte) q.deN.dbM;
}
if (q.deN.dbO >= 0) {
bArr2[1] = (byte) q.deN.dbO;
}
cVar.lta.setAppCmd(TbsListener$ErrorCode.INFO_INITX5_FALSE_DEFAULT, bArr2, 2);
}
if (q.deN.dbP >= 0 || q.deN.dbQ >= 0) {
bArr2[0] = (byte) -1;
bArr2[1] = (byte) -1;
if (q.deN.dbP >= 0) {
bArr2[0] = (byte) q.deN.dbP;
}
if (q.deN.dbQ >= 0) {
bArr2[1] = (byte) q.deN.dbQ;
}
cVar.lta.setAppCmd(422, bArr2, 2);
}
if (q.deN.dbR >= 0) {
bArr2[0] = (byte) q.deN.dbR;
cVar.lta.setAppCmd(TbsListener$ErrorCode.INFO_USE_BACKUP_FILE_INSTALL_BY_SERVER, bArr2, 1);
}
if (q.deN.dbS >= 0 && q.deN.dbS != 5) {
bArr2[0] = (byte) q.deN.dbS;
cVar.lta.setAppCmd(TbsListener$ErrorCode.INFO_TEMP_CORE_EXIST_CONF_ERROR, bArr2, 1);
}
if (q.deN.dbT >= 0 && q.deN.dbT != 5) {
bArr2[0] = (byte) q.deN.dbT;
cVar.lta.setAppCmd(TbsListener$ErrorCode.INFO_CORE_EXIST_NOT_LOAD, bArr2, 1);
}
if (q.deN.dbU >= 0) {
bArr2[0] = (byte) q.deN.dbU;
cVar.lta.setAppCmd(419, bArr2, 1);
}
if (1 == q.deN.dcs) {
byte[] bArr4 = new byte[30];
for (int i = 0; i < 15; i++) {
bArr4[i * 2] = (byte) (q.deN.dct[i] & 255);
bArr4[(i * 2) + 1] = (byte) ((q.deN.dct[i] >> 8) & 255);
}
cVar.lta.setAppCmd(420, bArr4, 30);
}
if (q.deN.dcs == 0) {
cVar.lta.setAppCmd(421, bArr, 1);
}
if (q.deN.dcw > 0) {
bArr2[0] = (byte) q.deN.dcw;
cVar.lta.setAppCmd(424, bArr2, 1);
}
if (q.deN.dbV > 0) {
bArr2[0] = (byte) q.deN.dbV;
cVar.lta.setAppCmd(431, bArr2, 4);
}
if (q.deN.dcE >= 0) {
cVar.lta.setAppCmd(426, new byte[]{(byte) q.deN.dcE, (byte) q.deN.dcF, (byte) q.deN.dcG, (byte) q.deN.dcH}, 4);
}
}
public c() {
x.i("MicroMsg.MT.MultiTalkEngine", "init multiTalk engine");
Context context = ad.getContext();
com.tencent.wecall.talkroom.model.e cHL = com.tencent.wecall.talkroom.model.e.cHL();
com.tencent.wecall.talkroom.model.e.ig(context);
this.lta = cHL;
this.lta.cEI();
this.ltb = new b();
int f = bi.f((Integer) au.HS().get(1));
this.lta.a(o.bgN(), new 1(this));
this.lta.bg(f, com.tencent.mm.model.q.GF());
au.DF().a(1918, this);
au.DF().a(1919, this);
au.DF().a(1927, this);
au.DF().a(1928, this);
au.DF().a(1929, this);
au.DF().a(1931, this);
au.DF().a(1932, this);
au.DF().a(1933, this);
au.DF().a(1935, this);
au.DF().a(1937, this);
au.DF().a(1938, this);
au.DF().a(1939, this);
}
public final void a(int i, int i2, String str, l lVar) {
n nVar = (n) lVar;
x.i("MicroMsg.MT.MultiTalkEngine", "onSceneEnd errtype " + i + " errCode " + i2 + " cmdid " + nVar.isz);
this.lta.c(i2, nVar.isy, nVar.isz, nVar.cdy);
}
}
|
package menage;
import java.sql.ResultSet;
import java.sql.Connection;
import java.sql.Statement;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.Toolkit;
import java.awt.Color;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JButton;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Eighth extends JFrame {
private JPanel contentPane;
private ResultSet rs=null ;
static Connection connection ;
static Statement stmt ;
private JTextField side;
private JTextField strv;
private JTextField mide;
private JTextField mnom;
private JTextField atrav;
private JTextField ntrav;
private JTextField mprix;
private JTextField ptrav;
private JTextField ide1;
private JTextField pnom;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Eighth frame = new Eighth(connection, stmt);
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Eighth(Connection connection,Statement stmt) {
setTitle("Mise a jour");
setIconImage(Toolkit.getDefaultToolkit().getImage("C:\\Users\\admin\\Downloads\\maison-dessin-anime_11460-1609.jpg"));
this.connection= connection ;
this.stmt = stmt ;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 600, 450);
contentPane = new JPanel();
contentPane.setBackground(new Color(255, 250, 250));
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblNewLabel = new JLabel("Suppression d un participant?");
lblNewLabel.setFont(new Font("Sitka Subheading", Font.BOLD, 14));
lblNewLabel.setBounds(10, 11, 208, 14);
contentPane.add(lblNewLabel);
side = new JTextField();
side.setEnabled(false);
side.setText("...");
side.setBackground(new Color(255, 245, 238));
side.setBounds(10, 95, 89, 20);
contentPane.add(side);
side.setColumns(10);
JLabel lblNewLabel_1 = new JLabel("Donner le ide du participant");
lblNewLabel_1.setEnabled(false);
lblNewLabel_1.setFont(new Font("Sitka Subheading", Font.BOLD, 14));
lblNewLabel_1.setBounds(10, 70, 192, 14);
contentPane.add(lblNewLabel_1);
JButton btnNewButton_1 = new JButton("Done");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
String i=side.getText();
stmt.execute("delete from participant where ide="+i);
stmt.execute("delete from travaille where ide="+i);
stmt.execute("delete from paiement where ide="+i);
side.setText("");
}
catch(Exception ex) {
ex.printStackTrace();
}
}
});
btnNewButton_1.setEnabled(false);
btnNewButton_1.setFont(new Font("Sitka Subheading", Font.BOLD, 14));
btnNewButton_1.setBounds(109, 94, 89, 23);
contentPane.add(btnNewButton_1);
JButton btnNewButton = new JButton("Oui");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
side.setEnabled(true);
lblNewLabel_1.setEnabled(true);
btnNewButton_1.setEnabled(true);
}
});
btnNewButton.setBackground(new Color(255, 245, 238));
btnNewButton.setFont(new Font("Sitka Subheading", Font.BOLD, 14));
btnNewButton.setBounds(10, 36, 89, 23);
contentPane.add(btnNewButton);
JLabel lblSuppressionDUn = new JLabel("Suppression d un travaille?");
lblSuppressionDUn.setFont(new Font("Sitka Subheading", Font.BOLD, 14));
lblSuppressionDUn.setBounds(10, 126, 208, 14);
contentPane.add(lblSuppressionDUn);
JLabel lblNewLabel_1_1 = new JLabel("Donner le nom du travaille");
lblNewLabel_1_1.setFont(new Font("Sitka Subheading", Font.BOLD, 14));
lblNewLabel_1_1.setEnabled(false);
lblNewLabel_1_1.setBounds(10, 185, 192, 14);
contentPane.add(lblNewLabel_1_1);
strv = new JTextField();
strv.setText("...");
strv.setEnabled(false);
strv.setColumns(10);
strv.setBackground(new Color(255, 245, 238));
strv.setBounds(10, 210, 89, 20);
contentPane.add(strv);
JButton btnNewButton_1_1 = new JButton("Done");
btnNewButton_1_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
String i="'"+strv.getText()+"'";
stmt.execute("delete from travaille where nomt="+i);
side.setText("");
}
catch(Exception ex) {
ex.printStackTrace();
}
}
});
btnNewButton_1_1.setFont(new Font("Sitka Subheading", Font.BOLD, 14));
btnNewButton_1_1.setEnabled(false);
btnNewButton_1_1.setBounds(109, 209, 89, 23);
contentPane.add(btnNewButton_1_1);
JButton btnNewButton_2 = new JButton("Oui");
btnNewButton_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
btnNewButton_1_1.setEnabled(true);
strv.setEnabled(true);
lblNewLabel_1_1.setEnabled(true);
}
});
btnNewButton_2.setFont(new Font("Sitka Subheading", Font.BOLD, 14));
btnNewButton_2.setBackground(new Color(255, 245, 238));
btnNewButton_2.setBounds(10, 151, 89, 23);
contentPane.add(btnNewButton_2);
JLabel lblNewLabel_2 = new JLabel("Modification d un participant?");
lblNewLabel_2.setFont(new Font("Sitka Subheading", Font.BOLD, 14));
lblNewLabel_2.setBounds(244, 11, 208, 14);
contentPane.add(lblNewLabel_2);
JLabel lblNewLabel_1_2 = new JLabel("Donner le ide du participant et son nouveau nom");
lblNewLabel_1_2.setFont(new Font("Sitka Subheading", Font.BOLD, 14));
lblNewLabel_1_2.setEnabled(false);
lblNewLabel_1_2.setBounds(244, 68, 330, 14);
contentPane.add(lblNewLabel_1_2);
mide = new JTextField();
mide.setText("ide");
mide.setEnabled(false);
mide.setColumns(10);
mide.setBackground(new Color(255, 245, 238));
mide.setBounds(244, 95, 68, 20);
contentPane.add(mide);
mnom = new JTextField();
mnom.setEnabled(false);
mnom.setText("nom");
mnom.setBackground(new Color(255, 245, 238));
mnom.setBounds(339, 95, 98, 20);
contentPane.add(mnom);
mnom.setColumns(10);
JButton btnNewButton_1_2 = new JButton("Done");
btnNewButton_1_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
String i=mide.getText();
String m="'"+mnom.getText()+"'";
stmt.execute("update participant set nom="+m+"where ide="+i);
stmt.execute("update travaille set nom="+m+"where ide="+i);
stmt.execute("update paiement set nom="+m+"where ide="+i);
side.setText("");
mnom.setText("");
}
catch(Exception ex) {
ex.printStackTrace();
}
}
});
btnNewButton_1_2.setFont(new Font("Sitka Subheading", Font.BOLD, 14));
btnNewButton_1_2.setEnabled(false);
btnNewButton_1_2.setBounds(472, 95, 89, 23);
contentPane.add(btnNewButton_1_2);
JButton btnNewButton_3 = new JButton("Oui");
btnNewButton_3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
btnNewButton_1_2.setEnabled(true);
mide.setEnabled(true);
lblNewLabel_1_2.setEnabled(true);
mnom.setEnabled(true);
}
});
btnNewButton_3.setFont(new Font("Sitka Subheading", Font.BOLD, 14));
btnNewButton_3.setBackground(new Color(255, 245, 238));
btnNewButton_3.setBounds(244, 34, 89, 23);
contentPane.add(btnNewButton_3);
JButton btnNewButton_4 = new JButton("Home");
btnNewButton_4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setVisible(false);
Second s=new Second(connection,stmt);
s.setVisible(true);
}
});
btnNewButton_4.setBackground(new Color(255, 240, 245));
btnNewButton_4.setFont(new Font("Sitka Subheading", Font.BOLD, 14));
btnNewButton_4.setBounds(10, 377, 89, 23);
contentPane.add(btnNewButton_4);
JLabel lblNewLabel_2_1 = new JLabel("Modification d un travaille?");
lblNewLabel_2_1.setFont(new Font("Sitka Subheading", Font.BOLD, 14));
lblNewLabel_2_1.setBounds(244, 126, 208, 14);
contentPane.add(lblNewLabel_2_1);
JLabel lblNewLabel_1_2_1 = new JLabel("Donner l ancien et le nouveau nom du travaille");
lblNewLabel_1_2_1.setFont(new Font("Sitka Subheading", Font.BOLD, 14));
lblNewLabel_1_2_1.setEnabled(false);
lblNewLabel_1_2_1.setBounds(244, 185, 330, 14);
contentPane.add(lblNewLabel_1_2_1);
atrav = new JTextField();
atrav.setText("ancien");
atrav.setEnabled(false);
atrav.setColumns(10);
atrav.setBackground(new Color(255, 245, 238));
atrav.setBounds(244, 210, 89, 20);
contentPane.add(atrav);
ntrav = new JTextField();
ntrav.setText("nouveau");
ntrav.setEnabled(false);
ntrav.setColumns(10);
ntrav.setBackground(new Color(255, 245, 238));
ntrav.setBounds(354, 210, 98, 20);
contentPane.add(ntrav);
JButton btnNewButton_1_2_1 = new JButton("Done");
btnNewButton_1_2_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
String i="'"+ntrav.getText()+"'";
String m="'"+atrav.getText()+"'";
stmt.execute("update travaille set nomt="+i+"where nomt="+m);
ntrav.setText("");
atrav.setText("");
}
catch(Exception ex) {
ex.printStackTrace();
}
}
});
btnNewButton_1_2_1.setFont(new Font("Sitka Subheading", Font.BOLD, 14));
btnNewButton_1_2_1.setEnabled(false);
btnNewButton_1_2_1.setBounds(472, 209, 89, 23);
contentPane.add(btnNewButton_1_2_1);
JButton btnNewButton_3_1 = new JButton("Oui");
btnNewButton_3_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
atrav.setEnabled(true);
ntrav.setEnabled(true);
btnNewButton_1_2_1.setEnabled(true);
}
});
btnNewButton_3_1.setFont(new Font("Sitka Subheading", Font.BOLD, 14));
btnNewButton_3_1.setBackground(new Color(255, 245, 238));
btnNewButton_3_1.setBounds(244, 149, 89, 23);
contentPane.add(btnNewButton_3_1);
JLabel lblNewLabel_2_1_1 = new JLabel("Modification du prix du paiement?");
lblNewLabel_2_1_1.setFont(new Font("Sitka Subheading", Font.BOLD, 14));
lblNewLabel_2_1_1.setBounds(10, 257, 237, 14);
contentPane.add(lblNewLabel_2_1_1);
JLabel lblNewLabel_1_2_2 = new JLabel("Donner le prix que vous voulez");
lblNewLabel_1_2_2.setFont(new Font("Sitka Subheading", Font.BOLD, 14));
lblNewLabel_1_2_2.setEnabled(false);
lblNewLabel_1_2_2.setBounds(10, 314, 220, 14);
contentPane.add(lblNewLabel_1_2_2);
mprix = new JTextField();
mprix.setText("...");
mprix.setEnabled(false);
mprix.setColumns(10);
mprix.setBackground(new Color(255, 245, 238));
mprix.setBounds(10, 333, 89, 20);
contentPane.add(mprix);
JButton btnNewButton_1_1_1 = new JButton("Done");
btnNewButton_1_1_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
String i=mprix.getText();
stmt.execute("update paiement set somme="+i);
mprix.setText("");
}
catch(Exception ex) {
ex.printStackTrace();
}
}
});
btnNewButton_1_1_1.setFont(new Font("Sitka Subheading", Font.BOLD, 14));
btnNewButton_1_1_1.setEnabled(false);
btnNewButton_1_1_1.setBounds(109, 332, 89, 23);
contentPane.add(btnNewButton_1_1_1);
JButton btnNewButton_3_2 = new JButton("Oui");
btnNewButton_3_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
lblNewLabel_1_2_2.setEnabled(true);
mprix.setEnabled(true);
btnNewButton_1_1_1.setEnabled(true);
}
});
btnNewButton_3_2.setFont(new Font("Sitka Subheading", Font.BOLD, 14));
btnNewButton_3_2.setBackground(new Color(255, 245, 238));
btnNewButton_3_2.setBounds(10, 279, 89, 23);
contentPane.add(btnNewButton_3_2);
JLabel lblNewLabel_2_1_1_1 = new JLabel("permutation du travaille?");
lblNewLabel_2_1_1_1.setFont(new Font("Sitka Subheading", Font.BOLD, 14));
lblNewLabel_2_1_1_1.setBounds(244, 255, 237, 14);
contentPane.add(lblNewLabel_2_1_1_1);
JLabel lblNewLabel_1_2_2_1 = new JLabel("Donner le travaille a permute");
lblNewLabel_1_2_2_1.setFont(new Font("Sitka Subheading", Font.BOLD, 14));
lblNewLabel_1_2_2_1.setEnabled(false);
lblNewLabel_1_2_2_1.setBounds(244, 312, 220, 14);
contentPane.add(lblNewLabel_1_2_2_1);
ptrav = new JTextField();
ptrav.setText("...");
ptrav.setEnabled(false);
ptrav.setColumns(10);
ptrav.setBackground(new Color(255, 245, 238));
ptrav.setBounds(448, 309, 113, 20);
contentPane.add(ptrav);
JLabel lblNewLabel_1_2_2_1_1 = new JLabel("Donner le participant");
lblNewLabel_1_2_2_1_1.setFont(new Font("Sitka Subheading", Font.BOLD, 14));
lblNewLabel_1_2_2_1_1.setEnabled(false);
lblNewLabel_1_2_2_1_1.setBounds(244, 336, 220, 14);
contentPane.add(lblNewLabel_1_2_2_1_1);
ide1 = new JTextField();
ide1.setText("ide ");
ide1.setEnabled(false);
ide1.setColumns(10);
ide1.setBackground(new Color(255, 245, 238));
ide1.setBounds(244, 357, 89, 20);
contentPane.add(ide1);
pnom = new JTextField();
pnom.setText("nom");
pnom.setEnabled(false);
pnom.setColumns(10);
pnom.setBackground(new Color(255, 245, 238));
pnom.setBounds(348, 357, 89, 20);
contentPane.add(pnom);
JButton btnNewButton_1_1_1_1 = new JButton("Done");
btnNewButton_1_1_1_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
String i="'"+ptrav.getText()+"'";
String id=ide1.getText();
String n="'"+pnom.getText()+"'";
stmt.execute("update travaille set ide="+id+" and nom="+n+" where nomt="+i);}
catch (Exception e1) {
e1.printStackTrace();
}
}});
btnNewButton_1_1_1_1.setFont(new Font("Sitka Subheading", Font.BOLD, 14));
btnNewButton_1_1_1_1.setEnabled(false);
btnNewButton_1_1_1_1.setBounds(472, 358, 89, 23);
contentPane.add(btnNewButton_1_1_1_1);
JButton btnNewButton_3_2_1 = new JButton("Oui");
btnNewButton_3_2_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
btnNewButton_1_1_1_1.setEnabled(true);
pnom.setEnabled(true);
ide1.setEnabled(true);
lblNewLabel_1_2_2_1_1.setEnabled(true);
ptrav.setEnabled(true);
lblNewLabel_1_2_2_1.setEnabled(true);
}
});
btnNewButton_3_2_1.setFont(new Font("Sitka Subheading", Font.BOLD, 14));
btnNewButton_3_2_1.setBackground(new Color(255, 245, 238));
btnNewButton_3_2_1.setBounds(244, 280, 89, 23);
contentPane.add(btnNewButton_3_2_1);
}
}
|
package cn.bdqn.tangcco.dao.impl;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Scanner;
import cn.bdqn.tangcco.dao.BaseDao;
import cn.bdqn.tangcco.dao.StudentDao;
import cn.bdqn.tangcco.entity.Student;
public class StudentDaoImpl extends BaseDao implements StudentDao{
/**
* 用户登录操作
*/
public Student findUser(String uname, String pwd) {
Student student=null;
ResultSet rs=null;
try {
//3.创建statement对象,发送sql语句
String sql="SELECT * FROM `student` WHERE `studentName`=? AND `loginPwd`=?;";
Object[] params={uname,pwd};
rs=super.executeQuery(sql, params);
while (rs.next()) {
student=new Student();
student.setStudentNo(rs.getInt(1));
student.setStudentName(rs.getString("studentName"));
student.setLoginPwd(rs.getString("loginPwd"));
student.setSex(rs.getString("sex"));
student.setPhone(rs.getString("phone"));
student.setBornDate(rs.getDate("bornDate"));
}
}catch (Exception e) {
e.printStackTrace();
}finally{
this.closeAll();//关闭连接
}
return student;
}
public List<Student> getAll() {
List<Student> students=new ArrayList<Student>();
Connection conntection=null;
ResultSet rs=null;
PreparedStatement pstmt=null;
try {
Class.forName("com.mysql.jdbc.Driver");//1.加载驱动
//2.获得连接Connection对象
conntection=DriverManager.getConnection("jdbc:mysql://localhost:3306/myschool", "root","bdqn");
//3.创建statement对象,发送sql语句
String sql="SELECT s.*,g.* FROM `student` s,grade g WHERE s.`gradeId`=g.`gradeId`;";
pstmt=conntection.prepareStatement(sql);
//4.执行得到结果ResultSet并处理 数据集
rs=pstmt.executeQuery();
while (rs.next()) {
Student student=new Student();
student.setStudentNo(rs.getInt(1));
student.setStudentName(rs.getString("studentName"));
student.setLoginPwd(rs.getString("loginPwd"));
student.setSex(rs.getString("sex"));
student.setPhone(rs.getString("phone"));
student.setBornDate(rs.getDate("bornDate"));
student.setGradeId(rs.getInt("gradeId"));
student.setGradeName(rs.getString("name"));
students.add(student);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally{
try {
if(pstmt!=null){
pstmt.close();
}
if(rs!=null){
rs.close();
}
if (conntection!=null) {
conntection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
return students;
}
/**
* 修改
*/
public int updateStudent(Student student) {
int result=0;
try {
//3.创建statement对象,发送sql语句
StringBuffer sb=new StringBuffer();
sb.append("UPDATE `student` SET `loginPwd` =?, `studentName` =?," +
" `sex` =?, `gradeId` =?, `phone` =?, `address` =?, `bornDate` =? WHERE `studentNo` = ?;");
java.sql.Date dt=new java.sql.Date(student.getBornDate().getTime());
Object[] params={
student.getLoginPwd(),
student.getStudentName(),
student.getSex(),
student.getGradeId(),
student.getPhone(),
student.getAddress(),
dt,
student.getStudentNo()
};
result=super.executeUpdate(sb.toString(), params);
}catch (Exception e) {
e.printStackTrace();
}finally{
}
return result;
}
public int addStudent(Student student) {
int result=0;
Connection conntection=null;
PreparedStatement pstmt=null;
try {
Class.forName("com.mysql.jdbc.Driver");//1.加载驱动
//2.获得连接Connection对象
conntection=DriverManager.getConnection("jdbc:mysql://localhost:3306/myschool", "root","bdqn");
//3.创建statement对象,发送sql语句
StringBuffer sb=new StringBuffer();
sb.append("INSERT INTO `student` (`studentNo`,`loginPwd`,");
sb.append("`studentName`,`sex`,`gradeId`,`phone`,`address`,`bornDate`)");
sb.append("VALUES (?,?,?,?,?,?,?,?);");
pstmt=conntection.prepareStatement(sb.toString());
pstmt.setInt(1, student.getStudentNo());
pstmt.setString(2, student.getLoginPwd());
pstmt.setString(3, student.getStudentName());
pstmt.setString(4, student.getSex());
pstmt.setInt(5, student.getGradeId());
pstmt.setString(6, student.getPhone());
pstmt.setString(7, student.getAddress());
java.sql.Date dt=new java.sql.Date(student.getBornDate().getTime());
pstmt.setDate(8, dt);
//4.执行得到结果ResultSet并处理 数据集
result=pstmt.executeUpdate();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally{
try {
if(pstmt!=null){
pstmt.close();
}
if (conntection!=null) {
conntection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
return result;
}
public Student searchByStuNo(int stuNo) {
Student student=null;
Connection conntection=null;
ResultSet rs=null;
PreparedStatement pstmt=null;
try {
Class.forName("com.mysql.jdbc.Driver");//1.加载驱动
//2.获得连接Connection对象
conntection=DriverManager.getConnection("jdbc:mysql://localhost:3306/myschool", "root","bdqn");
//3.创建statement对象,发送sql语句
String sql="SELECT * FROM `student`,`grade` WHERE student.`gradeId`=grade.`gradeId` AND `studentNo`=?;";
pstmt=conntection.prepareStatement(sql);
pstmt.setInt(1, stuNo);
//4.执行得到结果ResultSet并处理 数据集
rs=pstmt.executeQuery();
while (rs.next()) {
student=new Student();
student.setStudentNo(rs.getInt(1));
student.setStudentName(rs.getString("studentName"));
student.setLoginPwd(rs.getString("loginPwd"));
student.setSex(rs.getString("sex"));
student.setPhone(rs.getString("phone"));
student.setBornDate(rs.getDate("bornDate"));
student.setGradeName(rs.getString("name"));
student.setGradeId(rs.getInt("gradeId"));
student.setAddress(rs.getString("address"));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally{
try {
if(pstmt!=null){
pstmt.close();
}
if(rs!=null){
rs.close();
}
if (conntection!=null) {
conntection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
return student;
}
public int delStudent(int stuNo) {
int result=0;
try {
//3.创建statement对象,发送sql语句
StringBuffer sb=new StringBuffer();
sb.append("DELETE FROM `student` WHERE `studentNo`=?");
Object[] params={stuNo};
result=super.executeUpdate(sb.toString(), params);
} catch (Exception e) {
e.printStackTrace();
}finally{
}
return result;
}
/**
* 统计总记录数
*/
public int getTotalCount() {
int total=0;
try {
Object[] params={};
String sql="SELECT COUNT(*) FROM `student`;";
ResultSet rs=super.executeQuery(sql, params);
while (rs.next()) {
total=rs.getInt(1);
}
} catch (SQLException e) {
e.printStackTrace();
}
return total;
}
/**
* 统计每页显示学员信息
* @param pageIndex 页号
* @param pageSize 每页显示总记录数
* @return 学员信息
*/
public List<Student> getStudents(int pageIndex, int pageSize) {
int start=(pageIndex-1)*pageSize;
Object[] params={start,pageSize};
List<Student> students=new ArrayList<Student>();
try {
String sql="SELECT * FROM student s, grade g WHERE s.`gradeId` = g.`gradeId` ORDER BY `studentNo` desc LIMIT ?, ?";
ResultSet rs=super.executeQuery(sql, params);
while (rs.next()) {
Student student=new Student();
student.setStudentNo(rs.getInt(1));
student.setStudentName(rs.getString("studentName"));
student.setLoginPwd(rs.getString("loginPwd"));
student.setSex(rs.getString("sex"));
student.setPhone(rs.getString("phone"));
student.setBornDate(rs.getDate("bornDate"));
student.setGradeId(rs.getInt("gradeId"));
student.setGradeName(rs.getString("name"));
students.add(student);
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
super.closeAll();
}
System.out.println(pageIndex);
return students;
}
public static void main(String[] args) {
StudentDaoImpl stuDao=new StudentDaoImpl();
int total=stuDao.getTotalCount();
int pageIndex=3;
int pageSize=3;
int totalPages=(total%pageSize==0)?(total/pageSize):(total/pageSize+1);
System.out.println("总记录数:"+total);
System.out.println("总页数:"+totalPages);
System.out.println("当前页:"+pageIndex);
System.out.println("当前页信息:");
List<Student> students=stuDao.getStudents(pageIndex, pageSize);
for (Student student : students) {
System.out.println(student.getStudentNo()+"\t"+student.getStudentName()+"\t"+student.getGradeName());
}
}
public List<Student> searchByName(String name) {
List<Student> students=new ArrayList<Student>();
ResultSet rs=null;
try {
Object[] params={name};
String sql="SELECT * FROM `student` WHERE `studentName`=?;";
rs=super.executeQuery(sql, params);
while (rs.next()) {
Student student=new Student();
student.setStudentNo(rs.getInt(1));
student.setStudentName(rs.getString("studentName"));
student.setLoginPwd(rs.getString("loginPwd"));
student.setSex(rs.getString("sex"));
student.setPhone(rs.getString("phone"));
student.setBornDate(rs.getDate("bornDate"));
students.add(student);
}
} catch (Exception e) {
e.printStackTrace();
}finally{
super.closeAll();
}
return students;
}
}
|
/*
* Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.experimental.bytecode;
import java.util.function.Consumer;
import java.util.function.ToIntBiFunction;
public class AnnotationsBuilder<S, T, E> extends AbstractBuilder<S, T, E, AnnotationsBuilder<S, T, E>> {
GrowableByteBuffer annoAttribute;
int nannos;
AnnotationsBuilder(PoolHelper<S, T, E> poolHelper, TypeHelper<S, T> typeHelper) {
super(poolHelper, typeHelper);
this.annoAttribute = new GrowableByteBuffer();
annoAttribute.writeChar(0);
}
public enum Kind {
RUNTIME_VISIBLE,
RUNTIME_INVISIBLE;
}
enum Tag {
B('B'),
C('C'),
D('D'),
F('F'),
I('I'),
J('J'),
S('S'),
Z('Z'),
STRING('s'),
ENUM('e'),
CLASS('c'),
ANNO('@'),
ARRAY('[');
char tagChar;
Tag(char tagChar) {
this.tagChar = tagChar;
}
}
AnnotationsBuilder<S, T, E> withAnnotation(T annoType, Consumer<? super AnnotationElementBuilder> annotationBuilder) {
annoAttribute.writeChar(poolHelper.putType(annoType));
int offset = annoAttribute.offset;
annoAttribute.writeChar(0);
if (annotationBuilder != null) {
AnnotationElementBuilder _builder = new AnnotationElementBuilder();
int nelems = _builder.withElements(annotationBuilder);
patchCharAt(offset, nelems);
}
nannos++;
return this;
}
byte[] build() {
patchCharAt(0, nannos);
return annoAttribute.bytes();
}
private void patchCharAt(int offset, int newChar) {
int prevOffset = annoAttribute.offset;
try {
annoAttribute.offset = offset;
annoAttribute.writeChar(newChar);
} finally {
annoAttribute.offset = prevOffset;
}
}
@SuppressWarnings({"unchecked", "rawtypes"})
static Consumer NO_BUILDER =
new Consumer() {
@Override
public void accept(Object o) {
//do nothing
}
};
public class AnnotationElementBuilder {
int nelems;
public AnnotationElementBuilder withString(String name, String s) {
annoAttribute.writeChar(poolHelper.putUtf8(name));
writeStringValue(s);
return this;
}
private void writeStringValue(String s) {
annoAttribute.writeByte(Tag.STRING.tagChar);
annoAttribute.writeChar(poolHelper.putUtf8(s));
nelems++;
}
public AnnotationElementBuilder withClass(String name, T s) {
annoAttribute.writeChar(poolHelper.putUtf8(name));
writeClassValue(s);
return this;
}
private void writeClassValue(T s) {
annoAttribute.writeByte(Tag.CLASS.tagChar);
annoAttribute.writeChar(poolHelper.putType(s));
nelems++;
}
public AnnotationElementBuilder withEnum(String name, T enumType, int constant) {
annoAttribute.writeChar(poolHelper.putUtf8(name));
writeEnumValue(enumType, constant);
return this;
}
private void writeEnumValue(T enumType, int constant) {
annoAttribute.writeByte(Tag.ENUM.tagChar);
annoAttribute.writeChar(poolHelper.putType(enumType));
annoAttribute.writeChar(constant);
nelems++;
}
public AnnotationElementBuilder withAnnotation(String name, T annoType, Consumer<? super AnnotationElementBuilder> annotationBuilder) {
annoAttribute.writeChar(poolHelper.putUtf8(name));
writeAnnotationValue(annoType, annotationBuilder);
return this;
}
private void writeAnnotationValue(T annoType, Consumer<? super AnnotationElementBuilder> annotationBuilder) {
annoAttribute.writeByte(Tag.ANNO.tagChar);
annoAttribute.writeChar(poolHelper.putType(annoType));
int offset = annoAttribute.offset;
annoAttribute.writeChar(0);
int nelems = withNestedElements(annotationBuilder);
patchCharAt(offset, nelems);
this.nelems++;
}
public AnnotationElementBuilder withPrimitive(String name, char c) {
annoAttribute.writeChar(poolHelper.putUtf8(name));
writePrimitiveValue(Tag.C, (int)c, PoolHelper::putInt);
return this;
}
public AnnotationElementBuilder withPrimitive(String name, short s) {
annoAttribute.writeChar(poolHelper.putUtf8(name));
writePrimitiveValue(Tag.S, (int)s, PoolHelper::putInt);
return this;
}
public AnnotationElementBuilder withPrimitive(String name, byte b) {
annoAttribute.writeChar(poolHelper.putUtf8(name));
writePrimitiveValue(Tag.B, (int)b, PoolHelper::putInt);
return this;
}
public AnnotationElementBuilder withPrimitive(String name, int i) {
annoAttribute.writeChar(poolHelper.putUtf8(name));
writePrimitiveValue(Tag.I, i, PoolHelper::putInt);
return this;
}
public AnnotationElementBuilder withPrimitive(String name, float f) {
annoAttribute.writeChar(poolHelper.putUtf8(name));
writePrimitiveValue(Tag.F, f, PoolHelper::putFloat);
return this;
}
public AnnotationElementBuilder withPrimitive(String name, long l) {
annoAttribute.writeChar(poolHelper.putUtf8(name));
writePrimitiveValue(Tag.J, l, PoolHelper::putLong);
return this;
}
public AnnotationElementBuilder withPrimitive(String name, double d) {
annoAttribute.writeChar(poolHelper.putUtf8(name));
writePrimitiveValue(Tag.D, d, PoolHelper::putDouble);
return this;
}
public AnnotationElementBuilder withPrimitive(String name, boolean b) {
annoAttribute.writeChar(poolHelper.putUtf8(name));
writePrimitiveValue(Tag.Z, b ? 1 : 0, PoolHelper::putInt);
return this;
}
private <Z> void writePrimitiveValue(Tag tag, Z value, ToIntBiFunction<PoolHelper<S, T, E>, Z> poolFunc) {
annoAttribute.writeByte(tag.tagChar);
annoAttribute.writeChar(poolFunc.applyAsInt(poolHelper, value));
nelems++;
}
AnnotationElementBuilder withStrings(String name, String... ss) {
annoAttribute.writeChar(poolHelper.putUtf8(name));
annoAttribute.writeChar(ss.length);
for (String s : ss) {
writeStringValue(s);
}
return this;
}
@SuppressWarnings("unchecked")
AnnotationElementBuilder withClasses(String name, T... cc) {
annoAttribute.writeChar(poolHelper.putUtf8(name));
annoAttribute.writeChar(cc.length);
for (T c : cc) {
writeClassValue(c);
}
return this;
}
AnnotationElementBuilder withEnums(String name, T enumType, int... constants) {
annoAttribute.writeChar(poolHelper.putUtf8(name));
annoAttribute.writeChar(constants.length);
for (int c : constants) {
writeEnumValue(enumType, c);
}
return this;
}
@SuppressWarnings("unchecked")
public AnnotationElementBuilder withAnnotations(String name, T annoType, Consumer<? super AnnotationElementBuilder>... annotationBuilders) {
annoAttribute.writeChar(poolHelper.putUtf8(name));
annoAttribute.writeChar(annotationBuilders.length);
for (Consumer<? super AnnotationElementBuilder> annotationBuilder : annotationBuilders) {
writeAnnotationValue(annoType, annotationBuilder);
}
return this;
}
public AnnotationElementBuilder withPrimitives(String name, char... cc) {
annoAttribute.writeChar(poolHelper.putUtf8(name));
annoAttribute.writeChar(cc.length);
for (char c : cc) {
writePrimitiveValue(Tag.C, (int)c, PoolHelper::putInt);
}
return this;
}
public AnnotationElementBuilder withPrimitives(String name, short... ss) {
annoAttribute.writeChar(poolHelper.putUtf8(name));
annoAttribute.writeChar(ss.length);
for (short s : ss) {
writePrimitiveValue(Tag.S, (int)s, PoolHelper::putInt);
}
return this;
}
public AnnotationElementBuilder withPrimitives(String name, byte... bb) {
annoAttribute.writeChar(poolHelper.putUtf8(name));
annoAttribute.writeChar(bb.length);
for (byte b : bb) {
writePrimitiveValue(Tag.B, (int)b, PoolHelper::putInt);
}
return this;
}
public AnnotationElementBuilder withPrimitives(String name, int... ii) {
annoAttribute.writeChar(poolHelper.putUtf8(name));
annoAttribute.writeChar(ii.length);
for (int i : ii) {
writePrimitiveValue(Tag.I, i, PoolHelper::putInt);
}
return this;
}
public AnnotationElementBuilder withPrimitives(String name, float... ff) {
annoAttribute.writeChar(poolHelper.putUtf8(name));
annoAttribute.writeChar(ff.length);
for (float f : ff) {
writePrimitiveValue(Tag.F, f, PoolHelper::putFloat);
}
return this;
}
public AnnotationElementBuilder withPrimitives(String name, long... ll) {
annoAttribute.writeChar(poolHelper.putUtf8(name));
annoAttribute.writeChar(ll.length);
for (long l : ll) {
writePrimitiveValue(Tag.J, l, PoolHelper::putLong);
}
return this;
}
public AnnotationElementBuilder withPrimitives(String name, double... dd) {
annoAttribute.writeChar(poolHelper.putUtf8(name));
annoAttribute.writeChar(dd.length);
for (double d : dd) {
writePrimitiveValue(Tag.D, d, PoolHelper::putDouble);
}
return this;
}
public AnnotationElementBuilder withPrimitives(String name, boolean... bb) {
annoAttribute.writeChar(poolHelper.putUtf8(name));
annoAttribute.writeChar(bb.length);
for (boolean b : bb) {
writePrimitiveValue(Tag.Z, b ? 1 : 0, PoolHelper::putInt);
}
return this;
}
int withNestedElements(Consumer<? super AnnotationElementBuilder> annotationBuilder) {
return withElements(new AnnotationElementBuilder(), annotationBuilder);
}
int withElements(Consumer<? super AnnotationElementBuilder> annotationBuilder) {
return withElements(this, annotationBuilder);
}
private int withElements(AnnotationElementBuilder builder, Consumer<? super AnnotationElementBuilder> annotationBuilder) {
annotationBuilder.accept(builder);
return builder.nelems;
}
}
}
|
package com.ssafy.algo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Comparator;
import java.util.StringTokenizer;
/*
ACMICPC
문제 번호 : 1931
문제 제목 : 회의실배정
풀이 날짜 : 2020-08-06
Solved By Reamer
*/
public class acm_1931 {
static class Pair implements Comparable<Pair> {
int x, y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
public int compareTo(Pair o) {
if (this.y == o.y)
return this.x - o.x;
return this.y - o.y;
}
public String toString() {
return "Pair [x=" + x + ", y=" + y + "]";
}
}
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
int N = Integer.parseInt(br.readLine());
Pair[] pair = new Pair[N];
for (int i = 0; i < N; i++) {
st = new StringTokenizer(br.readLine(), " ");
int from = Integer.parseInt(st.nextToken());
int to = Integer.parseInt(st.nextToken());
pair[i] = new Pair(from, to);
}
Arrays.sort(pair);
int cnt = 1;
int prevStart = pair[0].x;
int prevEnd = pair[0].y;
for (int i = 1; i < N; i++) {
if (pair[i].x >= prevEnd) {
prevStart = pair[i].x;
prevEnd = pair[i].y;
cnt++;
}
}
System.out.println(cnt);
}
}
|
package steps;
import pages.Onboarding_Page;
import base.TestBase;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
public class Onboarding_steps extends TestBase {
Onboarding_Page onboard = new Onboarding_Page(driver);
@Given("I am in Welcome screen")
public void i_am_in_Welcome_screen() {
onboard.isUserInWelcomeScreen();
}
@When("I login with valid credential")
public void i_login_with_valid_credential() {
onboard.userSignUpProcess();
}
@When("accept the cookies confirmation")
public void accept_the_cookies_confirmation() {
onboard.acceptCookies();
}
@Then("I am in the home screen")
public void i_am_in_the_home_screen() {
onboard.isUserInHomeScreen();
}
@When("I select the hamburger menu")
public void i_select_the_hamburger_menu() {
onboard.launchHamburgerMenu();
}
@Then("I can dismiss the menu list")
public void i_can_dismiss_the_menu_list() {
onboard.disMissMenuList();
}
@When("I select the icon")
public void i_select_the_icon() {
onboard.launchProfile();
}
@Then("the profile details as the contact as {string}")
public void the_profile_details_as_the_contact_as(String string) {
onboard.getContactDetail(string);
}
@When("I navigate to home screen")
public void i_navigate_to_home_screen() {
onboard.backtoHomeScreen();
}
@When("I scroll down to view the Communities that are listed")
public void i_scroll_down_to_view_the_Communities_that_are_listed() {
onboard.scrollInHomeScreen();
}
@When("I logout")
public void i_logout() {
onboard.logOut();
}
@Then("I see that the user is navigated to Welcome screen")
public void i_see_that_the_user_is_navigated_to_Welcome_screen() {
onboard.isUserInWelcomeScreen();
}
}
|
package net.sssanma.mc.minigame;
public class MiniGameException extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
public MiniGameException(String paramString) {
super(paramString);
}
public MiniGameException(Throwable arg0) {
super(arg0);
}
public MiniGameException(String arg0, Throwable arg1) {
super(arg0, arg1);
}
}
|
package cz.uhk.restaurace.web;
import cz.uhk.restaurace.model.*;
import cz.uhk.restaurace.service.DishGeneralService;
import cz.uhk.restaurace.service.DishLocService;
import cz.uhk.restaurace.service.IngredientLocService;
import cz.uhk.restaurace.service.IngredientGeneralService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
/**
* Created by dann on 15.11.2014.
*/
@Controller
public class DishController {
@Autowired
private DishLocService dishLocService;
@Autowired
private DishGeneralService dishGeneralService;
@Autowired
private IngredientLocService ingredientLocService;
@Autowired
private IngredientGeneralService ingredientGeneralService;
private String language = "cs";
public void setLanguage(String language, HttpSession session) {
this.language = language;
}
/**
* Create dish and store it in a session if not yet done, than return a page with localized ingredient names
* @param session
* @param model
* @return
*/
@RequestMapping(value = "/teppanyaki", method = RequestMethod.GET)
public String showTeppanyakiHighLevel(HttpSession session, Model model) {
DishGeneral dish = (DishGeneral)session.getAttribute("teppanyakiDish");
if (dish == null) {
dish = dishGeneralService.createDish();
session.setAttribute("teppanyakiDish", dish);
}
ingredientGeneralService.actualizeLocFieldsOnIngredients(dish.getIngredients(), this.language);
model.addAttribute("ingredientTypes", ingredientGeneralService.getIngredientTypes());
return "teppanyaki";
}
/**
* Get page with localized list of ingredients according to chosen ingredient category
* @param session
* @param model
* @param ingredient
* @return
*/
@RequestMapping(value = "/teppanyaki/{ingredient}")
public String showIngredientsByCategory(HttpSession session, Model model, @PathVariable("ingredient") String ingredient) {
DishGeneral dish = (DishGeneral)session.getAttribute("teppanyakiDish");
if (dish == null) {
dish = dishGeneralService.createDish();
session.setAttribute("teppanyakiDish", dish);
}
IngredientGeneral.IngredientType category = null;
for (IngredientGeneral.IngredientType type : IngredientGeneral.IngredientType
.values()) {
if (ingredient.equals(type.getUrl())) {
category = type;
}
}
ingredientGeneralService.actualizeLocFieldsOnIngredients(dish.getIngredients(), this.language);
model.addAttribute("ingredients", ingredientGeneralService.getIngredientsByCategory(category, this.language));
model.addAttribute("ingredientTypes", ingredientGeneralService.getIngredientTypes());
return "teppanyaki";
}
/**
* Add ingredient to teppanyaki dish, return json to ajax event handler
* @param session
* @param id
* @param grams
* @return
*/
//TODO doimplementovat, checknout potencialni duplicity v mape
@RequestMapping(value = "/addIngredient", method = RequestMethod.GET, produces = "application/json")
@ResponseBody
public IngredientGeneral addIngredient(HttpSession session, @RequestParam Integer id,
@RequestParam(required = false) String grams){
DishGeneral dish = (DishGeneral) session.getAttribute("teppanyakiDish");
if (dish == null) {
dish = dishGeneralService.createDish();
session.setAttribute("teppanyakiDish", dish);
}
IngredientGeneral ingredient = null;
if (dish != null) {
ingredient = ingredientGeneralService.getIngredientById(id);
ingredient.setIngredientLocalized(ingredientGeneralService.getIngredientLocalized(ingredient.getId(), this.language));
ingredient.setGrams(Integer.parseInt(grams));
dish.getIngredients().put(id, ingredient);
}
return ingredient;
}
@RequestMapping(value = "/removeIngredient", method = RequestMethod.GET)
public String removeIngredient(HttpSession session, @RequestParam("category") String category,
@RequestParam("id") Integer id) {
DishGeneral dish = (DishGeneral) session
.getAttribute("teppanyakiDish");
dish.getIngredients().remove(id);
return "redirect:/teppanyaki/" + category;
}
/**
* Show all drinks
* @param session
* @param model
* @return
*/
@RequestMapping(value = "/drinks", method = RequestMethod.GET)
public String showDrinks(HttpSession session, Model model){
model.addAttribute("drinksToShow", true);
model.addAttribute("drinks", dishGeneralService.listDrinks(this.language));
return "menu";
}
/**
* Show all dishes
* @param model
* @return
*/
@RequestMapping(value = "/dishes", method = RequestMethod.GET)
public String showDishes(Model model){
model.addAttribute("dishesToShow", true);
model.addAttribute("dishes", dishGeneralService.listDishes(this.language));
return "menu";
}
/**
* Show all food
* @param session
* @param model
* @return
*/
@RequestMapping(value = "/menu", method = RequestMethod.GET)
public String showAllProducts(HttpSession session, Model model){
model.addAttribute("dishesToShow", true);
model.addAttribute("drinksToShow", true);
model.addAttribute("dishes", dishGeneralService.listDishes(this.language));
model.addAttribute("drinks", dishGeneralService.listDrinks(this.language));
return "menu";
}
//nemazat, pripravena metoda pro ajax
/*@RequestMapping(value = "/removeIngredient", method = RequestMethod.GET)
@ResponseBody
public Integer removeIngredient(HttpSession session, @RequestParam("id") Integer id) {
DishLocalized dish = (DishLocalized) session.getAttribute("teppanyakiDish");
dish.getIngredientsLocalized().remove(id);
return id;
}*/
}
|
//import java.util.Locale;
public class Main {
public static void main(String[] args) {
System.out.println("Hello world");
String nome = "Maria";
int idade = 30;
double renda = 4000.0;
//Locale.setDefault(Locale.US);
System.out.printf("%s tem %d anos e uma renda de %.2f", nome, idade, renda);
}
}
|
/* 1: */ package com.kaldin.user.adminprofile.form;
/* 2: */
/* 3: */ import org.apache.struts.action.ActionForm;
/* 4: */
/* 5: */ public class EmailSettingForm
/* 6: */ extends ActionForm
/* 7: */ {
/* 8: */ private static final long serialVersionUID = 1L;
/* 9:12 */ private String host = "";
/* 10:14 */ private String mailFrom = "";
/* 11:16 */ private String port = "";
/* 12:18 */ private String userName = "";
/* 13:20 */ private String password = "";
/* 14:22 */ private String auth = "";
/* 15:24 */ private String action = "";
/* 16: */
/* 17: */ public String getHost()
/* 18: */ {
/* 19:27 */ return this.host;
/* 20: */ }
/* 21: */
/* 22: */ public void setHost(String host)
/* 23: */ {
/* 24:31 */ this.host = host;
/* 25: */ }
/* 26: */
/* 27: */ public String getMailFrom()
/* 28: */ {
/* 29:35 */ return this.mailFrom;
/* 30: */ }
/* 31: */
/* 32: */ public void setMailFrom(String mailFrom)
/* 33: */ {
/* 34:39 */ this.mailFrom = mailFrom;
/* 35: */ }
/* 36: */
/* 37: */ public String getPort()
/* 38: */ {
/* 39:43 */ return this.port;
/* 40: */ }
/* 41: */
/* 42: */ public void setPort(String port)
/* 43: */ {
/* 44:47 */ this.port = port;
/* 45: */ }
/* 46: */
/* 47: */ public String getUserName()
/* 48: */ {
/* 49:51 */ return this.userName;
/* 50: */ }
/* 51: */
/* 52: */ public void setUserName(String userName)
/* 53: */ {
/* 54:55 */ this.userName = userName;
/* 55: */ }
/* 56: */
/* 57: */ public String getPassword()
/* 58: */ {
/* 59:59 */ return this.password;
/* 60: */ }
/* 61: */
/* 62: */ public void setPassword(String password)
/* 63: */ {
/* 64:63 */ this.password = password;
/* 65: */ }
/* 66: */
/* 67: */ public String getAuth()
/* 68: */ {
/* 69:67 */ return this.auth;
/* 70: */ }
/* 71: */
/* 72: */ public void setAuth(String auth)
/* 73: */ {
/* 74:71 */ this.auth = auth;
/* 75: */ }
/* 76: */
/* 77: */ public String getAction()
/* 78: */ {
/* 79:75 */ return this.action;
/* 80: */ }
/* 81: */
/* 82: */ public void setAction(String action)
/* 83: */ {
/* 84:79 */ this.action = action;
/* 85: */ }
/* 86: */ }
/* Location: C:\Java Work\Workspace\Kaldin\WebContent\WEB-INF\classes\com\kaldin\kaldin_java.zip
* Qualified Name: kaldin.user.adminprofile.form.EmailSettingForm
* JD-Core Version: 0.7.0.1
*/
|
/**
* Abstract part of bridge pattern
*
* @author durrah (mhd.durrah@gmail.com) on 5/16/15.
*/
package com.ugarit.java.designpatterns.bridge.abs;
|
package com.stanzione.weatherfollower;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Date;
public class MainActivity extends ActionBarActivity {
private static String TAG = MainActivity.class.getSimpleName();
private RelativeLayout backgroundLayout;
private TableLayout tableCities;
private ProgressBar progressBar;
private Button startWebservice;
private Button otherButton;
private TextView testLabel;
private String[] citiesToSearch;
private HTTPRequestOperation asyncOperation;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate");
backgroundLayout = (RelativeLayout) findViewById(R.id.backgroundLayout);
tableCities = (TableLayout) findViewById(R.id.tableCitiesResult);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
startWebservice = (Button) findViewById(R.id.startWebservice);
otherButton = (Button) findViewById(R.id.otherButton);
testLabel = (TextView) findViewById(R.id.testLabel);
setBackground();
startWebservice.setVisibility(View.INVISIBLE);
otherButton.setVisibility(View.INVISIBLE);
testLabel.setVisibility(View.INVISIBLE);
startWebservice.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startOperation();
}
});
otherButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
testLabel.setText("Working");
}
});
}
@Override
protected void onStart() {
super.onStart();
startOperation();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.menu_edit_cities) {
Intent intent = new Intent(this, CitiesActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
private void setBackground(){
int currentHour = new Date().getHours();
Log.d(TAG, "Current hour: " + currentHour);
if(currentHour < 18){
backgroundLayout.setBackgroundResource(R.drawable.bg_day);
}
else{
backgroundLayout.setBackgroundResource(R.drawable.bg_night);
}
}
private void startOperation(){
if(asyncOperation == null){
asyncOperation = new HTTPRequestOperation();
}
Log.d(TAG, asyncOperation.getStatus().toString());
if(asyncOperation.getStatus() == AsyncTask.Status.PENDING){
Log.d(TAG, "Starting operation..");
citiesToSearch = getActivatedCities();
Log.d(TAG, "Activated cities:");
for(int i=0; i<citiesToSearch.length; i++){
Log.d(TAG, citiesToSearch[i]);
}
Log.d(TAG, "Total of activated cities: " + citiesToSearch.length);
progressBar.setVisibility(View.VISIBLE);
asyncOperation.execute(citiesToSearch);
}
else if(asyncOperation.getStatus() == AsyncTask.Status.RUNNING){
Log.d(TAG, "The operation is still running..");
}
else if(asyncOperation.getStatus() == AsyncTask.Status.FINISHED){
Log.d(TAG, "The operation has finished, starting again..");
citiesToSearch = getActivatedCities();
Log.d(TAG, "Activated cities:");
for(int i=0; i<citiesToSearch.length; i++){
Log.d(TAG, citiesToSearch[i]);
}
Log.d(TAG, "Total of activated cities: " + citiesToSearch.length);
progressBar.setVisibility(View.VISIBLE);
asyncOperation = new HTTPRequestOperation();
asyncOperation.execute(citiesToSearch);
}
}
private String[] getActivatedCities(){
ArrayList<String> cities = new ArrayList<String>();
SharedPreferences prefs = getSharedPreferences(Configs.SHARED_CONFIGS, Activity.MODE_PRIVATE);
boolean activated = false;
if(prefs.getBoolean(Configs.CITY_ACTIVATED_1, true)){
cities.add(getResources().getString(R.string.string_city_1));
}
if(prefs.getBoolean(Configs.CITY_ACTIVATED_2, true)){
cities.add(getResources().getString(R.string.string_city_2));
}
if(prefs.getBoolean(Configs.CITY_ACTIVATED_3, true)){
cities.add(getResources().getString(R.string.string_city_3));
}
if(prefs.getBoolean(Configs.CITY_ACTIVATED_4, true)){
cities.add(getResources().getString(R.string.string_city_4));
}
if(prefs.getBoolean(Configs.CITY_ACTIVATED_5, true)){
cities.add(getResources().getString(R.string.string_city_5));
}
String[] returnArr = new String[cities.size()];
return cities.toArray(returnArr);
}
private class HTTPRequestOperation extends AsyncTask<String, Integer, ArrayList<CityResult>> {
private String TAG = HTTPRequestOperation.class.getSimpleName();
@Override
protected void onPreExecute() {
Log.d(TAG, "onPreExecute");
}
@Override
protected ArrayList<CityResult> doInBackground(String... cities) {
ArrayList<CityResult> citiesResult = new ArrayList<CityResult>();
CityResult cityResult;
try {
for(String city : cities) {
Log.d(TAG, "Starting search for city: " + city);
String cityHtml = getCityResultHTML(city);
if (cityHtml == null) {
Log.e(TAG, "Could not get weather info for city: " + city);
continue;
}
String currentTemperature = getCurrentTemperature(cityHtml);
if (currentTemperature == null) {
Log.e(TAG, "Could not get weather info for city: " + city);
continue;
}
Log.d(TAG, city + ": " + currentTemperature);
cityResult = new CityResult(city, currentTemperature);
citiesResult.add(cityResult);
}
} finally {
}
/*
for (int i = 0; i < 5; i++) {
Log.d(TAG, "doInBackground: " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.interrupted();
}
}
*/
return citiesResult;
}
private String getCityResultHTML(String city){
if(city.equals("São Paulo"))
city = "558/saopaulo-sp";
else if(city.equals("Rio de Janeiro"))
city = "321/riodejaneiro-rj";
else if(city.equals("Curitiba"))
city = "271/curitiba-pr";
else if(city.equals("Florianópolis"))
city = "377/florianopolis-sc";
else if(city.equals("Salvador"))
city = "56/salvador-ba";
String cityHtml = "";
try{
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://www.climatempo.com.br/previsao-do-tempo/cidade/" + city);
HttpResponse response = client.execute(request);
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null)
{
str.append(line);
}
in.close();
cityHtml = str.toString();
return cityHtml;
} catch (ClientProtocolException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
private String getCurrentTemperature(String html){
String temperature = null;
String[] arr = html.split("temp-momento\">");
if(arr.length > 1){
String[] temperatureArr = arr[1].split("</span>");
if(temperatureArr.length > 1){
temperature = temperatureArr[0];
}
}
return temperature;
}
@Override
protected void onProgressUpdate(Integer... progress) {
}
@Override
protected void onPostExecute(ArrayList<CityResult> citiesResult) {
testLabel.setText("Executed!");
tableCities.removeAllViews();
tableCities.setAlpha(0.75f);
createTableHeader();
for(int i=0; i<citiesResult.size(); i++){
Log.d(TAG, "" + i);
TableRow cityRow = new TableRow(MainActivity.this);
cityRow.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT,
TableRow.LayoutParams.WRAP_CONTENT));
TextView cityNameView = new TextView(MainActivity.this);
cityNameView.setText(citiesResult.get(i).getCityName());
cityNameView.setTextSize(20);
cityNameView.setPadding(10, 0, 0, 0);
TextView currentTemperatureView = new TextView(MainActivity.this);
currentTemperatureView.setText(citiesResult.get(i).getCurrentTemperature());
currentTemperatureView.setTextSize(20);
currentTemperatureView.setPadding(30, 0, 5, 0);
if(i%2 == 0)
cityRow.setBackgroundResource(R.drawable.table_line_odd);
else
cityRow.setBackgroundResource(R.drawable.table_line_even);
cityRow.addView(cityNameView);
cityRow.addView(currentTemperatureView);
tableCities.addView(cityRow, new TableLayout.LayoutParams(TableLayout.LayoutParams.FILL_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT));
}
createTableFooter();
progressBar.setVisibility(View.INVISIBLE);
}
private void createTableHeader(){
TableRow headerRow = new TableRow(MainActivity.this);
headerRow.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT,
TableRow.LayoutParams.WRAP_CONTENT));
TextView cityNameTitleView = new TextView(MainActivity.this);
cityNameTitleView.setText(getResources().getString(R.string.table_header_city));
cityNameTitleView.setTextSize(25);
cityNameTitleView.setPadding(10, 0, 0, 0);
cityNameTitleView.setTextColor(Color.WHITE);
TextView currentTemperatureTitleView = new TextView(MainActivity.this);
currentTemperatureTitleView.setText(getResources().getString(R.string.table_header_temperature));
currentTemperatureTitleView.setTextSize(25);
currentTemperatureTitleView.setPadding(30, 0, 5, 0);
currentTemperatureTitleView.setTextColor(Color.WHITE);
headerRow.setBackgroundResource(R.drawable.table_header);
headerRow.addView(cityNameTitleView);
headerRow.addView(currentTemperatureTitleView);
tableCities.addView(headerRow, new TableLayout.LayoutParams(TableLayout.LayoutParams.FILL_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT));
}
private void createTableFooter(){
TableRow footerRow = new TableRow(MainActivity.this);
footerRow.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT,
TableRow.LayoutParams.WRAP_CONTENT));
TextView cityNameTitleView = new TextView(MainActivity.this);
cityNameTitleView.setText("");
cityNameTitleView.setTextSize(20);
cityNameTitleView.setPadding(10, 0, 0, 0);
cityNameTitleView.setTextColor(Color.WHITE);
TextView currentTemperatureTitleView = new TextView(MainActivity.this);
currentTemperatureTitleView.setText("");
currentTemperatureTitleView.setTextSize(20);
currentTemperatureTitleView.setPadding(30, 0, 5, 0);
currentTemperatureTitleView.setTextColor(Color.WHITE);
footerRow.addView(cityNameTitleView);
footerRow.addView(currentTemperatureTitleView);
footerRow.setBackgroundResource(R.drawable.table_footer);
tableCities.addView(footerRow, new TableLayout.LayoutParams(TableLayout.LayoutParams.FILL_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT));
}
}
}
|
package com.jojoldu.book.springboot.web.dto;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
@Getter //선언된 모든 필드에 get 메소드 생성
@RequiredArgsConstructor //final 필드가 포함된 생성자 생성, final이 안붙은 애들은 포함 안함
public class HelloResponseDto {
private final String name;
private final int amount;
}
|
/*******************************************************************************
* Copyright (c) 2019
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*******************************************************************************/
package go.graphics.swing.vulkan;
import org.joml.Matrix4f;
import org.lwjgl.BufferUtils;
import org.lwjgl.PointerBuffer;
import org.lwjgl.system.MemoryStack;
import org.lwjgl.system.MemoryUtil;
import org.lwjgl.util.vma.Vma;
import org.lwjgl.util.vma.VmaAllocationCreateInfo;
import org.lwjgl.vulkan.VkBufferCopy;
import org.lwjgl.vulkan.VkBufferCreateInfo;
import org.lwjgl.vulkan.VkBufferImageCopy;
import org.lwjgl.vulkan.VkBufferMemoryBarrier;
import org.lwjgl.vulkan.VkClearAttachment;
import org.lwjgl.vulkan.VkClearRect;
import org.lwjgl.vulkan.VkClearValue;
import org.lwjgl.vulkan.VkCommandBuffer;
import org.lwjgl.vulkan.VkCommandBufferBeginInfo;
import org.lwjgl.vulkan.VkDescriptorBufferInfo;
import org.lwjgl.vulkan.VkDescriptorSetLayoutBinding;
import org.lwjgl.vulkan.VkDevice;
import org.lwjgl.vulkan.VkExtent2D;
import org.lwjgl.vulkan.VkFramebufferCreateInfo;
import org.lwjgl.vulkan.VkImageMemoryBarrier;
import org.lwjgl.vulkan.VkImageSubresourceRange;
import org.lwjgl.vulkan.VkImageViewCreateInfo;
import org.lwjgl.vulkan.VkInstance;
import org.lwjgl.vulkan.VkPhysicalDevice;
import org.lwjgl.vulkan.VkPresentInfoKHR;
import org.lwjgl.vulkan.VkQueue;
import org.lwjgl.vulkan.VkQueueFamilyProperties;
import org.lwjgl.vulkan.VkRenderPassBeginInfo;
import org.lwjgl.vulkan.VkSamplerCreateInfo;
import org.lwjgl.vulkan.VkSubmitInfo;
import org.lwjgl.vulkan.VkSurfaceCapabilitiesKHR;
import org.lwjgl.vulkan.VkSurfaceFormatKHR;
import org.lwjgl.vulkan.VkSwapchainCreateInfoKHR;
import org.lwjgl.vulkan.VkWriteDescriptorSet;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.nio.LongBuffer;
import java.nio.ShortBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Semaphore;
import java.util.function.BiFunction;
import go.graphics.AbstractColor;
import go.graphics.BackgroundDrawHandle;
import go.graphics.BufferHandle;
import go.graphics.EPrimitiveType;
import go.graphics.ETextureType;
import go.graphics.GLDrawContext;
import go.graphics.ManagedHandle;
import go.graphics.MultiDrawHandle;
import go.graphics.TextureHandle;
import go.graphics.UnifiedDrawHandle;
import go.graphics.VkDrawContext;
import go.graphics.swing.text.LWJGLTextDrawer;
import static org.lwjgl.util.vma.Vma.*;
import static org.lwjgl.vulkan.KHRSurface.*;
import static org.lwjgl.vulkan.KHRSwapchain.*;
import static org.lwjgl.vulkan.VK10.*;
public class VulkanDrawContext extends GLDrawContext implements VkDrawContext {
protected VkDevice device = null;
private VkPhysicalDevice physicalDevice;
private long surface = VK_NULL_HANDLE;
private int surfaceFormat;
private VkInstance instance;
private VkQueue presentQueue;
private VkQueue graphicsQueue;
private int universalQueueIndex;
private int graphicsQueueIndex;
private int presentQueueIndex;
protected long[] allocators = new long[] {0, 0, 0, 0};
private int fbWidth;
private int fbHeight;
private long commandPool = VK_NULL_HANDLE;
private VkCommandBuffer graphCommandBuffer = null;
private VkCommandBuffer memCommandBuffer = null;
private VkCommandBuffer fbCommandBuffer = null;
private long renderPass;
private long fetchFramebufferSemaphore = VK_NULL_HANDLE;
private long presentFramebufferSemaphore = VK_NULL_HANDLE;
private VulkanDescriptorPool universalDescPool = null;
private VulkanDescriptorPool textureDescPool = null;
private VulkanDescriptorPool multiDescPool = null;
public VulkanDescriptorSetLayout textureDescLayout = null;
public VulkanDescriptorSetLayout multiDescLayout = null;
private VulkanPipeline backgroundPipeline = null;
private VulkanPipeline lineUnifiedPipeline = null;
private VulkanPipeline unifiedArrayPipeline = null;
private VulkanPipeline unifiedMultiPipeline = null;
private VulkanPipeline unifiedPipeline = null;
final long[] samplers = new long[ETextureType.values().length];
private final Semaphore resourceMutex = new Semaphore(1);
private final Semaphore closeMutex = new Semaphore(1);
private final BiFunction<VkQueueFamilyProperties, Integer, Boolean> graphicsQueueCond = (queue, index) -> (queue.queueFlags()&VK_QUEUE_GRAPHICS_BIT)>0;
protected final List<VulkanMultiBufferHandle> multiBuffers = new ArrayList<>();
protected final List<VulkanTextureHandle> textures = new ArrayList<>();
protected final List<VulkanBufferHandle> buffers = new ArrayList<>();
private float guiScale;
public VulkanDrawContext(VkInstance instance, long surface, float guiScale) {
this.instance = instance;
this.guiScale = guiScale;
BiFunction<VkQueueFamilyProperties, Integer, Boolean> presentQueueCond = (queue, index) -> {
int[] present = new int[1];
vkGetPhysicalDeviceSurfaceSupportKHR(physicalDevice, index, surface, present);
return present[0]==1;
};
try(MemoryStack stack = MemoryStack.stackPush()) {
VkPhysicalDevice[] allPhysicalDevices = VulkanUtils.listPhysicalDevices(stack, instance);
physicalDevice = VulkanUtils.findPhysicalDevice(allPhysicalDevices);
VkQueueFamilyProperties.Buffer allQueueFamilies = VulkanUtils.listQueueFamilies(stack, physicalDevice);
universalQueueIndex = VulkanUtils.findQueue(allQueueFamilies, (queue, index) -> graphicsQueueCond.apply(queue, index)&&presentQueueCond.apply(queue, index));
graphicsQueueIndex = universalQueueIndex!=-1? universalQueueIndex : VulkanUtils.findQueue(allQueueFamilies, graphicsQueueCond);
presentQueueIndex = universalQueueIndex!=-1? universalQueueIndex : VulkanUtils.findQueue(allQueueFamilies, presentQueueCond);
if(graphicsQueueIndex == -1) throw new Error("Could not find any graphics queue.");
if(presentQueueIndex == -1) throw new Error("Could not find any present queue.");
// device extensions
List<String> deviceExtensions = new ArrayList<>();
deviceExtensions.add(VK_KHR_SWAPCHAIN_EXTENSION_NAME);
List<VkQueue> queues = new ArrayList<>();
device = VulkanUtils.createDevice(stack, physicalDevice, deviceExtensions, queues, universalQueueIndex!=-1?new int[] {universalQueueIndex} : new int[] {graphicsQueueIndex, presentQueueIndex});
if(universalQueueIndex != -1) {
graphicsQueue = presentQueue = queues.get(0);
} else {
graphicsQueue = queues.get(0);
presentQueue = queues.get(1);
}
setSurface(surface);
for(int i = 0; i != allocators.length; i++) allocators[i] = VulkanUtils.createAllocator(stack, instance, device, physicalDevice);
commandPool = VulkanUtils.createCommandPool(stack, device, universalQueueIndex);
graphCommandBuffer = VulkanUtils.createCommandBuffer(stack, device, commandPool);
memCommandBuffer = VulkanUtils.createCommandBuffer(stack, device, commandPool);
fbCommandBuffer = VulkanUtils.createCommandBuffer(stack, device, commandPool);
swapchainCreateInfo.sType(VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR)
.compositeAlpha(VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR)
.imageUsage(VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT|VK_IMAGE_USAGE_TRANSFER_SRC_BIT|VK_IMAGE_USAGE_TRANSFER_DST_BIT)
.presentMode(VK_PRESENT_MODE_FIFO_KHR) // must be supported by all drivers
.imageArrayLayers(1)
.clipped(false);
if(universalQueueIndex != -1) {
swapchainCreateInfo.imageSharingMode(VK_SHARING_MODE_EXCLUSIVE);
} else {
swapchainCreateInfo.imageSharingMode(VK_SHARING_MODE_CONCURRENT)
.pQueueFamilyIndices(stack.ints(graphicsQueueIndex, presentQueueIndex));
}
swapchainImageViewCreateInfo.sType(VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO)
.viewType(VK_IMAGE_VIEW_TYPE_2D);
swapchainImageViewCreateInfo.subresourceRange()
.aspectMask(VK_IMAGE_ASPECT_COLOR_BIT)
.baseMipLevel(0)
.levelCount(1)
.baseArrayLayer(0)
.layerCount(1);
framebufferCreateInfo.sType(VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO)
.layers(1);
final Map<Integer, Integer> universalAllocateAmounts = new HashMap<>();
universalAllocateAmounts.put(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VulkanUtils.ALLOCATE_UBO_SLOTS);
universalAllocateAmounts.put(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VulkanUtils.ALLOCATE_TEXTURE_SLOTS);
universalDescPool = new VulkanDescriptorPool(device, VulkanUtils.ALLOCATE_SET_SLOTS, universalAllocateAmounts);
final Map<Integer, Integer> textureAllocateAmounts = new HashMap<>();
textureAllocateAmounts.put(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VulkanUtils.TEXTURE_POOL_SIZE);
textureDescPool = new VulkanDescriptorPool(device, VulkanUtils.TEXTURE_POOL_SIZE, textureAllocateAmounts);
final Map<Integer, Integer> multiAllocateAmounts = new HashMap<>();
multiAllocateAmounts.put(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VulkanUtils.MULTI_POOL_SIZE);
multiDescPool = new VulkanDescriptorPool(device, VulkanUtils.MULTI_POOL_SIZE, multiAllocateAmounts);
VkDescriptorSetLayoutBinding.Buffer textureBindings = VkDescriptorSetLayoutBinding.callocStack(1, stack);
textureBindings.get(0).set(0, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_FRAGMENT_BIT, null);
textureDescLayout = new VulkanDescriptorSetLayout(device, textureBindings);
VkDescriptorSetLayoutBinding.Buffer multiBindings = VkDescriptorSetLayoutBinding.callocStack(1, stack);
multiBindings.get(0).set(0, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1, VK_SHADER_STAGE_VERTEX_BIT, null);
multiDescLayout = new VulkanDescriptorSetLayout(device, multiBindings);
unifiedPipeline = new VulkanPipeline.UnifiedPipeline(stack, this, universalDescPool, renderPass, EPrimitiveType.Quad);
lineUnifiedPipeline = new VulkanPipeline.UnifiedPipeline(stack, this, universalDescPool, renderPass, EPrimitiveType.Line);
unifiedArrayPipeline = new VulkanPipeline.UnifiedArrayPipeline(stack, this, universalDescPool, renderPass);
unifiedMultiPipeline = new VulkanPipeline.UnifiedMultiPipeline(stack, this, universalDescPool, renderPass);
backgroundPipeline = new VulkanPipeline.BackgroundPipeline(stack, this, universalDescPool, renderPass);
LongBuffer semaphoreBfr = stack.callocLong(1);
fetchFramebufferSemaphore = VulkanUtils.createSemaphore(semaphoreBfr, device);
presentFramebufferSemaphore = VulkanUtils.createSemaphore(semaphoreBfr, device);
VkSamplerCreateInfo samplerCreateInfo = VkSamplerCreateInfo.callocStack(stack)
.sType(VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO)
.magFilter(VK_FILTER_NEAREST)
.minFilter(VK_FILTER_NEAREST)
.addressModeU(VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE)
.addressModeV(VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE)
.addressModeW(VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE)
.mipmapMode(VK_SAMPLER_MIPMAP_MODE_NEAREST)
.minLod(0)
.maxLod(0)
.compareEnable(false)
.anisotropyEnable(false)
.unnormalizedCoordinates(false);
samplers[ETextureType.NEAREST_FILTER.ordinal()] = VulkanUtils.createSampler(stack, samplerCreateInfo, device);
samplerCreateInfo.minFilter(VK_FILTER_LINEAR)
.magFilter(VK_FILTER_LINEAR);
samplers[ETextureType.LINEAR_FILTER.ordinal()] = VulkanUtils.createSampler(stack, samplerCreateInfo, device);
int globalUniformBufferSize = 4*4*4*(VulkanUtils.MAX_GLOBALTRANS_COUNT+1); // mat4+(1+MAX_GLOBALTRANS_COUNT)
globalUniformStagingBuffer = createBuffer(globalUniformBufferSize, STAGING_BUFFER);
globalUniformBufferData = BufferUtils.createByteBuffer(globalUniformBufferSize);
globalUniformBuffer = createBuffer(globalUniformBufferSize, STATIC_BUFFER);
backgroundUniformBfr = createBuffer(4*4*4, STATIC_BUFFER); // mat4
unifiedUniformBfr = createBuffer(4, STATIC_BUFFER);
if(globalUniformBuffer == null || backgroundUniformBfr == null || unifiedUniformBfr == null) throw new Error("Could not create uniform buffers.");
installUniformBuffer(globalUniformBuffer, 0);
installUniformBuffer(backgroundUniformBfr, 1, 0, backgroundPipeline);
installUniformBuffer(unifiedUniformBfr, 1, 0, lineUnifiedPipeline);
installUniformBuffer(unifiedUniformBfr, 1, 0, unifiedArrayPipeline);
installUniformBuffer(unifiedUniformBfr, 1, 0, unifiedMultiPipeline);
installUniformBuffer(unifiedUniformBfr, 1, 0, unifiedPipeline);
} finally {
if(unifiedUniformBfr == null) invalidate();
}
}
@Override
public void invalidate() {
closeMutex.acquireUninterruptibly();
resourceMutex.acquireUninterruptibly();
closeMutex.release();
textures.forEach(VulkanTextureHandle::destroy);
buffers.forEach(VulkanBufferHandle::destroy);
for(long sampler : samplers) {
if(sampler != 0) vkDestroySampler(device, sampler, null);
}
if(presentFramebufferSemaphore != VK_NULL_HANDLE) vkDestroySemaphore(device, presentFramebufferSemaphore, null);
if(fetchFramebufferSemaphore != VK_NULL_HANDLE) vkDestroySemaphore(device, fetchFramebufferSemaphore, null);
if(swapchain != VK_NULL_HANDLE) {
destroyFramebuffers(-1);
destroySwapchainViews(-1);
vkDestroySwapchainKHR(device, swapchain, null);
}
if(backgroundPipeline != null) backgroundPipeline.destroy();
if(lineUnifiedPipeline != null) lineUnifiedPipeline.destroy();
if(unifiedArrayPipeline != null) unifiedArrayPipeline.destroy();
if(unifiedMultiPipeline != null) unifiedMultiPipeline.destroy();
if(unifiedPipeline != null) unifiedPipeline.destroy();
if(multiDescLayout != null) multiDescLayout.destroy();
if(textureDescLayout != null) textureDescLayout.destroy();
if(multiDescPool != null) multiDescPool.destroy();
if(textureDescPool != null) textureDescPool.destroy();
if(universalDescPool != null) universalDescPool.destroy();
for(long allocator : allocators) if(allocator != 0) vmaDestroyAllocator(allocator);
if(renderPass != VK_NULL_HANDLE) vkDestroyRenderPass(device, renderPass, null);
if(fbCommandBuffer != null) vkFreeCommandBuffers(device, commandPool, fbCommandBuffer);
if(memCommandBuffer != null) vkFreeCommandBuffers(device, commandPool, memCommandBuffer);
if(graphCommandBuffer != null) vkFreeCommandBuffers(device, commandPool, graphCommandBuffer);
if(commandPool != VK_NULL_HANDLE) vkDestroyCommandPool(device, commandPool, null);
commandBufferRecording = false;
if(device != null) vkDestroyDevice(device, null);
fbCommandBuffer = null;
memCommandBuffer = null;
graphCommandBuffer = null;
commandPool = VK_NULL_HANDLE;
presentFramebufferSemaphore = VK_NULL_HANDLE;
fetchFramebufferSemaphore = VK_NULL_HANDLE;
swapchain = VK_NULL_HANDLE;
device = null;
super.invalidate();
resourceMutex.release();
}
@Override
public void setShadowDepthOffset(float depth) {
unifiedUniformBfrData.putFloat(0, depth);
unifiedDataUpdated = true;
}
private void updateUnifiedStatic() {
if(unifiedDataUpdated) {
updateBufferAt(unifiedUniformBfr, 0, unifiedUniformBfrData);
unifiedDataUpdated = false;
}
}
protected VulkanBufferHandle unifiedUniformBfr = null;
private final ByteBuffer unifiedUniformBfrData = BufferUtils.createByteBuffer(4);
private boolean unifiedDataUpdated = false;
private final LongBuffer imageBfr = BufferUtils.createLongBuffer(1);
private final LongBuffer imageViewBfr = BufferUtils.createLongBuffer(1);
private final PointerBuffer imageAllocationBfr = BufferUtils.createPointerBuffer(1);
@Override
public TextureHandle generateTexture(int width, int height, ShortBuffer data, String name) {
return generateTextureInternal(width, height, data, 0L);
}
private TextureHandle generateTextureInternal(int width, int height, ShortBuffer data, long descSet) {
if(!commandBufferRecording) return null;
if(width == 0) width = 1;
if(height == 0) height = 1;
VulkanTextureHandle vkTexHandle = createTexture(width, height, VK_FORMAT_R4G4B4A4_UNORM_PACK16, VK_IMAGE_USAGE_SAMPLED_BIT|VK_IMAGE_USAGE_TRANSFER_DST_BIT, true, descSet);
changeLayout(vkTexHandle, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, true);
if(data != null) updateTexture(vkTexHandle, 0, 0, width, height, data);
return vkTexHandle;
}
@Override
protected void drawMulti(MultiDrawHandle call) {
if(!commandBufferRecording || call == null || call.drawCalls == null || call.sourceQuads == null) return;
updateUnifiedStatic();
VulkanBufferHandle vkDrawCalls = (VulkanBufferHandle) call.drawCalls;
bind(unifiedMultiPipeline);
VulkanBufferHandle vkQuads = (VulkanBufferHandle)call.sourceQuads.vertices;
long verticesDescSet = multiDescriptorSets.computeIfAbsent(vkQuads, this::createMultiDescriptorSet);
bindDescSets(getTextureDescSet(call.sourceQuads.texture), verticesDescSet);
unifiedMultiPipeline.bindVertexBuffers(graphCommandBuffer, vkDrawCalls.getBufferIdVk());
vkCmdDraw(graphCommandBuffer, 4, call.used, 0, 0);
((VulkanMultiBufferHandle)call.drawCalls).inc();
}
private final Map<VulkanBufferHandle, Long> multiDescriptorSets = new HashMap<>();
private final VulkanMultiBufferHandle unifiedArrayBfr = createMultiBuffer(2*100*4*4, DYNAMIC_BUFFER);
private final ByteBuffer unifiedArrayStaging = BufferUtils.createByteBuffer(2*100*4*4);
@Override
protected void drawUnifiedArray(UnifiedDrawHandle call, int primitive, int vertexCount, float[] trans, float[] colors, int array_len) {
if(!commandBufferRecording || call == null || call.vertices == null) return;
updateUnifiedStatic();
if(primitive != EPrimitiveType.Quad) throw new Error("not implemented primitive: " + primitive);
FloatBuffer data = unifiedArrayStaging.asFloatBuffer();
data.put(colors, 0, array_len*4);
data.position(4*100);
data.put(trans, 0, array_len*4);
updateBufferAt(unifiedArrayBfr, 0, unifiedArrayStaging);
bind(unifiedArrayPipeline);
long vb = ((VulkanBufferHandle)call.vertices).getBufferIdVk();
unifiedArrayPipeline.bindVertexBuffers(graphCommandBuffer, vb, vb, unifiedArrayBfr.getBufferIdVk());
bindDescSets(getTextureDescSet(call.texture));
vkCmdDraw(graphCommandBuffer, vertexCount, array_len, call.offset, 0);
unifiedArrayBfr.inc();
}
private final Map<Integer, VulkanBufferHandle> lineIndexBfr = new HashMap<>();
@Override
protected void drawUnified(UnifiedDrawHandle call, int primitive, int vertices, int mode, float x, float y, float z, float sx, float sy, AbstractColor color, float intensity) {
if(!commandBufferRecording || call == null || call.vertices == null) return;
updateUnifiedStatic();
if(primitive == EPrimitiveType.Triangle || primitive == EPrimitiveType.Quad) {
bind(unifiedPipeline);
} else {
bind(lineUnifiedPipeline);
}
bindDescSets(getTextureDescSet(call.texture));
long vb = ((VulkanBufferHandle)call.vertices).getBufferIdVk();
lastPipeline.bindVertexBuffers(graphCommandBuffer, vb, vb);
ByteBuffer unifiedPushConstants = lastPipeline.pushConstantBfr;
// 4 padding bytes
unifiedPushConstants.putFloat(4, sx);
unifiedPushConstants.putFloat(8, sy);
unifiedPushConstants.putFloat(12, x);
unifiedPushConstants.putFloat(16, y);
unifiedPushConstants.putFloat(20, z);
if(color != null) {
unifiedPushConstants.putFloat(28, color.red);
unifiedPushConstants.putFloat(32, color.green);
unifiedPushConstants.putFloat(36, color.blue);
unifiedPushConstants.putFloat(40, color.alpha);
} else {
unifiedPushConstants.putFloat(28, 1);
unifiedPushConstants.putFloat(32, 1);
unifiedPushConstants.putFloat(36, 1);
unifiedPushConstants.putFloat(40, 1);
}
unifiedPushConstants.putFloat(44, intensity);
unifiedPushConstants.putInt(48, mode);
lastPipeline.pushConstants(graphCommandBuffer);
if(primitive == EPrimitiveType.Triangle) {
vkCmdDraw(graphCommandBuffer, vertices, 1, call.offset, 0);
} else if(primitive == EPrimitiveType.Quad) {
vkCmdDraw(graphCommandBuffer, 4, 1, call.offset, 0);
} else {
VulkanBufferHandle indexBfr = lineIndexBfr.get(vertices);
if(indexBfr == null) {
ByteBuffer indices = BufferUtils.createByteBuffer((vertices)*2*4);
IntBuffer data = indices.asIntBuffer();
for(int i = 0; i != vertices; i++) {
data.put(i*2, i);
data.put(i*2+1, (i+1)%vertices);
}
indexBfr = createBuffer(indices.remaining(), STATIC_BUFFER);
updateBufferAt(indexBfr, 0, indices);
lineIndexBfr.put(vertices, indexBfr);
}
vkCmdBindIndexBuffer(graphCommandBuffer, indexBfr.getBufferIdVk(), 0, VK_INDEX_TYPE_UINT32);
vkCmdDrawIndexed(graphCommandBuffer, (vertices+(primitive==EPrimitiveType.LineLoop?0:-1))*2, 1, 0, call.offset, 0);
}
}
@Override
public void drawBackground(BackgroundDrawHandle call) {
if(!commandBufferRecording || call == null || call.texture == null || call.vertices == null || call.colors == null) return;
VulkanBufferHandle vkShape = (VulkanBufferHandle) call.vertices;
VulkanBufferHandle vkColor = (VulkanBufferHandle) call.colors;
bind(backgroundPipeline);
if(backgroundDataUpdated) {
updateBufferAt(backgroundUniformBfr, 0, backgroundUniformBfrData);
backgroundDataUpdated = false;
}
bindDescSets(getTextureDescSet(call.texture));
backgroundPipeline.bindVertexBuffers(graphCommandBuffer, vkShape.getBufferIdVk(), vkColor.getBufferIdVk());
int starti = call.offset < 0 ? (int)Math.ceil(-call.offset/(float)call.stride) : 0;
int draw_lines = call.lines-starti;
int triangleCount = ((VulkanBufferHandle) call.vertices).getSize()/20;
for (int i = 0; i != draw_lines; i++) {
int lineStart = (call.offset+call.stride*(i+starti))*3;
int lineLen = call.width*3;
if(lineStart >= triangleCount) break;
else if(lineStart+lineLen >= triangleCount) lineLen = triangleCount-lineStart;
vkCmdDraw(graphCommandBuffer, lineLen, 1, lineStart, 0);
}
}
@Override
public void setHeightMatrix(float[] matrix) {
backgroundUniformBfrData.asFloatBuffer().put(matrix, 0, 16);
backgroundDataUpdated = true;
}
protected final VulkanBufferHandle backgroundUniformBfr;
private final ByteBuffer backgroundUniformBfrData = BufferUtils.createByteBuffer((4*4+2*4+1)*4);
private boolean backgroundDataUpdated = false;
protected int globalAttrIndex = 0;
private final Matrix4f global = new Matrix4f();
@Override
public void setGlobalAttributes(float x, float y, float z, float sx, float sy, float sz) {
if(!commandBufferRecording) return;
if(globalAttrIndex == VulkanUtils.MAX_GLOBALTRANS_COUNT) throw new Error("Out of globalTrans slots: increase VulkanUtils.MAX_GLOBALTRANS_COUNT");
globalAttrIndex++;
finishFrame();
global.identity();
global.scale(sx, sy, sz);
global.translate(x, y, z);
global.get(4*4*4*(globalAttrIndex+1), globalUniformBufferData);
if(lastPipeline != null) vkCmdPushConstants(graphCommandBuffer, lastPipeline.pipelineLayout, VK_SHADER_STAGE_ALL_GRAPHICS, 0, new int[]{globalAttrIndex});
}
@Override
public void updateTexture(TextureHandle handle, List<int[]> diff, ByteBuffer data) {
if(!commandBufferRecording || handle == null) return;
VulkanTextureHandle vkTexture = (VulkanTextureHandle)handle;
if(vkTexture.getImageViewId() == VK_NULL_HANDLE) return;
int stagingPos = prepareStagingData(data);
int count = diff.size();
VkBufferImageCopy.Buffer regions = VkBufferImageCopy.create(count);
for(int i = 0; i != count; i++) {
VkBufferImageCopy imageCopy = regions.get(i);
int[] original = diff.get(i);
imageCopy.imageOffset().set(original[0], original[1], 0);
imageCopy.imageExtent().set(original[2], original[3], 1);
imageCopy.imageSubresource().set(VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1);
imageCopy.bufferOffset(stagingPos+original[4]).bufferRowLength(original[2]);
}
changeLayout(vkTexture, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, true);
vkCmdCopyBufferToImage(memCommandBuffer, stagingBuffers.get(stagingBufferIndex).getBufferIdVk(), vkTexture.getTextureIdVk(), VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, regions);
changeLayout(vkTexture, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, true);
}
@Override
public void updateTexture(TextureHandle textureIndex, int left, int bottom, int width, int height, ShortBuffer data) {
if(!commandBufferRecording || textureIndex == null || width == 0 || height == 0) return;
VulkanTextureHandle vkTexture = (VulkanTextureHandle) textureIndex;
if(vkTexture.getImageViewId() == VK_NULL_HANDLE) return;
int stagingPos = prepareStagingData(data);
VkBufferImageCopy.Buffer region = VkBufferImageCopy.create(1);
region.get(0).imageOffset().set(left, bottom, 0);
region.get(0).imageExtent().set(width, height, 1);
region.get(0).imageSubresource().set(VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1);
region.get(0).bufferOffset(stagingPos).bufferRowLength(width);
changeLayout(vkTexture, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, true);
vkCmdCopyBufferToImage(memCommandBuffer, stagingBuffers.get(stagingBufferIndex).getBufferIdVk(), vkTexture.getTextureIdVk(), VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, region);
changeLayout(vkTexture, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, true);
}
@Override
public TextureHandle resizeTexture(TextureHandle textureIndex, int width, int height, ShortBuffer data) {
if(textureIndex == null) return null;
((VulkanTextureHandle)textureIndex).setDestroy();
if(!commandBufferRecording) return null;
return generateTextureInternal(width, height, data, ((VulkanTextureHandle)textureIndex).descSet);
}
private final VkImageMemoryBarrier.Buffer layoutTransition = VkImageMemoryBarrier.create(1)
.sType(VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER)
.srcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
.dstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
.srcAccessMask(VK_ACCESS_MEMORY_WRITE_BIT|VK_ACCESS_MEMORY_READ_BIT)
.dstAccessMask(VK_ACCESS_MEMORY_WRITE_BIT|VK_ACCESS_MEMORY_READ_BIT);
private void changeLayout(VulkanTextureHandle texture, int oldLayout, int newLayout, boolean memOrFB) {
if(!commandBufferRecording) return;
layoutTransition.image(texture.getTextureIdVk())
.oldLayout(oldLayout)
.newLayout(newLayout);
layoutTransition.subresourceRange().set(VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1);
vkCmdPipelineBarrier(memOrFB?memCommandBuffer:fbCommandBuffer, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, null, null, layoutTransition);
}
private final PointerBuffer map_buffer_bfr = BufferUtils.createPointerBuffer(1);
protected int usedStagingMemory = 0;
protected int stagingBufferIndex = 0;
protected final List<VulkanBufferHandle> stagingBuffers = new ArrayList<>();
private int prepareStagingData(Buffer data) {
ByteBuffer bdata = (data instanceof ByteBuffer)?(ByteBuffer)data : null;
ShortBuffer sdata = (data instanceof ShortBuffer)?(ShortBuffer)data : null;
int size;
if(bdata != null) size = bdata.remaining();
else if(sdata != null) size = sdata.remaining()*2;
else throw new Error("Not yet implemented Buffer variant: " + data.getClass().getName());
do {
if(stagingBuffers.size() == stagingBufferIndex) {
int newSize = 1024*(1<<stagingBufferIndex); // aka 1kB * 2^index
if(newSize < size) newSize = size; // don't create a too small buffer
stagingBuffers.add(stagingBufferIndex, createBuffer(newSize, STAGING_BUFFER));
} else {
if(usedStagingMemory+size > stagingBuffers.get(stagingBufferIndex).getSize()) {
stagingBufferIndex++;
usedStagingMemory = 0;
} else {
break;
}
}
} while(true);
VulkanBufferHandle currentStagingBuffer = stagingBuffers.get(stagingBufferIndex);
vmaMapMemory(allocators[currentStagingBuffer.getType()], currentStagingBuffer.getAllocation(), map_buffer_bfr);
ByteBuffer mapped = MemoryUtil.memByteBuffer(map_buffer_bfr.get(0)+usedStagingMemory, currentStagingBuffer.getSize()-usedStagingMemory);
if(bdata != null) mapped.put(bdata.asReadOnlyBuffer());
if(sdata != null) mapped.asShortBuffer().put(sdata.asReadOnlyBuffer());
vmaUnmapMemory(allocators[currentStagingBuffer.getType()], currentStagingBuffer.getAllocation());
int offset = usedStagingMemory;
usedStagingMemory += size;
// bufferOffset must be a multiple of 4
usedStagingMemory -= -usedStagingMemory%4;
return offset;
}
private final VkBufferCopy.Buffer update_buffer_region = VkBufferCopy.create(1);
@Override
public void updateBufferAt(BufferHandle handle, int pos, ByteBuffer data) {
if(!commandBufferRecording || handle == null || data.remaining() == 0) return;
VulkanBufferHandle vkBuffer = (VulkanBufferHandle)handle;
if(vkBuffer.getType() == STATIC_BUFFER) {
if (data.remaining() >= 65536) {
int writePos = prepareStagingData(data);
update_buffer_region.get(0).set(writePos, pos, data.remaining());
vkCmdCopyBuffer(memCommandBuffer, stagingBuffers.get(stagingBufferIndex).getBufferIdVk(), vkBuffer.getBufferIdVk(), update_buffer_region);
} else {
vkCmdUpdateBuffer(memCommandBuffer, vkBuffer.getBufferIdVk(), pos, data);
}
syncQueues(vkBuffer.getEvent(), vkBuffer.getBufferIdVk());
} else {
vmaMapMemory(allocators[vkBuffer.getType()], vkBuffer.getAllocation(), map_buffer_bfr);
ByteBuffer mapped = MemoryUtil.memByteBuffer(map_buffer_bfr.get(0), vkBuffer.getSize());
mapped.put(data.asReadOnlyBuffer());
vmaUnmapMemory(allocators[vkBuffer.getType()], vkBuffer.getAllocation());
vmaFlushAllocation(allocators[vkBuffer.getType()], vkBuffer.getAllocation(), pos, data.remaining());
}
}
@Override
public void updateBufferAt(BufferHandle handle, List<Integer> pos, List<Integer> len, ByteBuffer data) {
if(!commandBufferRecording || handle == null) return;
VulkanBufferHandle vkBuffer = (VulkanBufferHandle)handle;
int writePos = prepareStagingData(data);
int count = pos.size();
VkBufferCopy.Buffer update_buffer_regions = VkBufferCopy.create(count);
for(int i = 0; i != count; i++) {
int off = pos.get(i);
update_buffer_regions.get(i).set(writePos+off, off, len.get(i));
}
vkCmdCopyBuffer(memCommandBuffer, stagingBuffers.get(stagingBufferIndex).getBufferIdVk(), vkBuffer.getBufferIdVk(), update_buffer_regions);
syncQueues(vkBuffer.getEvent(), vkBuffer.getBufferIdVk());
}
private final LongBuffer bufferBfr = BufferUtils.createLongBuffer(1);
private final PointerBuffer bufferAllocationBfr = BufferUtils.createPointerBuffer(1);
private final VkBufferCreateInfo bufferCreateInfo = VkBufferCreateInfo.create()
.sType(VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO)
.sharingMode(VK_SHARING_MODE_EXCLUSIVE);
private final VmaAllocationCreateInfo bufferAllocInfo = VmaAllocationCreateInfo.create();
private int consumedTexSlots = 0;
private VulkanTextureHandle createTexture(int width, int height, int format, int usage, boolean color, long descSet) {
VulkanUtils.createImage(this, width, height, format, usage, color, imageBfr, imageViewBfr, imageAllocationBfr);
long textureDescSet = descSet;
if(textureDescSet == 0 && color) { // only color images can be used
textureDescSet = textureDescPool.createNewSet(textureDescLayout);
}
VulkanTextureHandle vkTexHandle = new VulkanTextureHandle(this,
color?consumedTexSlots:-1,
imageBfr.get(0),
imageAllocationBfr.get(0),
imageViewBfr.get(0),
textureDescSet);
if(descSet == 0) {
vkTexHandle.tick();
}
if(color && descSet == 0) consumedTexSlots++;
if(!color) vkTexHandle.setInstalled(); // depth images cant be installed
textures.add(vkTexHandle);
return vkTexHandle;
}
private static final int STAGING_BUFFER = 0;
private static final int STATIC_BUFFER = 1;
private static final int DYNAMIC_BUFFER = 2;
public static final int TEXTUREDATA_BUFFER = 2;
public static final int READBACK_BUFFER = 3;
protected VulkanMultiBufferHandle createMultiBuffer(int size, int type) {
VulkanMultiBufferHandle vkMultiBfrHandle = new VulkanMultiBufferHandle(this, type, size);
multiBuffers.add(vkMultiBfrHandle);
return vkMultiBfrHandle;
}
protected VulkanBufferHandle createBuffer(int size, int type) {
if(type == STAGING_BUFFER) {
bufferCreateInfo.usage(VK_BUFFER_USAGE_TRANSFER_SRC_BIT);
bufferAllocInfo.usage(VMA_MEMORY_USAGE_CPU_ONLY);
} else if(type == STATIC_BUFFER) {
bufferCreateInfo.usage(VK_BUFFER_USAGE_TRANSFER_DST_BIT|VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT|VK_BUFFER_USAGE_INDEX_BUFFER_BIT|VK_BUFFER_USAGE_VERTEX_BUFFER_BIT);
bufferAllocInfo.usage(VMA_MEMORY_USAGE_GPU_ONLY);
} else if(type == DYNAMIC_BUFFER) {
bufferCreateInfo.usage(VK_BUFFER_USAGE_VERTEX_BUFFER_BIT);
bufferAllocInfo.usage(VMA_MEMORY_USAGE_CPU_TO_GPU);
} else if(type == READBACK_BUFFER) {
bufferCreateInfo.usage(VK_BUFFER_USAGE_TRANSFER_DST_BIT);
bufferAllocInfo.usage(VMA_MEMORY_USAGE_GPU_TO_CPU);
}
bufferCreateInfo.size(size);
long event;
try {
event = VulkanUtils.createEvent(device);
} catch(Throwable thrown) {
thrown.printStackTrace();
return null;
}
if(vmaCreateBuffer(allocators[type], bufferCreateInfo, bufferAllocInfo, bufferBfr, bufferAllocationBfr, null) < 0) {
vkDestroyEvent(device, event, null);
return null;
}
VulkanBufferHandle vkBfrHandle = new VulkanBufferHandle(this, type, bufferBfr.get(0), bufferAllocationBfr.get(0), event, size);
buffers.add(vkBfrHandle);
return vkBfrHandle;
}
private final LongBuffer syncQueueBfr = BufferUtils.createLongBuffer(1);
private final VkBufferMemoryBarrier.Buffer synQueueArea = VkBufferMemoryBarrier.create(1)
.sType(VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER)
.srcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
.dstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
.size(VK_WHOLE_SIZE)
.offset(0);
private void syncQueues(long event, long buffer) {
syncQueueBfr.put(0, event);
vkCmdSetEvent(memCommandBuffer, event, VK_PIPELINE_STAGE_TRANSFER_BIT|VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT);
synQueueArea.srcAccessMask(VK_ACCESS_MEMORY_WRITE_BIT).dstAccessMask(VK_ACCESS_MEMORY_READ_BIT).buffer(buffer);
vkCmdWaitEvents(graphCommandBuffer, syncQueueBfr, VK_PIPELINE_STAGE_TRANSFER_BIT|VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT|VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, null, synQueueArea, null);
}
@Override
public BackgroundDrawHandle createBackgroundDrawCall(int vertices, TextureHandle texture) {
VulkanBufferHandle vertexBfr = createBuffer(vertices*5*4, STATIC_BUFFER);
VulkanBufferHandle colorBfr = createBuffer(vertices*4, STATIC_BUFFER);
return new BackgroundDrawHandle(this, -1, texture, vertexBfr, colorBfr);
}
@Override
public UnifiedDrawHandle createUnifiedDrawCall(int vertices, String name, TextureHandle texture, float[] data) {
BufferHandle vertexBuffer = createBuffer(vertices*(texture!=null?4:2)*4, STATIC_BUFFER);
if (data != null) {
try(MemoryStack stack = MemoryStack.stackPush()) {
ByteBuffer dataBfr = stack.malloc(data.length*4);
dataBfr.asFloatBuffer().put(data);
updateBufferAt(vertexBuffer, 0, dataBfr);
}
}
return new UnifiedDrawHandle(this, -1, 0, vertices, texture, vertexBuffer);
}
@Override
protected MultiDrawHandle createMultiDrawCall(String name, ManagedHandle source) {
VulkanMultiBufferHandle drawCallBuffer = createMultiBuffer(MultiDrawHandle.MAX_CACHE_ENTRIES*12*4, DYNAMIC_BUFFER);
drawCallBuffer.reset();
return new MultiDrawHandle(this, managedHandles.size(), MultiDrawHandle.MAX_CACHE_ENTRIES, source, drawCallBuffer);
}
@Override
public void clearDepthBuffer() {
if(!commandBufferRecording) return;
finishFrame();
VkClearAttachment.Buffer clearAttachment = VkClearAttachment.create(1);
clearAttachment.get(0).set(VK_IMAGE_ASPECT_DEPTH_BIT, 1, CLEAR_VALUES.get(1));
VkClearRect.Buffer clearRect = VkClearRect.create(1).layerCount(1).baseArrayLayer(0);
clearRect.rect().extent().set(fbWidth, fbHeight);
vkCmdClearAttachments(graphCommandBuffer, clearAttachment, clearRect);
}
private long swapchain = VK_NULL_HANDLE;
private long[] swapchainImages;
private long[] swapchainViews;
private long[] framebuffers;
private final VkSurfaceCapabilitiesKHR surfaceCapabilities = VkSurfaceCapabilitiesKHR.create();
private final VkSwapchainCreateInfoKHR swapchainCreateInfo = VkSwapchainCreateInfoKHR.create();
private final VkFramebufferCreateInfo framebufferCreateInfo = VkFramebufferCreateInfo.create();
private final VkImageViewCreateInfo swapchainImageViewCreateInfo = VkImageViewCreateInfo.create();
private void destroySwapchainViews(int count) {
if(swapchainViews == null) return;
if(count == -1) count = swapchainViews.length;
for(int i = 0; i != count; i++) {
vkDestroyImageView(device, swapchainViews[i], null);
}
swapchainViews = null;
}
private void destroyFramebuffers(int count) {
if(framebuffers == null) return;
if(count == -1) count = framebuffers.length;
for(int i = 0; i != count; i++) {
vkDestroyFramebuffer(device, framebuffers[i], null);
}
framebuffers = null;
}
private VulkanTextureHandle depthImage = null;
protected final VulkanBufferHandle globalUniformStagingBuffer;
protected final VulkanBufferHandle globalUniformBuffer;
private final ByteBuffer globalUniformBufferData;
private final Matrix4f projMatrix = new Matrix4f();
private int newWidth;
private int newHeight;
private boolean resizeScheduled = false;
@Override
public void resize(int width, int height) {
newWidth = width;
newHeight = height;
resizeScheduled = true;
}
public void removeSurface() {
destroyFramebuffers(-1);
destroySwapchainViews(-1);
vkDestroySwapchainKHR(device, swapchain, null);
vkDestroySurfaceKHR(instance, this.surface, null);
vkDestroyRenderPass(device, renderPass, null);
swapchain = VK_NULL_HANDLE;
renderPass = VK_NULL_HANDLE;
}
public void setSurface(long surface) {
this.surface = surface;
try(MemoryStack stack = MemoryStack.stackPush()) {
VkSurfaceFormatKHR.Buffer allSurfaceFormats = VulkanUtils.listSurfaceFormats(stack, physicalDevice, surface);
VkSurfaceFormatKHR surfaceFormat = VulkanUtils.findSurfaceFormat(allSurfaceFormats);
this.surfaceFormat = surfaceFormat.format();
IntBuffer present = stack.callocInt(1);
vkGetPhysicalDeviceSurfaceSupportKHR(physicalDevice, presentQueueIndex, surface, present);
if(present.get(0) == 0) {
System.err.println("[VULKAN] can't present anymore");
return;
}
renderPass = VulkanUtils.createRenderPass(stack, device, surfaceFormat.format());
renderPassBeginInfo.renderPass(renderPass);
framebufferCreateInfo.renderPass(renderPass);
swapchainCreateInfo.surface(surface)
.imageColorSpace(surfaceFormat.colorSpace())
.imageFormat(surfaceFormat.format());
swapchainImageViewCreateInfo.format(surfaceFormat.format());
}
}
private void doResize(int width, int height) {
try(MemoryStack stack = MemoryStack.stackPush()) {
destroyFramebuffers(-1);
destroySwapchainViews(-1);
if (vkGetPhysicalDeviceSurfaceCapabilitiesKHR(physicalDevice, surface, surfaceCapabilities) != VK_SUCCESS) {
return;
}
fbWidth = width;
fbHeight = height;
int imageCount = surfaceCapabilities.minImageCount() + 1;
VkExtent2D minDim = surfaceCapabilities.maxImageExtent();
VkExtent2D maxDim = surfaceCapabilities.maxImageExtent();
fbWidth = Math.max(Math.min(fbWidth, maxDim.width()), minDim.width());
fbHeight = Math.max(Math.min(fbHeight, maxDim.height()), minDim.height());
if (surfaceCapabilities.maxImageCount() != 0)
imageCount = Math.min(imageCount, surfaceCapabilities.maxImageCount());
swapchainCreateInfo.preTransform(surfaceCapabilities.currentTransform())
.minImageCount(imageCount)
.oldSwapchain(swapchain)
.imageExtent()
.width(fbWidth)
.height(fbHeight);
LongBuffer swapchainBfr = stack.callocLong(1);
boolean error = vkCreateSwapchainKHR(device, swapchainCreateInfo, null, swapchainBfr) != VK_SUCCESS;
vkDestroySwapchainKHR(device, swapchain, null);
if (error) {
swapchain = VK_NULL_HANDLE;
return;
} else {
swapchain = swapchainBfr.get(0);
}
swapchainImages = VulkanUtils.getSwapchainImages(device, swapchain);
if (swapchainImages == null) {
vkDestroySwapchainKHR(device, swapchain, null);
swapchain = VK_NULL_HANDLE;
return;
}
if(depthImage != null) depthImage.setDestroy();
depthImage = createTexture(fbWidth, fbHeight, VK_FORMAT_D32_SFLOAT, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, false, 0L);
LongBuffer imageViewBfr = stack.callocLong(1);
swapchainViews = new long[swapchainImages.length];
for (int i = 0; i != swapchainImages.length; i++) {
swapchainImageViewCreateInfo.image(swapchainImages[i]);
long imageView;
try {
imageView = VulkanUtils.createImageView(device, swapchainImages[i], surfaceFormat, true, imageViewBfr);
} catch(Throwable thrown) {
thrown.printStackTrace();
destroySwapchainViews(i);
vkDestroySwapchainKHR(device, swapchain, null);
swapchain = VK_NULL_HANDLE;
return;
}
swapchainViews[i] = imageView;
}
framebufferCreateInfo.width(fbWidth)
.height(fbHeight);
LongBuffer framebufferBfr = stack.callocLong(1);
framebuffers = new long[swapchainViews.length];
for (int i = 0; i != swapchainViews.length; i++) {
framebufferCreateInfo.pAttachments(stack.longs(swapchainViews[i], depthImage.getImageViewId()));
if (vkCreateFramebuffer(device, framebufferCreateInfo, null, framebufferBfr) != VK_SUCCESS) {
destroyFramebuffers(i);
destroySwapchainViews(-1);
vkDestroySwapchainKHR(device, swapchain, null);
swapchain = VK_NULL_HANDLE;
}
framebuffers[i] = framebufferBfr.get(0);
}
backgroundPipeline.resize(fbWidth, fbHeight);
lineUnifiedPipeline.resize(fbWidth, fbHeight);
unifiedMultiPipeline.resize(fbWidth, fbHeight);
unifiedArrayPipeline.resize(fbWidth, fbHeight);
unifiedPipeline.resize(fbWidth, fbHeight);
renderPassBeginInfo.renderArea().extent().width(fbWidth).height(fbHeight);
projMatrix.identity();
projMatrix.scale(1.0f, -1.0f, 1.0f);
projMatrix.ortho(0, width,0, height, -1, 1, true);
projMatrix.get(0, globalUniformBufferData);
}
}
private int swapchainImageIndex = -1;
private boolean commandBufferRecording = false;
private final VkRenderPassBeginInfo renderPassBeginInfo = VkRenderPassBeginInfo.create().sType(VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO).pClearValues(CLEAR_VALUES);
private final static VkClearValue.Buffer CLEAR_VALUES = VkClearValue.create(2); // only zeros is equal to black
static {
CLEAR_VALUES.get(1).depthStencil().set(1, 0);
}
private static final VkCommandBufferBeginInfo commandBufferBeginInfo = VkCommandBufferBeginInfo.calloc().sType(VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO);
@Override
public void startFrame() {
if(swapchainImageIndex != -1) endFrame();
if(resizeScheduled) {
doResize(newWidth, newHeight);
resizeScheduled = false;
}
closeMutex.acquireUninterruptibly();
resourceMutex.acquireUninterruptibly();
closeMutex.release();
try(MemoryStack stack = MemoryStack.stackPush()) {
super.startFrame();
if(swapchain == VK_NULL_HANDLE || framebuffers == null) {
swapchainImageIndex = -1;
return;
}
for (VulkanTextureHandle texture : textures) {
texture.tick();
}
IntBuffer swapchainImageIndexBfr = stack.callocInt(1);
int err = vkAcquireNextImageKHR(device, swapchain, -1L, fetchFramebufferSemaphore, VK_NULL_HANDLE, swapchainImageIndexBfr);
if(err == VK_ERROR_OUT_OF_DATE_KHR || err == VK_SUBOPTIMAL_KHR) resizeScheduled = true;
if(err != VK_SUBOPTIMAL_KHR && err != VK_SUCCESS) {
swapchainImageIndex = -1;
return;
}
swapchainImageIndex = swapchainImageIndexBfr.get(0);
renderPassBeginInfo.framebuffer(framebuffers[swapchainImageIndex]);
if(vkBeginCommandBuffer(graphCommandBuffer, commandBufferBeginInfo) != VK_SUCCESS) return;
if(vkBeginCommandBuffer(memCommandBuffer, commandBufferBeginInfo) != VK_SUCCESS) {
vkEndCommandBuffer(graphCommandBuffer);
return;
}
commandBufferRecording = true;
// reset staging buffer
usedStagingMemory = 0;
stagingBufferIndex = 0;
globalAttrIndex = 0;
multiBuffers.forEach(VulkanMultiBufferHandle::reset);
vkCmdBeginRenderPass(graphCommandBuffer, renderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE);
lastPipeline = null;
update_buffer_region.dstOffset(0).srcOffset(0).size(globalUniformBuffer.getSize());
vkCmdCopyBuffer(memCommandBuffer, globalUniformStagingBuffer.getBufferIdVk(), globalUniformBuffer.getBufferIdVk(), update_buffer_region);
syncQueues(globalUniformBuffer.getEvent(), globalUniformBuffer.getBufferIdVk());
if(textDrawer == null) {
textDrawer = new LWJGLTextDrawer(this, guiScale);
}
} finally {
if(!commandBufferRecording) resourceMutex.release();
}
}
private VulkanBufferHandle framebufferReadBack = null;
private final VkBufferImageCopy.Buffer readBackRegion = VkBufferImageCopy.create(1);
private int rbWidth = -1, rbHeight = -1;
private boolean fbCBrecording = false;
private static final VkImageSubresourceRange CLEAR_SUBRESOURCE = VkImageSubresourceRange.calloc().set(VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1);
public void clearFramebuffer() {
if(!commandBufferRecording) return;
if(!fbCBrecording) {
if(vkBeginCommandBuffer(fbCommandBuffer, commandBufferBeginInfo)!=VK_SUCCESS) return;
fbCBrecording = true;
}
VulkanTextureHandle texture = new VulkanTextureHandle(this, -1, swapchainImages[swapchainImageIndex], 0, 0, 0);
changeLayout(texture, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, false);
vkCmdClearColorImage(fbCommandBuffer, swapchainImages[swapchainImageIndex], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, CLEAR_VALUES.get(0).color(), CLEAR_SUBRESOURCE);
changeLayout(texture, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, false);
}
public void readFramebuffer(IntBuffer pixels, int width, int height) {
if(!commandBufferRecording) return;
if(width > fbWidth) width = fbWidth;
if(height > fbHeight) height = fbHeight;
if(rbWidth != width || rbHeight != height) {
if(framebufferReadBack != null) {
framebufferReadBack.destroy();
buffers.remove(framebufferReadBack);
}
rbWidth = width;
rbHeight = height;
framebufferReadBack = createBuffer(4*rbHeight*rbWidth, READBACK_BUFFER);
}
readBackRegion.bufferOffset(0).bufferRowLength(width);
readBackRegion.imageSubresource().set(VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1);
readBackRegion.imageOffset().set(0, 0, 0);
readBackRegion.imageExtent().set(width, height, 1);
VulkanTextureHandle texture = new VulkanTextureHandle(this, -1, swapchainImages[swapchainImageIndex], 0, 0, 0);
if(vkBeginCommandBuffer(fbCommandBuffer, commandBufferBeginInfo) != VK_SUCCESS) {
return;
}
fbCBrecording = true;
changeLayout(texture, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, false);
vkCmdCopyImageToBuffer(fbCommandBuffer, swapchainImages[swapchainImageIndex], VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, framebufferReadBack.getBufferIdVk(), readBackRegion);
changeLayout(texture, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, false);
vkCmdPipelineBarrier(fbCommandBuffer, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, null, null, null);
vkCmdClearColorImage(fbCommandBuffer, swapchainImages[swapchainImageIndex], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, CLEAR_VALUES.get(0).color(), CLEAR_SUBRESOURCE);
changeLayout(texture, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, false);
endFrame();
PointerBuffer ptr = BufferUtils.createPointerBuffer(1);
Vma.vmaMapMemory(allocators[READBACK_BUFFER], framebufferReadBack.getAllocation(), ptr);
ByteBuffer mapped = MemoryUtil.memByteBuffer(ptr.get(0), framebufferReadBack.getSize());
IntBuffer mappedPixels = mapped.asIntBuffer();
int[] line = new int[width];
for(int i = 0; i != height; i++) {
mappedPixels.position(i*width);
mappedPixels.get(line);
pixels.position((height-i-1)*width);
pixels.put(line);
}
pixels.rewind();
Vma.vmaUnmapMemory(allocators[READBACK_BUFFER], framebufferReadBack.getAllocation());
}
public void endFrame() {
try(MemoryStack stack = MemoryStack.stackPush()) {
boolean cmdBfrSend = false;
if(commandBufferRecording) {
updateBufferAt(globalUniformStagingBuffer, 0, globalUniformBufferData);
vkCmdEndRenderPass(graphCommandBuffer);
vkEndCommandBuffer(graphCommandBuffer);
vkEndCommandBuffer(memCommandBuffer);
if(fbCBrecording) vkEndCommandBuffer(fbCommandBuffer);
commandBufferRecording = false;
VkSubmitInfo graphSubmitInfo = VkSubmitInfo.callocStack(stack)
.sType(VK_STRUCTURE_TYPE_SUBMIT_INFO)
.pSignalSemaphores(stack.longs(presentFramebufferSemaphore));
if(fbCBrecording) {
graphSubmitInfo.pCommandBuffers(stack.pointers(memCommandBuffer.address(), graphCommandBuffer.address(), fbCommandBuffer.address()));
fbCBrecording = false;
} else {
graphSubmitInfo.pCommandBuffers(stack.pointers(memCommandBuffer.address(), graphCommandBuffer.address()));
}
if(swapchainImageIndex != -1) {
graphSubmitInfo.pWaitSemaphores(stack.longs(fetchFramebufferSemaphore))
.pWaitDstStageMask(stack.ints(VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT))
.waitSemaphoreCount(1);
}
int error = vkQueueSubmit(graphicsQueue, graphSubmitInfo, VK_NULL_HANDLE);
if(error != VK_SUCCESS) {
// whatever
System.out.println("Could not submit CommandBuffers: " + error);
} else {
cmdBfrSend = true;
}
}
if(swapchainImageIndex != -1) {
VkPresentInfoKHR presentInfo = VkPresentInfoKHR.callocStack(stack)
.sType(VK_STRUCTURE_TYPE_PRESENT_INFO_KHR)
.pImageIndices(stack.ints(swapchainImageIndex))
.swapchainCount(1)
.pSwapchains(stack.longs(swapchain));
if(cmdBfrSend) presentInfo.pWaitSemaphores(stack.longs(presentFramebufferSemaphore));
if(vkQueuePresentKHR(presentQueue, presentInfo) != VK_SUCCESS) {
// should not happen but we can't do anything about it
}
vkQueueWaitIdle(presentQueue);
swapchainImageIndex = -1;
}
} finally {
resourceMutex.release();
}
}
private VulkanPipeline lastPipeline = null;
private void bind(VulkanPipeline pipeline) {
if(pipeline != lastPipeline) {
pipeline.bind(graphCommandBuffer, frameIndex);
lastPipeline = pipeline;
}
}
private void bindDescSets(long... descSets) {
lastPipeline.bindDescSets(graphCommandBuffer, descSets);
}
private long getTextureDescSet(TextureHandle texture) {
if(texture == null) {
return textures.stream().filter(tex -> tex.getTextureId() != -1).findAny().get().descSet;
} else {
return ((VulkanTextureHandle) texture).descSet;
}
}
private final VkDescriptorBufferInfo.Buffer install_uniform_buffer = VkDescriptorBufferInfo.create(1).range(VK_WHOLE_SIZE);
private final VkWriteDescriptorSet.Buffer install_uniform_buffer_write = VkWriteDescriptorSet.create(1)
.sType(VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET)
.descriptorType(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER)
.pBufferInfo(install_uniform_buffer)
.descriptorCount(1)
.dstArrayElement(0);
private void installUniformBuffer(VulkanBufferHandle buffer, int binding) {
install_uniform_buffer_write.dstBinding(binding);
install_uniform_buffer.buffer(buffer.getBufferIdVk());
backgroundPipeline.update(install_uniform_buffer_write);
lineUnifiedPipeline.update(install_uniform_buffer_write);
unifiedArrayPipeline.update(install_uniform_buffer_write);
unifiedMultiPipeline.update(install_uniform_buffer_write);
unifiedPipeline.update(install_uniform_buffer_write);
}
private void installUniformBuffer(VulkanBufferHandle buffer, int binding, int index, VulkanPipeline pipeline) {
install_uniform_buffer_write.dstBinding(binding);
install_uniform_buffer_write.dstArrayElement(index);
install_uniform_buffer.buffer(buffer.getBufferIdVk());
pipeline.update(install_uniform_buffer_write);
}
private long createMultiDescriptorSet(VulkanBufferHandle multiBuffer) {
long descSet = multiDescPool.createNewSet(multiDescLayout);
VkDescriptorBufferInfo.Buffer install_uniform_buffer = VkDescriptorBufferInfo.create(1);
install_uniform_buffer.get(0).set(multiBuffer.getBufferIdVk(), 0, VK_WHOLE_SIZE);
VkWriteDescriptorSet.Buffer install_uniform_buffer_write = VkWriteDescriptorSet.create(1)
.sType(VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET)
.descriptorType(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER)
.pBufferInfo(install_uniform_buffer)
.descriptorCount(1)
.dstArrayElement(0)
.dstBinding(0)
.dstSet(descSet);
vkUpdateDescriptorSets(device, install_uniform_buffer_write, null);
return descSet;
}
}
|
package kz.kbtu.auth.type;
public enum Faculty {
FIT,
MCM,
BS,
ISE,
KMA,
FOGI,
FGA
}
|
package ru.job4j.sortirovka.sortirovkacomparator;
import java.util.Comparator;
public class ComparatorByName implements Comparator<User> {
@Override
public int compare(User a, User b) {
return a.getName().compareTo(b.getName());
}
}
|
package com.example.model;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class DAOCustomerImplementation implements DAOCustomer {
private List<Customer> customers = new ArrayList<>();
public DAOCustomerImplementation() {
File fc = new File("customers.ser");
if (fc.exists()) {
ObjectInputStream ois;
try {
ois = new ObjectInputStream(
new FileInputStream("customers.ser"));
customers = (List<Customer>) ois.readObject();
ois.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Override
public List<Customer> getAllCustomers() {
return customers;
}
@Override
public void addCustomer(Customer c) {
if (customers.size() != 0) {
c.setId(customers.get(customers.size() - 1).id + 1);
}
customers.add(c);
saveCustomers();
}
@Override
public void removeCustomer(int id) {
int find_id = 0, i;
for (i = 0; i < customers.size(); i++) {
if (customers.get(i).id == id)
find_id = i;
}
customers.remove(find_id);
saveCustomers();
}
private void saveCustomers() {
ObjectOutputStream oos;
try {
oos = new ObjectOutputStream(new FileOutputStream("customers.ser"));
oos.writeObject(customers);
oos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
package com.cloudogu.smeagol.wiki.domain;
import java.util.Optional;
/**
* PageRepositories are able to execute crud actions on pages.
*/
public interface PageRepository {
/**
* Saves the page.
*
* @param page modified page
*/
Page save(Page page);
/**
* Returns {@code true} if the path exists.
*
* @return {@code true} if path exists
*/
boolean exists(WikiId wikiId, Path path);
/**
* Find the page with the given path in the requested wiki.
*
* @param wikiId id of the wiki
* @param path path of the page
*
* @return page with path
*/
Optional<Page> findByWikiIdAndPath(WikiId wikiId, Path path);
/**
* Find the page with the given path and commitId in the requested wiki.
*
* @param wikiId id of the wiki
* @param path path of the page
* @param commitId id of the commit
*
* @return page with path
*/
Optional<Page> findByWikiIdAndPathAndCommit(WikiId wikiId, Path path, CommitId commitId);
/**
* Deletes the page.
*
* @param page deleted page
* @param commit delete commit
*/
void delete(Page page, Commit commit);
}
|
package com.niloy.dxball_new;
/**
* Created by user on 5/10/2017.
*/
import java.util.ArrayList;
import android.graphics.Canvas;
import android.util.Log;
public class Collision {
Bricks brick;
Ball ball;
Bar bar;
Canvas canvas;
public void setCanvas(Canvas canvas)
{
this.canvas=canvas;
}
void ballWithBar(ArrayList <GameObject> gameObjectLsit){
ball=(Ball)gameObjectLsit.get(0);
if(gameObjectLsit.size()>1)
{
bar =(Bar)gameObjectLsit.get(1);
if(bar.x-10<=ball.x && bar.x1+10>= ball.x && ball.y+30>this.canvas.getHeight()-30)
{
ball.speedY=-5;
}
}
}
void ballWithBrick(ArrayList<GameObject> gameObjectList)
{
ball=(Ball)gameObjectList.get(0);
if(gameObjectList.size()>2)
{
for(int i=2;i<gameObjectList.size();i++)
{
try{
brick=(Bricks) gameObjectList.get(i);
if(ball.x>=brick.x-25 && ball.x<= brick.x1+25 && ball.y-30<brick.y1+3 && ball.y-30>brick.y1-3){
GameCanvas.Score+=10;
brick.life--;
ball.speedY=5;
}
else if(ball.x+30>=brick.x-2 && ball.x+30 <= brick.x+2 && ball.y<= brick.y1+25 && ball.y>= brick.y-25 ){
GameCanvas.Score+=10;
brick.life--;
ball.speedX=-5;
}
else if(ball.x-30<= brick.x1+2 && ball.x-30>=brick.x1-2 && ball.y<= brick.y1+25 && ball.y >= brick.y-25 )
{
GameCanvas.Score+=10;
brick.life--;
ball.speedY=5;
ball.speedX=5;
}
else if(ball.x>=brick.x-25 && ball.x<= brick.x1+25 && ball.y+30>=brick.y-2 && ball.y+30<=brick.y+2)
{
GameCanvas.Score+=10;
brick.life--;
ball.speedY=-5;
ball.speedX=-5;
}
if(brick.life==0)
{
gameObjectList.remove(i);
}
}catch (Exception e)
{
e.getMessage();
}
}
}
}
}
|
import javafx.scene.canvas.GraphicsContext;
/**
*
* @author MunerKhan
*/
public interface MyShapeInterface {
public abstract double getArea();
public abstract double getPerimeter();
public abstract void draw(GraphicsContext shapeCont);
public abstract MyRectangle getMyBoundingRectangle();
public abstract boolean pointInMyShape(MyPoint p);
public abstract double intersectMyShape(MyShape shape1);
}
|
package Exception.BlockException;
public class BlockConstructFailException extends BlockException{
public BlockConstructFailException(String message) {
super(message);
}
}
|
package headFirst.adapter.object;
/**
* 클라이언트인 칠면조의 요청을,
* 어댑티인 오리의 요청에 맞추기 위해
* 어댑티를 둔다. 이 어댑티는 오리의 요청을 인터페이스로 상속받는다.
*/
public class DuckTestDrive {
public static void main(String[] args) {
MallarDuck duck = new MallarDuck();
WildTurkey turkey = new WildTurkey();
Duck turkeyAdapter = new TurkeyAdapter(turkey);
System.out.println("야생 칠면조가 말하길");
turkey.gobble();
turkey.fly();
System.out.println("\n 물오리가 말하길");
duck.quack();
duck.fly();
System.out.println("\n 칠면조 어대터가 말하길");
testDuck(turkeyAdapter);
}
static void testDuck(Duck duck){
duck.quack();
duck.fly();
}
}
|
package Template.EditorialTemplate;
import NodeAndComponentConfig.navigateToNode;
import NodeAndComponentConfig.rightClickInsert;
import NodeAndComponentConfig.whatIsTheComponentName;
import TemplateImplementation.globalTemplateImplementation;
import Util.Config;
import Util.DataUtil;
import Util.Xls_Reader;
import Util.excelConfig;
import base.testBase;
import mapDataSourceWithFE.editorialTemplateControls;
import mapDataSourceWithFE.mapControlWithDataSource;
import org.openqa.selenium.support.PageFactory;
import org.testng.SkipException;
import org.testng.annotations.AfterClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Hashtable;
import java.util.List;
public class Editorial_WhyWeTravel extends testBase {
String testSheetName = "Editorial_WhyWeTravel";
public mapControlWithDataSource mapcontrolWithDataSource;
@Test
public void testMethod() {
}
/* @AfterClass
public void mapDataSourceWithFrontEndControls() throws Exception {
Xls_Reader xls = new Xls_Reader(excelConfig.TESTDATA_XLS_PATH);
invokeBrowser();
// editorialComponentList();
globalTemplateImplementation sitecore = new globalTemplateImplementation(driver, test.get());
PageFactory.initElements(driver, sitecore);
editorialTemplateControls editorialtemplateControl = sitecore.launchSitecore()
.login()
.goToContentEditorIfNotKickOffUser()
.navigateToWhichTauckNodeForMappingDataSourceWithFrontEndControl(navigateToNode.EDITORIAL_WHY_WE_TRAVEL)
.clickPresentationLink()
.clickDetailsLink()
.clickFinalLayoutTabInsideLayoutDetailsDialog()
.navigateToDeviceEditor()
.clickControlsInsideDeviceEditorForMappingDataSourceSequentially();
List<String> listOfComponentToMapWithDataSource = DataUtil.grabControlListForMapping(xls,testSheetName,"Template_Control");
for (int outerloop = 0; outerloop < listOfComponentToMapWithDataSource.size(); outerloop++) {
// Xls_Reader xls = new Xls_Reader(excelConfig.TESTDATA_XLS_PATH);
Hashtable<String, String> data = DataUtil.getControlDatasourcePlaceholderValueFromXls(xls, listOfComponentToMapWithDataSource.get(outerloop), testSheetName);
List<String> splitControlString = Arrays.asList(data.get("Control").split("\\|"));
List<String> splitPlaceholderString = Arrays.asList(data.get("PlaceHolder").split("\\|"));
List<String> splitDatasourceString = Arrays.asList(data.get("DataSource").split("\\|"));
for (int innerloop = 0; innerloop < splitControlString.size(); innerloop++) {
mapcontrolWithDataSource = editorialtemplateControl
.addNewControls()
.selectWhichControlsToAdd()
.addEditorialTemplateFEControl(splitControlString.get(innerloop))
.openPropertyDialogBoxCheckbox()
.clickSelectButton()
.inputPlaceHolderAndDataSource(splitPlaceholderString.get(innerloop), splitDatasourceString.get(innerloop));
}
}
mapcontrolWithDataSource
.saveAndCloseDeviceEditorAndLayoutDetails();
}
/* @Test
public void create_EditorialSubTemplate_WhyWeTravel() throws Exception {
invokeBrowser();
globalTemplateImplementation sitecore = new globalTemplateImplementation(driver, test.get());
PageFactory.initElements(driver, sitecore);
sitecore.launchSitecore()
.login()
.goToContentEditorIfNotKickOffUser()
// Creating EditorialTemplate template
.navigateToWhichTauckNode(navigateToNode.HOME)
.rightClickInsertTemplateOrComponent(rightClickInsert.EDITORIAL_SUB_TEMPLATE_WHY_WE_TRAVEL)
.switchToContentIframeDialog(Config.PARENT_FRAME, Config.CHILD_FRAME);
// Delete pre-added FE Controls before mapping datasource.
Object mapControlswithDataSource = sitecore.createTemplateOrTemplateComponent(whatIsTheComponentName.EDITORIAL_SUB_TEMPLATE_WHY_WE_TRAVEL, mapControlWithDataSource.class.getSimpleName());
if (mapControlswithDataSource instanceof mapControlWithDataSource)
((mapControlWithDataSource) mapControlswithDataSource)
.clickPresentationLink()
.clickDetailsLink()
.clickFinalLayoutTabInsideLayoutDetailsDialog()
.navigateToDeviceEditor()
.clickControlsInsideDeviceEditor()
.removePreAddedFEControls();
}
@Test(dependsOnMethods = {"create_EditorialSubTemplate_WhyWeTravel"}, dataProvider = "readTestData")
public void verifyPreFeededSubCategoriesInsideTemplate(Hashtable<String, String> data) throws InterruptedException, IOException {
if (!DataUtil.isTestExecutable(xls, testSheetName)) {
throw new SkipException("Skipping the test as Rnumode is N");
}
if (!data.get(excelConfig.RUNMODE_COL).equals("Y")) {
throw new SkipException("Skipping the test as Rnumode is N");
}
invokeBrowser();
globalTemplateImplementation sitecore = new globalTemplateImplementation(driver, test.get());
PageFactory.initElements(driver, sitecore);
sitecore
.login()
.goToContentEditorIfNotKickOffUser()
.verifyPreFeededSubComponent(navigateToNode.EDITORIAL_WHY_WE_TRAVEL, Arrays.asList(data.get("CategoriesList").split("\\|")));
}
// @Test( dependsOnMethods = {"create_EditorialSubTemplate_WhyWeTravel", "verifyPreFeededSubCategoriesInsideTemplate"}, dataProvider = "readTestData")
@Test( dataProvider = "readTestData")
public void fill_Content_Of_Editorial_Title_Component(Hashtable<String, String> data) throws InterruptedException, IOException {
if (!DataUtil.isTestExecutable(xls, testSheetName)) {
throw new SkipException("Skipping the test as Rnumode is N");
}
if (!data.get(excelConfig.RUNMODE_COL).equals("Y")) {
throw new SkipException("Skipping the test as Rnumode is N");
}
invokeBrowser();
globalTemplateImplementation sitecore = new globalTemplateImplementation(driver, test.get());
PageFactory.initElements(driver, sitecore);
sitecore
.login()
.goToContentEditorIfNotKickOffUser()
.navigateToWhichTauckNode(navigateToNode.EDITORIAL_WHY_WE_TRAVEL , "/" + data.get("preFeededComponentName"))
.fill_Component_Content_With_Data(data.get("Content"));
}
// @Test( dependsOnMethods = {"create_EditorialSubTemplate_WhyWeTravel", "verifyPreFeededSubCategoriesInsideTemplate"}, dataProvider = "readTestData")
@Test( dataProvider = "readTestData")
public void fill_Content_Of_Header_Hero_Component(Hashtable<String, String> data) throws InterruptedException, IOException {
if (!DataUtil.isTestExecutable(xls, testSheetName)) {
throw new SkipException("Skipping the test as Rnumode is N");
}
if (!data.get(excelConfig.RUNMODE_COL).equals("Y")) {
throw new SkipException("Skipping the test as Rnumode is N");
}
invokeBrowser();
globalTemplateImplementation sitecore = new globalTemplateImplementation(driver, test.get());
PageFactory.initElements(driver, sitecore);
sitecore
.login()
.goToContentEditorIfNotKickOffUser()
.navigateToWhichTauckNode(navigateToNode.EDITORIAL_WHY_WE_TRAVEL, "/" + data.get("preFeededComponentName"))
.fill_Component_Content_With_Data(data.get("Content"));
}
// @Test( dependsOnMethods = {"create_EditorialSubTemplate_WhyWeTravel", "verifyPreFeededSubCategoriesInsideTemplate"}, dataProvider = "readTestData")
@Test( dataProvider = "readTestData")
public void add_Rich_Text_Copy_Inside_Text_Copy_Folder_And_fill_Content(Hashtable<String, String> data) throws
InterruptedException, IOException {
if (!DataUtil.isTestExecutable(xls, testSheetName)) {
throw new SkipException("Skipping the test as Rnumode is N");
}
if (!data.get(excelConfig.RUNMODE_COL).equals("Y")) {
throw new SkipException("Skipping the test as Rnumode is N");
}
invokeBrowser();
globalTemplateImplementation sitecore = new globalTemplateImplementation(driver, test.get());
PageFactory.initElements(driver, sitecore);
sitecore
.login()
.goToContentEditorIfNotKickOffUser();
for (int i = 0; i < DataUtil.splitStringBasedOnComma(data.get("ComponentName")).size(); i++) {
sitecore
.navigateToWhichTauckNode(navigateToNode.EDITORIAL_WHY_WE_TRAVEL, "/" + data.get("preFeededComponentName"))
.rightClickInsertTemplateOrComponent(data.get("RightClickInsert"))
.switchToContentIframeDialog(Config.PARENT_FRAME, Config.CHILD_FRAME)
.createTemplateOrTemplateComponent(DataUtil.splitStringBasedOnComma(data.get("ComponentName")).get(i))
.fill_Component_Content_With_Data(DataUtil.splitStringBasedOnUnderscore(data.get("Content")).get(i));
}
}
// @Test( dependsOnMethods = {"create_EditorialSubTemplate_WhyWeTravel", "verifyPreFeededSubCategoriesInsideTemplate"}, dataProvider = "readTestData")
@Test( dataProvider = "readTestData")
public void add_MediaCarouselCards_And_fill_Content(Hashtable<String, String> data) throws
InterruptedException, IOException {
if (!DataUtil.isTestExecutable(xls, testSheetName)) {
throw new SkipException("Skipping the test as Rnumode is N");
}
if (!data.get(excelConfig.RUNMODE_COL).equals("Y")) {
throw new SkipException("Skipping the test as Rnumode is N");
}
invokeBrowser();
globalTemplateImplementation sitecore = new globalTemplateImplementation(driver, test.get());
PageFactory.initElements(driver, sitecore);
sitecore
.login()
.goToContentEditorIfNotKickOffUser();
for (int i = 0; i < DataUtil.splitStringBasedOnComma(data.get("ComponentName")).size(); i++) {
sitecore
.navigateToWhichTauckNode(navigateToNode.EDITORIAL_WHY_WE_TRAVEL, "/" + data.get("preFeededComponentName"))
.rightClickInsertTemplateOrComponent(data.get("RightClickInsert"))
.switchToContentIframeDialog(Config.PARENT_FRAME, Config.CHILD_FRAME)
.createTemplateOrTemplateComponent(DataUtil.splitStringBasedOnComma(data.get("ComponentName")).get(i))
.fill_Component_Content_With_Data(DataUtil.splitStringBasedOnUnderscore(data.get("Content")).get(i));
}
sitecore
.navigateToWhichTauckNode(navigateToNode.EDITORIAL_WHY_WE_TRAVEL, "/" + data.get("preFeededComponentName"))
.MultiListSelection(DataUtil.splitStringBasedOnComma(data.get("ComponentName")));
}
// @Test( dependsOnMethods = {"create_EditorialSubTemplate_WhyWeTravel", "verifyPreFeededSubCategoriesInsideTemplate"}, dataProvider = "readTestData")
@Test( dataProvider = "readTestData")
public void add_GridMediaCards_And_fill_Content(Hashtable<String, String> data) throws
InterruptedException, IOException {
if (!DataUtil.isTestExecutable(xls, testSheetName)) {
throw new SkipException("Skipping the test as Rnumode is N");
}
if (!data.get(excelConfig.RUNMODE_COL).equals("Y")) {
throw new SkipException("Skipping the test as Rnumode is N");
}
invokeBrowser();
globalTemplateImplementation sitecore = new globalTemplateImplementation(driver, test.get());
PageFactory.initElements(driver, sitecore);
sitecore
.login()
.goToContentEditorIfNotKickOffUser();
for (int i = 0; i < DataUtil.splitStringBasedOnComma(data.get("ComponentName")).size(); i++) {
sitecore
.navigateToWhichTauckNode(navigateToNode.EDITORIAL_WHY_WE_TRAVEL, "/" + data.get("preFeededComponentName"))
.rightClickInsertTemplateOrComponent(data.get("RightClickInsert"))
.switchToContentIframeDialog(Config.PARENT_FRAME, Config.CHILD_FRAME)
.createTemplateOrTemplateComponent(DataUtil.splitStringBasedOnComma(data.get("ComponentName")).get(i))
.fill_Component_Content_With_Data(DataUtil.splitStringBasedOnUnderscore(data.get("Content")).get(i));
}
}
// @Test( dependsOnMethods = {"create_EditorialSubTemplate_WhyWeTravel", "verifyPreFeededSubCategoriesInsideTemplate"}, dataProvider = "readTestData")
@Test( dataProvider = "readTestData")
public void add_AuthorProfile_And_fill_Content(Hashtable<String, String> data) throws
InterruptedException, IOException {
if (!DataUtil.isTestExecutable(xls, testSheetName)) {
throw new SkipException("Skipping the test as Rnumode is N");
}
if (!data.get(excelConfig.RUNMODE_COL).equals("Y")) {
throw new SkipException("Skipping the test as Rnumode is N");
}
invokeBrowser();
globalTemplateImplementation sitecore = new globalTemplateImplementation(driver, test.get());
PageFactory.initElements(driver, sitecore);
sitecore
.login()
.goToContentEditorIfNotKickOffUser()
.navigateToWhichTauckNode(navigateToNode.EDITORIAL_WHY_WE_TRAVEL, "/" + data.get("preFeededComponentName"))
.fill_Component_Content_With_Data(data.get("Content"));
}
// @Test( dependsOnMethods = {"create_EditorialSubTemplate_WhyWeTravel", "verifyPreFeededSubCategoriesInsideTemplate"}, dataProvider = "readTestData")
@Test( dataProvider = "readTestData")
public void add_EditorialQuote_And_fill_Content(Hashtable<String, String> data) throws
InterruptedException, IOException {
if (!DataUtil.isTestExecutable(xls, testSheetName)) {
throw new SkipException("Skipping the test as Rnumode is N");
}
if (!data.get(excelConfig.RUNMODE_COL).equals("Y")) {
throw new SkipException("Skipping the test as Rnumode is N");
}
invokeBrowser();
globalTemplateImplementation sitecore = new globalTemplateImplementation(driver, test.get());
PageFactory.initElements(driver, sitecore);
sitecore
.login()
.goToContentEditorIfNotKickOffUser();
for (int i = 0; i < DataUtil.splitStringBasedOnComma(data.get("ComponentName")).size(); i++) {
sitecore
.navigateToWhichTauckNode(navigateToNode.EDITORIAL_WHY_WE_TRAVEL, "/" + data.get("preFeededComponentName"))
.rightClickInsertTemplateOrComponent(data.get("RightClickInsert"))
.switchToContentIframeDialog(Config.PARENT_FRAME, Config.CHILD_FRAME)
.createTemplateOrTemplateComponent(DataUtil.splitStringBasedOnComma(data.get("ComponentName")).get(i))
.fill_Component_Content_With_Data(DataUtil.splitStringBasedOnUnderscore(data.get("Content")).get(i));
}
}
// @Test( dependsOnMethods = {"create_EditorialSubTemplate_WhyWeTravel", "verifyPreFeededSubCategoriesInsideTemplate"}, dataProvider = "readTestData")
@Test( dataProvider = "readTestData")
public void add_FeaturedBrand_And_fill_Content(Hashtable<String, String> data) throws
InterruptedException, IOException {
if (!DataUtil.isTestExecutable(xls, testSheetName)) {
throw new SkipException("Skipping the test as Rnumode is N");
}
if (!data.get(excelConfig.RUNMODE_COL).equals("Y")) {
throw new SkipException("Skipping the test as Rnumode is N");
}
invokeBrowser();
globalTemplateImplementation sitecore = new globalTemplateImplementation(driver, test.get());
PageFactory.initElements(driver, sitecore);
sitecore
.login()
.goToContentEditorIfNotKickOffUser();
for (int i = 0; i < DataUtil.splitStringBasedOnComma(data.get("ComponentName")).size(); i++) {
sitecore
.navigateToWhichTauckNode(navigateToNode.EDITORIAL_WHY_WE_TRAVEL, "/" + data.get("preFeededComponentName"))
.rightClickInsertTemplateOrComponent(data.get("RightClickInsert"))
.switchToContentIframeDialog(Config.PARENT_FRAME, Config.CHILD_FRAME)
.createTemplateOrTemplateComponent(DataUtil.splitStringBasedOnComma(data.get("ComponentName")).get(i))
.fill_Component_Content_With_Data(DataUtil.splitStringBasedOnUnderscore(data.get("Content")).get(i));
}
}*/
@DataProvider(name = "readTestData")
public Object[][] getData(Method method) {
Xls_Reader xls = new Xls_Reader(excelConfig.TESTDATA_XLS_PATH);
if (method.getName().equals("verifyPreFeededSubCategoriesInsideTemplate")) {
return DataUtil.getData(xls, "PreFeededSubCategories", testSheetName);
} else if (method.getName().equals("fill_Content_Of_Editorial_Title_Component")) {
return DataUtil.getData(xls, "EditorialTitle", testSheetName);
} else if (method.getName().equals("fill_Content_Of_Header_Hero_Component")) {
return DataUtil.getData(xls, "HeaderHero", testSheetName);
} else if (method.getName().equals("add_MediaCarouselCards_And_fill_Content")) {
return DataUtil.getData(xls, "MediaCarousel", testSheetName);
} else if (method.getName().equals("add_Rich_Text_Copy_Inside_Text_Copy_Folder_And_fill_Content")) {
return DataUtil.getData(xls, "TextCopyFolder", testSheetName);
} else if (method.getName().equals("add_GridMediaCards_And_fill_Content")) {
return DataUtil.getData(xls, "GridMediaFolder", testSheetName);
} else if (method.getName().equals("add_AuthorProfile_And_fill_Content")) {
return DataUtil.getData(xls, "AuthorProfiles", testSheetName);
} else if (method.getName().equals("add_EditorialQuote_And_fill_Content")) {
return DataUtil.getData(xls, "EditoriaQuotes", testSheetName);
} else if (method.getName().equals("add_FeaturedBrand_And_fill_Content")) {
return DataUtil.getData(xls, "FeaturedBrand", testSheetName);
}
return null;
}
}
|
package pl.edu.pw.mini.gapso.optimizer.restart;
import org.junit.Assert;
import pl.edu.pw.mini.gapso.function.Function;
import pl.edu.pw.mini.gapso.optimizer.Particle;
import pl.edu.pw.mini.gapso.optimizer.Swarm;
public class RestartScheme {
public static final double BORDERLINE_CASE_THRESHOLD = 1e-8;
public static double[][] samples = new double[][]{
{0.0, 0.0},
{-BORDERLINE_CASE_THRESHOLD / 10, BORDERLINE_CASE_THRESHOLD / 10},
{BORDERLINE_CASE_THRESHOLD / 10, BORDERLINE_CASE_THRESHOLD / 10},
{BORDERLINE_CASE_THRESHOLD, BORDERLINE_CASE_THRESHOLD / 10},
{BORDERLINE_CASE_THRESHOLD, BORDERLINE_CASE_THRESHOLD},
{BORDERLINE_CASE_THRESHOLD * 10, 4.0}
};
public static double[][] samplesForSpread = new double[][]{
{1.0, 1.0},
{1 - BORDERLINE_CASE_THRESHOLD / 10, BORDERLINE_CASE_THRESHOLD / 10},
{1 + BORDERLINE_CASE_THRESHOLD / 10, BORDERLINE_CASE_THRESHOLD / 10},
{1 + BORDERLINE_CASE_THRESHOLD, BORDERLINE_CASE_THRESHOLD / 10},
{1 + BORDERLINE_CASE_THRESHOLD, BORDERLINE_CASE_THRESHOLD},
{1 + BORDERLINE_CASE_THRESHOLD * 10, 4.0}
};
public static void ValidateRestartManagerAgainstRestartsScheme(Function function, double[][] samples, boolean[] restarts, RestartManager observer) {
Swarm swarm = new Swarm();
Assert.assertTrue(observer.shouldBeRestarted(swarm.getParticles()));
for (
int i = 0;
i < samples.length; ++i) {
new Particle(
samples[i],
function,
swarm
);
final boolean actual = observer.shouldBeRestarted(swarm.getParticles());
Assert.assertEquals(restarts[i], actual);
}
}
}
|
/**
*
*/
package com.wonders.task.autoUrge.util;
/**
* @ClassName: GenerateSqlUtil
* @Description: TODO(这里用一句话描述这个类的作用)
* @author zhoushun
* @date 2013-4-29 下午7:01:01
*
*/
public class GenerateSqlUtil {
public static String urgeSql = "";
public static String overSql = "";
public static String mobileSql = "";
public static String delaySql = "";
public static String deptSql = "";
public static String generateOverInfoSql(String overdate){
overSql =
"select substr(t.helpurl,instr(t.helpurl,':')+1,instr(t.helpurl,'<+>')-instr(t.helpurl,':')-1) deptId, " +
" i.summary," +
" b.pname as pname," +
" b.pincident as pincident, " +
" b.cname as cname, " +
" b.cincident as cincident," +
" t.assignedtouser userId," +
" c.name userName," +
" v.login_name leaderId,v.name leaderName," +
" v.dept_id deptIdd ,v.dept deptNamee ," +
" to_char(" +
" to_date(to_char(sysdate,'YYYY.MM.DD'),'YYYY.MM.DD')-to_date(to_char(t.starttime,'YYYY.MM.DD'),'YYYY.MM.DD')" +
" ) delay" +
" from t_subprocess b, tasks t , v_dept_leaders v ,incidents i , cs_user c" +
" where b.cname = t.processname" +
" and b.cname='部门内部子流程'" +
" and b.cincident = t.incident" +
" and (instr(t.helpurl,'<+>') >0)" +
" and t.status = 1 " +
" and c.removed = 0 and 'ST/'||c.login_name= t.assignedtouser" +
" and b.pname=i.processname and b.pincident = i.incident and i.status != 33" +
" and substr(t.helpurl,instr(t.helpurl,':')+1,instr(t.helpurl,'<+>')-instr(t.helpurl,':')-1) = v.dept_id" +
" and t.overduetime is not null "+
" and to_date(to_char(sysdate,'YYYY.MM.DD'),'YYYY.MM.DD')-to_date(to_char(t.overduetime,'YYYY.MM.DD'),'YYYY.MM.DD')>1" +
" and mod(" +
" to_date(to_char(sysdate,'YYYY.MM.DD'),'YYYY.MM.DD')-to_date(to_char(t.overduetime,'YYYY.MM.DD'),'YYYY.MM.DD'),"+overdate+
" )=0" ;
return overSql;
}
public static String generateDelayInfoSql(){
delaySql = "select t.process,t.incident from t_delay_item t where " +
" t.delay_date > to_char(sysdate,'yyyy-mm-dd') " +
" and status = '0' and removed ='0'";
return delaySql;
}
public static String generateMobleInfoSql(){
mobileSql = "select 'ST/'||c.login_name as userId,c.name," +
" case " +
" when " +
" c.mobile1 is not null then c.mobile1" +
" else " +
" c.mobile2 end mobile" +
" from cs_user c " +
" where c.removed=0 and (c.mobile1 is not null or c.mobile2 is not null)";
return mobileSql;
}
public static String gengerateUrgeInfoSql(String overdate){
urgeSql = "select o.summary, o.userId, o.leaderId,o.userName,o.deptIdd deptId, o.deptNamee deptName from ("+generateOverInfoSql(overdate)+") o "+
" where not exists (" +
" select '' from t_delay_item d where o.cname = d.process" +
" and o.cincident = d.incident and " +
" d.delay_date > to_char(sysdate,'yyyy-mm-dd') " +
" and d.status = '0' and d.removed ='0' )";
//System.out.println("urgeSql=:"+urgeSql);
return urgeSql;
}
}
|
package com.github.bobby.multithreading;
public class Log {
private String uuid;
private String logName;
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public String getLogName() {
return logName;
}
public void setLogName(String logName) {
this.logName = logName;
}
}
|
package LC0_200.LC150_200;
public class LC200_Numbers_Of_Islands {
public int numIslands(char[][] grid) {
int re = 0;
for(int i = 0; i < grid.length; ++i)
for(int j = 0; j < grid[0].length; ++j)
if(grid[i][j] == '1') {
re++;
dfs(grid, i, j);
}
return re;
}
void dfs(char[][] grid, int y, int x) {
//if out of bounds or at a cell with '0' or '*', simply stop and return
if(x < 0 || x >= grid[0].length || y < 0 || y >= grid.length || grid[y][x] != '1')
return;
grid[y][x] = '*';
dfs(grid, y + 1, x);
dfs(grid, y, x + 1);
dfs(grid, y - 1, x);
dfs(grid, y, x - 1);
}
}
|
/*
* Copyright 2017 DSATool team
*
* 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 heroes.inventory;
import org.controlsfx.control.CheckComboBox;
import dsa41basis.fight.RangedWeapon;
import dsatool.resources.ResourceManager;
import dsatool.util.ErrorLogger;
import dsatool.util.ReactiveSpinner;
import dsatool.util.Tuple3;
import dsatool.util.Tuple5;
import javafx.collections.FXCollections;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.Window;
import jsonant.value.JSONObject;
public class RangedWeaponEditor {
@FXML
private VBox root;
@FXML
private TextField name;
@FXML
private TextField type;
@FXML
private TextField notes;
@FXML
private Button okButton;
@FXML
private CheckBox noBullet;
@FXML
private CheckBox noBulletweight;
@FXML
private ReactiveSpinner<Integer> weight;
@FXML
private ComboBox<String> bulletType;
@FXML
private ReactiveSpinner<Integer> weightBullet;
@FXML
private CheckBox tpStamina;
@FXML
private CheckBox tpWound;
@FXML
private ReactiveSpinner<Integer> tpNumDice;
@FXML
private ReactiveSpinner<Integer> tpTypeDice;
@FXML
private ReactiveSpinner<Integer> tpAdditional;
@FXML
private ReactiveSpinner<Integer> load;
@FXML
private ReactiveSpinner<Integer> distanceVeryClose;
@FXML
private ReactiveSpinner<Integer> distanceClose;
@FXML
private ReactiveSpinner<Integer> distanceMedium;
@FXML
private ReactiveSpinner<Integer> distanceFar;
@FXML
private ReactiveSpinner<Integer> distanceVeryFar;
@FXML
private ReactiveSpinner<Integer> distanceTPVeryClose;
@FXML
private ReactiveSpinner<Integer> distanceTPClose;
@FXML
private ReactiveSpinner<Integer> distanceTPMedium;
@FXML
private ReactiveSpinner<Integer> distanceTPFar;
@FXML
private ReactiveSpinner<Integer> distanceTPVeryFar;
@FXML
private Button cancelButton;
@FXML
private CheckComboBox<String> talents;
public RangedWeaponEditor(final Window window, final RangedWeapon weapon) {
final FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setController(this);
try {
fxmlLoader.load(getClass().getResource("RangedWeaponEditor.fxml").openStream());
} catch (final Exception e) {
ErrorLogger.logError(e);
}
final Stage stage = new Stage();
stage.setTitle("Bearbeiten");
stage.setScene(new Scene(root, 440, 330));
stage.initModality(Modality.WINDOW_MODAL);
stage.initOwner(window);
name.setText(weapon.getName());
type.setText(weapon.getItemType());
final JSONObject rangedTalents = ResourceManager.getResource("data/Talente").getObj("Fernkampftalente");
for (final String talent : rangedTalents.keySet()) {
talents.getItems().add(talent);
}
for (final String talent : weapon.getTalents()) {
talents.getCheckModel().check(talent);
}
final Tuple3<Integer, Integer, Integer> tpValues = weapon.getTpRaw();
tpNumDice.getValueFactory().setValue(tpValues._1);
tpTypeDice.getValueFactory().setValue(tpValues._2);
tpAdditional.getValueFactory().setValue(tpValues._3);
final String tp = weapon.getTp();
tpStamina.setSelected(tp.contains("A"));
tpWound.setSelected(tp.contains("*"));
final Tuple5<Integer, Integer, Integer, Integer, Integer> distances = weapon.getDistanceRaw();
distanceVeryClose.getValueFactory().setValue(distances._1);
distanceClose.getValueFactory().setValue(distances._2);
distanceMedium.getValueFactory().setValue(distances._3);
distanceFar.getValueFactory().setValue(distances._4);
distanceVeryFar.getValueFactory().setValue(distances._5);
final Tuple5<Integer, Integer, Integer, Integer, Integer> distanceTp = weapon.getDistancetpRaw();
distanceTPVeryClose.getValueFactory().setValue(distanceTp._1);
distanceTPClose.getValueFactory().setValue(distanceTp._2);
distanceTPMedium.getValueFactory().setValue(distanceTp._3);
distanceTPFar.getValueFactory().setValue(distanceTp._4);
distanceTPVeryFar.getValueFactory().setValue(distanceTp._5);
weight.getValueFactory().setValue((int) weapon.getWeight());
bulletType.setItems(FXCollections.observableArrayList("Pfeile", "Bolzen"));
final String ammunitionType = weapon.getAmmunitionType();
noBullet.setSelected(ammunitionType != null);
if (ammunitionType == null) {
bulletType.setDisable(true);
} else {
bulletType.setValue(ammunitionType);
}
final double bulletWeight = weapon.getBulletweight();
noBulletweight.setSelected(bulletWeight != Double.NEGATIVE_INFINITY);
if (bulletWeight == Double.NEGATIVE_INFINITY) {
weightBullet.setDisable(true);
} else {
weightBullet.getValueFactory().setValue((int) bulletWeight);
}
load.getValueFactory().setValue(weapon.getLoad());
notes.setText(weapon.getNotes());
bulletType.disableProperty().bind(noBullet.selectedProperty().not());
weightBullet.disableProperty().bind(noBulletweight.selectedProperty().not());
okButton.setOnAction(event -> {
weapon.setName(name.getText());
weapon.setItemType(type.getText());
weapon.setTalents(talents.getCheckModel().getCheckedItems());
weapon.setTp(tpTypeDice.getValue(), tpNumDice.getValue(), tpAdditional.getValue(), tpWound.isSelected(), tpStamina.isSelected());
weapon.setDistances(distanceVeryClose.getValue(), distanceClose.getValue(), distanceMedium.getValue(), distanceFar.getValue(),
distanceVeryFar.getValue());
weapon.setDistanceTPs(distanceTPVeryClose.getValue(), distanceTPClose.getValue(), distanceTPMedium.getValue(), distanceTPFar.getValue(),
distanceTPVeryFar.getValue());
weapon.setWeight(weight.getValue());
weapon.setAmmunitionType(noBullet.isSelected() ? bulletType.getValue() : null);
weapon.setBulletweight(noBulletweight.isSelected() ? weightBullet.getValue() : Double.NEGATIVE_INFINITY);
weapon.setLoad(load.getValue());
weapon.setNotes(notes.getText());
stage.close();
});
cancelButton.setOnAction(event -> stage.close());
stage.show();
}
}
|
package fr.lteconsulting;
public interface IObservableRegistration
{
void unregister();
}
|
package com.spring.domain;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* @author Naresh.P
*
*/
@Entity
@Table(name="pg_config_variable")
public class PgConfigVariable implements Serializable{
private static final long serialVersionUID = 6761810604108216966L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private long id;
private String merchantid;
private String submerchantid;
private String code;
private String value;
private String description;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getMerchantid() {
return merchantid;
}
public void setMerchantid(String merchantid) {
this.merchantid = merchantid;
}
public String getSubmerchantid() {
return submerchantid;
}
public void setSubmerchantid(String submerchantid) {
this.submerchantid = submerchantid;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
|
package cn.yami.wechat.demo.dto;
import java.util.Date;
public class SpikeShops {
private Long id;
private Long shopId;
private Integer stockCount;
private Date startDate;
private Date endDate;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getShopId() {
return shopId;
}
public void setShopId(Long shopId) {
this.shopId = shopId;
}
public Integer getStockCount() {
return stockCount;
}
public void setStockCount(Integer stockCount) {
this.stockCount = stockCount;
}
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
}
|
package Learn;
public class multipleArguments {
static int sum(int ...z){
System.out.println(z);
for(int i:z){
System.out.println(i);
}
return 0;
}
public static void main(String[] args) {
sum(1,2,3,4,5,7);
}
}
|
package english.pos;
import java.util.HashMap;
import java.util.Map;
public final class ETag {
public final static String[] PENN_TAG_STRINGS = {
"-NONE-",
"NN",
"JJ",
"NP",
"RRB",
"WRB",
"LS",
"PRP",
"DT",
"NNP",
"FW",
"NNS",
"JJS",
"JJR",
"UH",
"MD",
"VBD",
"WP",
"VBG",
"SO",
"CC",
"CD",
"PDT",
"RBS",
"VBN",
"RBR",
"#",
"$",
"IN",
"VBP",
"WDT",
"SYM",
"SBAR",
"NNPS",
"WP$",
",",
"VB",
".",
"VBZ",
"RB",
"AS",
"PRP$",
"EX",
"POS",
":",
"TO",
";",
"LRB",
"RP"
};
public final static Map<String, Integer> PENN_TAG_MAP = new HashMap<String, Integer>();
static {
PENN_TAG_MAP.put("-NONE-", new Integer(0));
PENN_TAG_MAP.put("NN", new Integer(1));
PENN_TAG_MAP.put("JJ", new Integer(2));
PENN_TAG_MAP.put("NP", new Integer(3));
PENN_TAG_MAP.put("RRB", new Integer(4));
PENN_TAG_MAP.put("WRB", new Integer(5));
PENN_TAG_MAP.put("LS", new Integer(6));
PENN_TAG_MAP.put("PRP", new Integer(7));
PENN_TAG_MAP.put("DT", new Integer(8));
PENN_TAG_MAP.put("NNP", new Integer(9));
PENN_TAG_MAP.put("FW", new Integer(10));
PENN_TAG_MAP.put("NNS", new Integer(11));
PENN_TAG_MAP.put("JJS", new Integer(12));
PENN_TAG_MAP.put("JJR", new Integer(13));
PENN_TAG_MAP.put("UH", new Integer(14));
PENN_TAG_MAP.put("MD", new Integer(15));
PENN_TAG_MAP.put("VBD", new Integer(16));
PENN_TAG_MAP.put("WP", new Integer(17));
PENN_TAG_MAP.put("VBG", new Integer(18));
PENN_TAG_MAP.put("SO", new Integer(19));
PENN_TAG_MAP.put("CC", new Integer(20));
PENN_TAG_MAP.put("CD", new Integer(21));
PENN_TAG_MAP.put("PDT", new Integer(22));
PENN_TAG_MAP.put("RBS", new Integer(23));
PENN_TAG_MAP.put("VBN", new Integer(24));
PENN_TAG_MAP.put("RBR", new Integer(25));
PENN_TAG_MAP.put("#", new Integer(26));
PENN_TAG_MAP.put("$", new Integer(27));
PENN_TAG_MAP.put("IN", new Integer(28));
PENN_TAG_MAP.put("VBP", new Integer(29));
PENN_TAG_MAP.put("WDT", new Integer(30));
PENN_TAG_MAP.put("SYM", new Integer(31));
PENN_TAG_MAP.put("SBAR", new Integer(32));
PENN_TAG_MAP.put("NNPS", new Integer(33));
PENN_TAG_MAP.put("WP$", new Integer(34));
PENN_TAG_MAP.put(",", new Integer(35));
PENN_TAG_MAP.put("VB", new Integer(36));
PENN_TAG_MAP.put(".", new Integer(37));
PENN_TAG_MAP.put("VBZ", new Integer(38));
PENN_TAG_MAP.put("RB", new Integer(39));
PENN_TAG_MAP.put("AS", new Integer(40));
PENN_TAG_MAP.put("PRP$", new Integer(41));
PENN_TAG_MAP.put("EX", new Integer(42));
PENN_TAG_MAP.put("POS", new Integer(43));
PENN_TAG_MAP.put(":", new Integer(44));
PENN_TAG_MAP.put("TO", new Integer(45));
PENN_TAG_MAP.put(";", new Integer(46));
PENN_TAG_MAP.put("LRB", new Integer(47));
PENN_TAG_MAP.put("RP", new Integer(48));
}
public final static int PENN_TAG_NONE = 0;
public final static int PENN_TAG_COUNT = 49;
public final static int PENN_TAG_FIRST = 1;
public final static int PENN_TAG_COUNT_BITS = 6;
public static final int NONE = PENN_TAG_NONE;
public static final int COUNT = PENN_TAG_COUNT;
public static final int MAX_COUNT = PENN_TAG_COUNT;
public static final int SIZE = PENN_TAG_COUNT_BITS;
public static final int FIRST = PENN_TAG_FIRST;
public static final int LAST = PENN_TAG_COUNT - 1;
protected int m_code; // unsigned
public ETag() {
m_code = NONE;
}
public ETag(int t) {
m_code = t;
}
public ETag(final ETag t) {
m_code = t.m_code;
}
public ETag(final String s) {
load(s);
}
@Override
public int hashCode() {
return m_code;
}
@Override
public boolean equals(final Object t) {
return m_code == ((ETag)t).m_code;
}
@Override
public String toString() {
return PENN_TAG_STRINGS[m_code];
}
public void load(final int i) {
m_code = i;
}
public void load(String s) {
Integer i = PENN_TAG_MAP.get(s);
m_code = i == null ? PENN_TAG_NONE : i.intValue();
}
public static String str(final int t) {
return PENN_TAG_STRINGS[t];
}
public static int code(final String s) {
Integer i = PENN_TAG_MAP.get(s);
return i == null ? PENN_TAG_NONE : i.intValue();
}
}
|
package classhandling;
public class square {
public double square1(int a,int b){
double x = Math.pow(a,b);
return x;
}
}
|
package DSArraypack;
import java.util.Scanner;
public class TowerOFHanoDemo {
public static void TowerOFHanoi(int n,int src,int dest,int mid)
{
if(n==1)
{
System.out.println("Disks from "+ src+ " +to "+ dest);
}
else
{
TowerOFHanoi(n-1,src,dest,mid);
System.out.println("Disk are:"+n+" from " +src+" to "+dest);
TowerOFHanoi(n-1,mid,src,dest);
}
}
public static void main(String []args)
{
Scanner sc=new Scanner(System.in);
int disk=sc.nextInt();
TowerOFHanoi(disk,5,7,6);
}
}
|
package org.maven.ide.eclipse.io;
import java.io.File;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import junit.framework.TestSuite;
import org.sonatype.tests.http.runner.junit.Junit3SuiteConfiguration;
import org.sonatype.tests.http.runner.annotations.Configurators;
import org.sonatype.tests.http.server.jetty.configurations.BasicAuthSslSuiteConfigurator;
import org.sonatype.tests.http.server.jetty.configurations.BasicAuthSuiteConfigurator;
import org.sonatype.tests.http.server.jetty.configurations.DigestAuthSslSuiteConfigurator;
import org.sonatype.tests.http.server.jetty.configurations.DigestAuthSuiteConfigurator;
// resource loading does not work properly for plugin tests
// @ConfiguratorList( "resources/S2IOFacadeAuthTestConfigurators.list" )
@Configurators( { BasicAuthSuiteConfigurator.class, DigestAuthSuiteConfigurator.class,
BasicAuthSslSuiteConfigurator.class, DigestAuthSslSuiteConfigurator.class } )
public class S2IOFacadeAuthTest
extends AbstractIOTest
{
private static String VALID_USERNAME = "user";
private static String PASSWORD = "password";
public void testDeleteRequest_ValidUser()
throws Exception
{
URI address = URI.create( server.getHttpUrl() + SECURE_FILE );
addRealmAndURL( "testDeleteRequest_ValidUser", address.toString(), VALID_USERNAME, PASSWORD );
ServerResponse resp = S2IOFacade.delete( address.toString(), null, monitor, "Monitor name" );
assertEquals( "Unexpected HTTP status code", HttpURLConnection.HTTP_OK, resp.getStatusCode() );
assertRequest( "Unexpected recorded request", "DELETE", address.toString() );
}
public void testDeleteRequest_ValidUser_NotFound()
throws Exception
{
URI address = URI.create( server.getHttpUrl() + "/secured/missingFile.txt" );
addRealmAndURL( "testDeleteRequest_ValidUser_NotFound", address.toString(), VALID_USERNAME, PASSWORD );
try
{
S2IOFacade.delete( address.toString(), null, monitor, "Monitor name" );
fail( "NotFoundException should have been thrown" );
}
catch ( NotFoundException e )
{
assertRequest( "Unexpected recorded request", "DELETE", address.toString() );
}
}
public void testExists_ValidUser()
throws Exception
{
URI address = URI.create( server.getHttpUrl() + FILE_PATH );
addRealmAndURL( "testExists_ValidUser", address.toString(), VALID_USERNAME, PASSWORD );
assertTrue( S2IOFacade.exists( address.toString(), monitor ) );
}
public void testExists_ValidUser_NotFound()
throws Exception
{
URI address = URI.create( server.getHttpUrl() + NEW_FILE );
addRealmAndURL( "testExists_ValidUser_NotFound", address.toString(), VALID_USERNAME, PASSWORD );
assertFalse( S2IOFacade.exists( address.toString(), monitor ) );
}
/*
* There seems to be an bug with the Jetty server & a head request with an invalid username/password combo on a
* protected resource.
*/
public void testHeadRequest_InvalidUser()
throws Exception
{
String url = server.getHttpUrl() + SECURE_FILE;
addRealmAndURL( "testHeadRequest_InvalidUser", url, "invalidusername", "invalidpassword" );
ServerResponse resp = S2IOFacade.head( url, null, monitor );
assertEquals( "Unexpected HTTP status code", HttpURLConnection.HTTP_UNAUTHORIZED, resp.getStatusCode() );
}
public void testHeadRequest_ValidUser()
throws Exception
{
URI address = URI.create( server.getHttpUrl() + SECURE_FILE );
addRealmAndURL( "testHeadRequest_ValidUser", address.toString(), VALID_USERNAME, PASSWORD );
ServerResponse resp = S2IOFacade.head( address.toString(), null, monitor );
assertEquals( "Unexpected HTTP status code", HttpURLConnection.HTTP_OK, resp.getStatusCode() );
assertRequest( "Unexpected recorded request", "HEAD", address.toString() );
}
public void testHeadRequest_ValidUser_NotFound()
throws Exception
{
URI address = URI.create( server.getHttpUrl() + "/secured/missingFile.txt" );
addRealmAndURL( "testHeadRequest_ValidUser_NotFound", address.toString(), VALID_USERNAME, PASSWORD );
ServerResponse resp = S2IOFacade.head( address.toString(), null, monitor );
assertEquals( "Unexpected HTTP status code", HttpURLConnection.HTTP_NOT_FOUND, resp.getStatusCode() );
assertRequest( "Unexpected recorded request", "HEAD", address.toString() );
}
public void testOpenStream_InvalidUser()
throws Exception
{
String url = server.getHttpUrl() + SECURE_FILE;
addRealmAndURL( "testOpenStream_InvalidUser", url, "invalidusername", "invalidpassword" );
try
{
readstream( S2IOFacade.openStream( url, monitor ) );
fail( "An UnauthorizedException should have been thrown" );
}
catch ( UnauthorizedException e )
{
assertTrue( "Missing http status code",
e.getMessage().contains( String.valueOf( HttpURLConnection.HTTP_UNAUTHORIZED ) ) );
}
}
public void testOpenStream_ValidUser()
throws Exception
{
String url = server.getHttpUrl() + SECURE_FILE;
addRealmAndURL( "testOpenStream_ValidUser", url, VALID_USERNAME, PASSWORD );
assertEquals( "Content of stream differs from file",
readstream( new FileInputStream( "resources" + SECURE_FILE ) ),
readstream( S2IOFacade.openStream( url, monitor ) ) );
}
public void testOpenStream_ValidUser_NotFound()
throws Exception
{
String url = server.getHttpUrl() + NEW_FILE;
addRealmAndURL( "testOpenStream_ValidUser_NotFound", url, VALID_USERNAME, PASSWORD );
try
{
readstream( S2IOFacade.openStream( url, monitor ) );
fail( "A NotFoundException should have been thrown" );
}
catch ( NotFoundException expected )
{
}
}
public void testPostRequest_ValidUser()
throws Exception
{
URI address = URI.create( server.getHttpUrl() + SECURED_NEW_FILE );
addRealmAndURL( "testPostRequest_ValidUser", address.toString(), VALID_USERNAME, PASSWORD );
ServerResponse resp =
S2IOFacade.post( new FileRequestEntity( new File( RESOURCES, FILE_LOCAL ) ), address.toString(), null,
monitor, "Monitor name" );
assertEquals( "Unexpected HTTP status code", HttpURLConnection.HTTP_CREATED, resp.getStatusCode() );
assertRequest( "Unexpected recorded request", "POST", address.toString() );
}
public void testPutRequest_ValidUser()
throws Exception
{
URI address = URI.create( server.getHttpUrl() + SECURED_NEW_FILE );
addRealmAndURL( "testPutRequest_ValidUser", address.toString(), VALID_USERNAME, PASSWORD );
ServerResponse resp =
S2IOFacade.put( new FileRequestEntity( new File( RESOURCES, FILE_LOCAL ) ), address.toString(), null,
monitor, "Monitor name" );
assertEquals( "Unexpected HTTP status code", HttpURLConnection.HTTP_CREATED, resp.getStatusCode() );
assertRequest( "Unexpected recorded request", "PUT", address.toString() );
}
public void testPutRequest_InvalidUser()
throws Exception
{
URI address = URI.create( server.getHttpUrl() + SECURED_NEW_FILE );
addRealmAndURL( "testPutRequest_InvalidUser", address.toString(), "invalidusername", "invalidpassword" );
try
{
ServerResponse response = S2IOFacade.put( new FileRequestEntity( new File( RESOURCES, FILE_LOCAL ) ), address.toString(), null,
monitor, "Monitor name" );
assertEquals( 401, response.getStatusCode() );
fail( "An UnauthorizedException should have been thrown" );
}
catch ( UnauthorizedException e )
{
assertTrue( "Missing http status code",
e.getMessage().contains( String.valueOf( HttpURLConnection.HTTP_UNAUTHORIZED ) ) );
}
}
public static TestSuite suite()
throws Exception
{
return Junit3SuiteConfiguration.suite( S2IOFacadeAuthTest.class );
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.lang.math;
import java.io.Serializable;
import org.apache.commons.lang.text.StrBuilder;
/**
* <p><code>NumberRange</code> represents an inclusive range of
* {@link java.lang.Number} objects of the same type.</p>
*
* @author Apache Software Foundation
* @author <a href="mailto:chrise@esha.com">Christopher Elkins</a>
* @since 2.0 (previously in org.apache.commons.lang)
* @version $Id$
*/
public final class NumberRange extends Range implements Serializable {
/**
* Required for serialization support.
*
* @see java.io.Serializable
*/
private static final long serialVersionUID = 71849363892710L;
/**
* The minimum number in this range.
*/
private final Number min;
/**
* The maximum number in this range.
*/
private final Number max;
/**
* Cached output hashCode (class is immutable).
*/
private transient int hashCode = 0;
/**
* Cached output toString (class is immutable).
*/
private transient String toString = null;
/**
* <p>Constructs a new <code>NumberRange</code> using the specified
* number as both the minimum and maximum in this range.</p>
*
* @param num the number to use for this range
* @throws IllegalArgumentException if the number is <code>null</code>
* @throws IllegalArgumentException if the number doesn't implement <code>Comparable</code>
* @throws IllegalArgumentException if the number is <code>Double.NaN</code> or <code>Float.NaN</code>
*/
public NumberRange(Number num) {
if (num == null) {
throw new IllegalArgumentException("The number must not be null");
}
if (num instanceof Comparable == false) {
throw new IllegalArgumentException("The number must implement Comparable");
}
if (num instanceof Double && ((Double) num).isNaN()) {
throw new IllegalArgumentException("The number must not be NaN");
}
if (num instanceof Float && ((Float) num).isNaN()) {
throw new IllegalArgumentException("The number must not be NaN");
}
this.min = num;
this.max = num;
}
/**
* <p>Constructs a new <code>NumberRange</code> with the specified
* minimum and maximum numbers (both inclusive).</p>
*
* <p>The arguments may be passed in the order (min,max) or (max,min). The
* {@link #getMinimumNumber()} and {@link #getMaximumNumber()} methods will return the
* correct value.</p>
*
* <p>This constructor is designed to be used with two <code>Number</code>
* objects of the same type. If two objects of different types are passed in,
* an exception is thrown.</p>
*
* @param num1 first number that defines the edge of the range, inclusive
* @param num2 second number that defines the edge of the range, inclusive
* @throws IllegalArgumentException if either number is <code>null</code>
* @throws IllegalArgumentException if the numbers are of different types
* @throws IllegalArgumentException if the numbers don't implement <code>Comparable</code>
*/
public NumberRange(Number num1, Number num2) {
if (num1 == null || num2 == null) {
throw new IllegalArgumentException("The numbers must not be null");
}
if (num1.getClass() != num2.getClass()) {
throw new IllegalArgumentException("The numbers must be of the same type");
}
if (num1 instanceof Comparable == false) {
throw new IllegalArgumentException("The numbers must implement Comparable");
}
if (num1 instanceof Double) {
if (((Double) num1).isNaN() || ((Double) num2).isNaN()) {
throw new IllegalArgumentException("The number must not be NaN");
}
} else if (num1 instanceof Float) {
if (((Float) num1).isNaN() || ((Float) num2).isNaN()) {
throw new IllegalArgumentException("The number must not be NaN");
}
}
int compare = ((Comparable) num1).compareTo(num2);
if (compare == 0) {
this.min = num1;
this.max = num1;
} else if (compare > 0) {
this.min = num2;
this.max = num1;
} else {
this.min = num1;
this.max = num2;
}
}
// Accessors
//--------------------------------------------------------------------
/**
* <p>Returns the minimum number in this range.</p>
*
* @return the minimum number in this range
*/
public Number getMinimumNumber() {
return min;
}
/**
* <p>Returns the maximum number in this range.</p>
*
* @return the maximum number in this range
*/
public Number getMaximumNumber() {
return max;
}
// Tests
//--------------------------------------------------------------------
/**
* <p>Tests whether the specified <code>number</code> occurs within
* this range.</p>
*
* <p><code>null</code> is handled and returns <code>false</code>.</p>
*
* @param number the number to test, may be <code>null</code>
* @return <code>true</code> if the specified number occurs within this range
* @throws IllegalArgumentException if the number is of a different type to the range
*/
public boolean containsNumber(Number number) {
if (number == null) {
return false;
}
if (number.getClass() != min.getClass()) {
throw new IllegalArgumentException("The number must be of the same type as the range numbers");
}
int compareMin = ((Comparable) min).compareTo(number);
int compareMax = ((Comparable) max).compareTo(number);
return compareMin <= 0 && compareMax >= 0;
}
// Range tests
//--------------------------------------------------------------------
// use Range implementations
// Basics
//--------------------------------------------------------------------
/**
* <p>Compares this range to another object to test if they are equal.</p>.
*
* <p>To be equal, the class, minimum and maximum must be equal.</p>
*
* @param obj the reference object with which to compare
* @return <code>true</code> if this object is equal
*/
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj instanceof NumberRange == false) {
return false;
}
NumberRange range = (NumberRange) obj;
return min.equals(range.min) && max.equals(range.max);
}
/**
* <p>Gets a hashCode for the range.</p>
*
* @return a hash code value for this object
*/
public int hashCode() {
if (hashCode == 0) {
hashCode = 17;
hashCode = 37 * hashCode + getClass().hashCode();
hashCode = 37 * hashCode + min.hashCode();
hashCode = 37 * hashCode + max.hashCode();
}
return hashCode;
}
/**
* <p>Gets the range as a <code>String</code>.</p>
*
* <p>The format of the String is 'Range[<i>min</i>,<i>max</i>]'.</p>
*
* @return the <code>String</code> representation of this range
*/
public String toString() {
if (toString == null) {
StrBuilder buf = new StrBuilder(32);
buf.append("Range[");
buf.append(min);
buf.append(',');
buf.append(max);
buf.append(']');
toString = buf.toString();
}
return toString;
}
}
|
/*
* created 29.03.2006
*
* Copyright 2009, ByteRefinery
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* $Id$
*/
package com.byterefinery.rmbench.database.mysql;
import com.byterefinery.rmbench.external.database.DatabaseInfo;
import com.byterefinery.rmbench.external.database.sql99.SQL99;
import com.byterefinery.rmbench.external.model.IDataType;
public class MySQL extends DatabaseInfo {
private final int MAX_CHAR_LENGTH = 255;
private final int MAX_VARCHAR_LENGTH = 65535;
private final MySQLListDatatype enumDataType = new MySQLEnumDataType();
private final MySQLListDatatype setDataType = new MySQLSetDataType();
public MySQL() {
// string types
registerDataType("CHAR", MAX_CHAR_LENGTH, true, IDataType.UNSPECIFIED_SIZE, SQL99.CHAR
.getPrimaryName(), 1);
registerDataType("NATIONAL CHAR", MAX_CHAR_LENGTH, true, IDataType.UNSPECIFIED_SIZE,
SQL99.NCHAR.getPrimaryName(), 1);
registerDataType(new String[] { "VARCHAR", "CHARACTER VARYING" }, MAX_VARCHAR_LENGTH, true,
1, SQL99.VARCHAR.getPrimaryName(), 1);
registerDataType("BIT", 64, false, 1, SQL99.BIT.getPrimaryName(), 1);
registerDataType("BINARY", MAX_CHAR_LENGTH, true, IDataType.UNSPECIFIED_SIZE, SQL99.BIT
.getPrimaryName(), 2);
registerDataType("VARBINARY", MAX_VARCHAR_LENGTH, true, 1, SQL99.BIT_VARYING
.getPrimaryName(), 1);
registerDataType("TINYBLOB", SQL99.BLOB.getPrimaryName(), 2);
registerDataType("TINYTEXT", SQL99.CLOB.getPrimaryName(), 2);
registerDataType("BLOB", SQL99.BLOB.getPrimaryName(), 1);
registerDataType("TEXT", SQL99.CLOB.getPrimaryName(), 1);
registerDataType("MEDIUMBLOB", SQL99.BLOB.getPrimaryName(), 1);
registerDataType("MEDIUMTEXT", SQL99.CLOB.getPrimaryName(), 2);
registerDataType("LONGBLOB", SQL99.BLOB.getPrimaryName(), 2);
registerDataType("LONGTEXT", SQL99.BLOB.getPrimaryName(), 2);
// numeric types
registerDataType(new String[] { "BOOLEAN", "BOOL" }, IDataType.UNLIMITED_SIZE, false,
IDataType.UNSPECIFIED_SIZE, SQL99.SMALLINT.getPrimaryName(), 2);
registerDataType(new MySQLIntegerDataType("TINYINT", 4), SQL99.SMALLINT
.getPrimaryName(), 2);
registerDataType(new MySQLIntegerDataType("SMALLINT", 6), SQL99.SMALLINT
.getPrimaryName(), 1);
registerDataType(new MySQLIntegerDataType("MEDIUMINT", 9), SQL99.INTEGER
.getPrimaryName(), 2);
registerDataType(new MySQLIntegerDataType(new String[] { "INT",
"INTEGER" }, (long) 11), SQL99.INTEGER.getPrimaryName(), 1);
// TODO MySQL.INTEGER --> SQL99.BIGINT ... no good idea :(
registerDataType(new MySQLIntegerDataType("BIGINT", 20), SQL99.INTEGER
.getPrimaryName(), 2);
registerDataType("SERIAL", SQL99.INTEGER.getPrimaryName(), 3);
registerDataType(new MySQLDoubleDataType(
new String[] { "FLOAT" },
IDataType.UNLIMITED_SIZE,
false,
IDataType.UNSPECIFIED_SIZE,
IDataType.UNLIMITED_SCALE,
false,
IDataType.UNSPECIFIED_SCALE)
, SQL99.FLOAT.getPrimaryName(), 1);
registerDataType(new MySQLDoubleDataType(
new String[] { "DOUBLE", "DOUBLE PRECISION" },
IDataType.UNLIMITED_SIZE,
false,
IDataType.UNSPECIFIED_SIZE,
IDataType.UNLIMITED_SCALE,
false,
IDataType.UNSPECIFIED_SCALE)
, SQL99.DOUBLE_PRECISION.getPrimaryName(), 1);
registerDataType(new String[] { "DECIMAL", "DEC" }, 65, false,
10, 30, false, 0, SQL99.DECIMAL.getPrimaryName(), 1);
// date & time
registerDataType("DATE", SQL99.DATE.getPrimaryName(), 1);
registerDataType(new String[]{"TIMESTAMP", "DATETIME"}, SQL99.TIMESTAMP.getPrimaryName(), 1);
registerDataType("TIME", SQL99.TIME.getPrimaryName(), 1);
registerDataType(enumDataType, null, 1);
registerDataType(setDataType, null, 1);
}
public IDataType getDataType(int typeID, String typeName, long size, int scale) {
IDataType dataType;
// handle the unsigned flag
String[] fragments = typeName.split(" ", 2);
if ((fragments.length >= 2) && fragments[1].equalsIgnoreCase("unsigned"))
dataType = getDataType(fragments[0]);
else
dataType = getDataType(typeName);
if (dataType != null) {
if (dataType.acceptsScale())
dataType.setScale(scale);
if (dataType.acceptsSize())
dataType.setSize(size);
}
return dataType;
}
}
|
package com.herbert.service;
import com.herbert.domain.Student;
/**
* @author Herbert
* @create 2019-06-11 15:58
*/
public interface StudentService {
Integer addStudent(Student student);
}
|
package com.learn.learn.设计模式.模版方法模式;
/**
* @Author: LL
* @Description: 一次性实现一个算法的不变的部分,并将可变的行为留给子类来实现;
* @Date:Create:in 2020/12/22 17:03
*/
class Template {
public static void main(String[] args) {
ConcreteClass_Baocai baocai = new ConcreteClass_Baocai();
baocai.cookProcess();
ConcreteClass_Caixin caixin = new ConcreteClass_Caixin();
caixin.cookProcess();
}
}
|
/**
* Spring Data JPA repositories.
*/
package com.mycompany.jhipsterappv2.repository;
|
class Solution {
void dfs(int[][] g, int i, int j, int dist)
{
if (i < 0 || j < 0 || i >= g.length || j >= g[0].length || (g[i][j] != 0 && g[i][j] <= dist)) return;
g[i][j] = dist;
dfs(g, i - 1, j, dist + 1);
dfs(g, i + 1, j, dist + 1);
dfs(g, i, j - 1, dist + 1);
dfs(g, i, j + 1, dist + 1);
}
int maxDistance(int[][] g) {
int mx = -1;
for (int i = 0; i < g.length; ++i)
for (int j = 0; j < g[i].length; ++j)
if (g[i][j] == 1) {
g[i][j] = 0;
dfs(g, i, j, 1);
}
for (int i = 0; i < g.length; ++i)
for (int j = 0; j < g[i].length; ++j)
if (g[i][j] > 1)
mx = Math.max(mx, g[i][j] - 1);
return mx;
}
}
/*
class Solution {
int x_coord;
int y_coord;
public int maxDistance(int[][] grid) {
int ans = -1;
int row = grid.length;
int col = grid[0].length;
int[][] mem = new int[row][col];
int max = Integer.MIN_VALUE;
int cur;
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
if(grid[i][j] == 0)
{
cur = find(grid, i, j, row, col, mem);
System.out.println("cur max " + cur + max);
if(cur > max) {
max = cur;
ans = Math.abs(i - x_coord) + Math.abs(j - y_coord);
}
}
}
}
if(max == Integer.MIN_VALUE)
{
return -1;
}
return max;
}
int find(int[][] grid, int i, int j, int row, int col, int[][] mem)
{
if(i < 0 || j < 0 || i >= row || j >= col || grid[i][j] == 2)
{
return Integer.MAX_VALUE - 1;
}
if(mem[i][j] != 0)
{
return mem[i][j];
}
if(grid[i][j] == 1)
{
return 0;
}
grid[i][j] = 2;
int max = Integer.MAX_VALUE;
int prev = max;
max = Math.min(max, 1+ find(grid, i, j+1, row, col, mem));
prev = max;
x_coord = i;
y_coord = j + 1;
max = Math.min(max, 1 + find(grid, i, j-1, row, col, mem));
if(prev != max)
{
prev = max;
x_coord = i;
y_coord = j - 1;
}
max = Math.min(max, 1 + find(grid, i+1, j, row, col, mem));
if(prev != max)
{
prev = max;
x_coord = i+1;
y_coord = j;
}
max = Math.min(max, 1 + find(grid, i-1, j, row, col, mem));
if(prev != max)
{
prev = max;
x_coord = i - 1;
y_coord = j;
}
max = Math.min(max, 1 + find(grid, i+1, j+1, row, col, mem));
if(prev != max)
{
prev = max;
x_coord = i + 1;
y_coord = j + 1;
}
max = Math.min(max, 1 + find(grid, i-1, j-1, row, col, mem));
if(prev != max)
{
prev = max;
x_coord = i - 1;
y_coord = j - 1;
}
max = Math.min(max, 1 + find(grid, i-1, j+1, row, col, mem));
if(prev != max)
{
prev = max;
x_coord = i - 1;
y_coord = j + 1;
}
max = Math.min(max, 1 + find(grid, i+1, j-1, row, col, mem));
if(prev != max)
{
prev = max;
x_coord = i + 1;
y_coord = j - 1;
}
grid[i][j] = 0;
mem[i][j] = max;
return max;
}
}
*/
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.openwebbeans.junit5.reusable;
import org.apache.openwebbeans.junit5.Cdi;
import org.junit.jupiter.api.Test;
import java.io.Closeable;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
@Cdi(disableDiscovery = true, onStarts = CdiWithOnStartTest.MyOnStart.class)
class CdiWithOnStartTest {
@Test
void run() {
assertTrue(MyOnStart.started.get());
}
public static class MyOnStart implements Cdi.OnStart {
private static final AtomicBoolean started = new AtomicBoolean();
@Override
public Closeable get() {
assertFalse(started.get());
started.set(true);
return () -> started.set(false);
}
}
}
|
package com.jiuzhe.app.hotel.module;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
* @Description:获取推荐房的参数
*/
@ApiModel(value = "RecommetQuery", description = "RecommetQuery")
public class RecommetQuery {
@ApiModelProperty(value = "城市名", example = "武汉市")
private String cityName;
@ApiModelProperty(value = "区域名", example = "洪山区")
private String area;
@ApiModelProperty(value = "需要多少条数据", example = "10")
private Integer num;
@ApiModelProperty(value = "评分依据", example = "0:weight;1:score")
private Integer gist;
public Integer getGist() {
return gist;
}
public void setGist(Integer gist) {
this.gist = gist;
}
public Integer getNum() {
return num;
}
public void setNum(Integer num) {
this.num = num;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public String getArea() {
return area;
}
public void setArea(String area) {
this.area = area;
}
}
|
package com.design.factory.func;
/**
* 工厂方法
* 特点:
* 1、符合实际,Audi、Bmw、Benz都拥有自己的工厂,直接向抽象工厂Factory索要就行
* 2、可以一定程度增加扩展性,若增加一个产品实现,只需要实现产品接口,修改工厂创建产品的方法,
* 消费者可以无感知(若消费者不关心具体产品是什么的情况)
*/
public class FactoryTest {
public static void main(String[] args) {
Factory factory = new AudiFactory();
System.out.println(factory.getCar());
}
}
|
package com.serkowski.bookings.services.availability;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.annotation.Validated;
import javax.validation.constraints.NotNull;
@Configuration
@ConfigurationProperties(prefix="bookings")
@Data
@Validated
public class AvailabilityConfigurationProperties {
@NotNull
private String externalServiceHost;
}
|
package cn.izouxiang.common.domain;
import org.apache.commons.lang.StringUtils;
import java.io.Serializable;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import cn.izouxiang.common.constant.Constant;
public class PageQuery implements Serializable{
private static final long serialVersionUID = -3443420658093242132L;
private Integer pageNumber;
private Integer pageSize;
private List<Query> queries;
private Map<String,Integer> orders;
private Map<String,Boolean> fields;
public PageQuery() {
pageSize = Integer.MAX_VALUE;
pageNumber = 1;
}
public PageQuery(Integer pageNumber, Integer pageSize) {
this.pageNumber = pageNumber;
this.pageSize = pageSize;
}
public void addOrder(String fieldName){
this.addOrder(fieldName,Constant.ORDER_DESC);
}
public void addOrder(String fieldName, Integer order){
if(this.orders == null){
this.orders = new LinkedHashMap<>();
}
this.orders.put(fieldName,order);
}
public void includeField(String fieldName){
addField(fieldName,true);
}
public void excludeField(String fieldName){
addField(fieldName,false);
}
public void addField(String fieldName, boolean show){
if(this.fields == null){
this.fields = new LinkedHashMap<>();
}
this.fields.put(fieldName,show);
}
public Map<String, Boolean> getFields() {
return fields;
}
public void addQuery(String fieldName, Object fieldValue){
this.addQuery(fieldName,fieldValue,Constant.EQUALS_SEARCH);
}
public void addQuery(String fieldName,Object fieldValue,int searchType){
if(this.queries == null){
queries = new LinkedList<>();
}
this.addQuery(new Query(fieldName,fieldValue,searchType));
}
public void addQuery(Query query){
this.queries.add(query);
}
public List<Query> getQueries() {
return queries;
}
public void setQueries(List<Query> queries) {
this.queries = queries;
}
public Map<String, Integer> getOrders() {
return orders;
}
public void setOrders(Map<String, Integer> orders) {
this.orders = orders;
}
public Integer getPageNumber() {
return pageNumber;
}
public void setPageNumber(Integer pageNumber) {
this.pageNumber = pageNumber;
}
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public static class Query implements Serializable{
private static final long serialVersionUID = 5297978978063023449L;
public String fieldName;
public Object fieldValue;
public int searchType;
public Query() {
}
public Query(String fieldName, Object fieldValue) {
this(fieldName,fieldValue,Constant.EQUALS_SEARCH);
}
public Query(String fieldName, Object fieldValue, int searchType) {
if(StringUtils.isBlank(fieldName) || Objects.isNull(fieldValue)){
throw new NullPointerException("Null fieldName and fieldValue are not allowed.\n");
}
this.fieldName = fieldName;
this.fieldValue = fieldValue;
this.searchType = searchType;
}
}
}
|
import java.util.ArrayList;
import java.util.HashMap;
/**
* app
*/
public class app {
public static ArrayList<Integer> findFactors(int num) {
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = num; i >= 1; i--) {
if (num % i == 0) {
list.add(i);
}
}
return list;
}
public static HashMap<Integer, Integer> assembleTable(ArrayList<Integer> list) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
int length = 0;
for (int var : list) {
length++;
}
int numOfPairs = length / 2;
for (int i = 1; i <= numOfPairs; i++) {
int item1 = list.get(list.size() - 1);
int item2 = list.get(0);
map.put(item1, item2);
list.remove(0);
list.remove(length - 2);
length -= 2;
}
return map;
}
public static ArrayList<Integer> findRightFactorSet(int aVal, int bVal, int cVal) {
ArrayList<Integer> awns = new ArrayList<Integer>();
ArrayList<Integer> factors = findFactors(cVal);
HashMap<Integer, Integer> map = assembleTable(factors);
ArrayList<Integer> keys = new ArrayList<Integer>();
ArrayList<Integer> values = new ArrayList<Integer>();
int targetProduct = aVal * cVal;
ArrayList<Integer> factors2 = findFactors(targetProduct);
HashMap<Integer, Integer> map2 = assembleTable(factors2);
ArrayList<Integer> keys2 = new ArrayList<Integer>();
ArrayList<Integer> values2 = new ArrayList<Integer>();
for (int i : map.keySet()) {
keys.add(i);
}
for (int i : map.values()) {
values.add(i);
}
for (int i : map2.keySet()) {
keys2.add(i);
}
for (int i : map2.values()) {
values2.add(i);
}
if (aVal == 1) {
for (int i = 0; i <= keys.size() - 1; i++) {
if ((keys.get(i) + values.get(i) == bVal) && (keys.get(i) * values.get(i) == cVal)) {
awns.add(keys.get(i));
awns.add(values.get(i));
}
}
} else if (aVal > 1) {
for (int i = 0; i <= keys2.size() - 1; i++) {
if ((keys2.get(i) + values2.get(i) == bVal) && (keys2.get(i) * values2.get(i) == targetProduct)) {
awns.add(keys2.get(i));
awns.add(values2.get(i));
}
}
}
return awns;
}
public static void main(String[] args) {
System.out.println(findRightFactorSet(1, 15, 56));
System.out.println(findRightFactorSet(1, 9, 14));
System.out.println(findRightFactorSet(2, 7, 3));
System.out.println(findRightFactorSet(3, 10, 8));
}
}
|
package Learn;
public class methodOverloading1 {
static int sum(int a, int b, int c){
return a+b+c;
}
static float sum(int a, int b, float c){
return a+b+c *1000;
}
public static void main(String[] args) {
System.out.println(methodOverloading1.sum(1,2, (float) 3));
}
}
|
package searchcodej;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import searchcodej.model.Classe;
import searchcodej.model.Method;
import searchcodej.model.PartOfString;
import searchcodej.model.SourceCodeNode;
import searchcodej.model.SourceCodeTree;
public class CodeTreeSearcher {
private SourceCodeSearcher searcher;
public CodeTreeSearcher() {
super();
this.searcher = new SourceCodeSearcher();
}
public List<PartOfString> searchInClassesOnly(List<SourceCodeTree> trees, List<Pattern> patterns) {
List<PartOfString> result = new ArrayList<PartOfString>();
for (SourceCodeTree sourceCodeTree : trees) {
postOrderWalkClasses(sourceCodeTree.getRootNode(), patterns, result);
}
return result ;
}
private void postOrderWalkClasses(SourceCodeNode currentNode,
final List<Pattern> patterns,
List<PartOfString> result) {
if (currentNode != null) {
//visit children first
for (SourceCodeNode childenNode : currentNode.getChildren()) {
postOrderWalkClasses(childenNode, patterns, result);
}
//visit root node in the end
if (currentNode.getData() instanceof Classe) {
Classe classe = (Classe) currentNode.getData();
//i have to check conflicts before i add the result
List<PartOfString> temp = this.searcher.searchIgnoreConflicts(classe, patterns);
for (PartOfString p : temp) {
if (!p.isThereConflict(result)) {
result.add(p);
}
}
}
}
}
public List<PartOfString> searchInMethodsOnly(List<SourceCodeTree> trees, List<Pattern> patterns) {
List<PartOfString> result = new ArrayList<PartOfString>();
for (SourceCodeTree sourceCodeTree : trees) {
result.addAll(postOrderWalkMethods(sourceCodeTree.getRootNode(), patterns));
}
return result;
}
private List<PartOfString> postOrderWalkMethods(SourceCodeNode rootNode, List<Pattern> patterns) {
List<PartOfString> result = new ArrayList<PartOfString>();
if (rootNode != null) {
//visit children first
for (SourceCodeNode childenNode : rootNode.getChildren()) {
result.addAll(postOrderWalkMethods(childenNode, patterns));
}
//visit root node in the end
if (rootNode.getData() instanceof Method) {
Method method = (Method) rootNode.getData();
result.addAll(this.searcher.searchIgnoreConflicts(method, patterns));
}
}
return result;
}
}
|
package com.sanyue.siqing.home;
import com.sanyue.siqing.Base.BaseMode;
import com.sanyue.siqing.Network.APIInterface;
import com.sanyue.siqing.Network.BaseObserver;
import com.sanyue.siqing.Network.HttpUtils;
import com.sanyue.siqing.bean.SelectSpecial;
import com.sanyue.siqing.bean.UserBean;
public class HomeMode extends BaseMode<HomePresnter,HomeContract.M> {
public HomeMode(HomePresnter homePresnter) {
super(homePresnter);
}
@Override
public HomeContract.M getConntract() {
return new HomeContract.M() {
@Override
public void home() {
// p.getContract().result(new UserBean("张三","18"));
// HttpUtils
// .getApiService(APIInterface.class)
// .selectSpecial()
// .compose(HttpUtils.applySchedulers())
// .subscribe(new BaseObserver<SelectSpecial>(getView().getDisposable(),getView(),null) {
// @Override
// protected void success(SelectSpecial e) {
// result(e);
// }
// });
}
};
}
}
|
package com.meridal.examples.springbootmysql.domain;
import static org.junit.jupiter.api.Assertions.*;
import com.meridal.examples.springbootmysql.test.TestFramework;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
public class RecordingTest extends TestFramework {
private static final String ID = "1234";
private static final String OTHER_ID = "5678";
@Test
public void testEqualsAndHashCodeWithSameID() {
final Recording recording = this.randomRecording(ID);
final Recording other = this.cloneRecording(ID, recording);
assertEquals(recording, other);
assertEquals(recording.hashCode(), other.hashCode());
}
@Test
public void testEqualsAndHashCodeWithDifferentID() {
final Recording recording = this.randomRecording(ID);
final Recording other = this.cloneRecording(OTHER_ID, recording);
assertNotEquals(recording, other);
assertNotEquals(recording.hashCode(), other.hashCode());
}
@Test
public void testEqualsAndHashCodeWithNullID() {
final Recording recording = this.randomRecording();
final Recording other = this.cloneRecording(ID, recording);
assertNotEquals(recording, other);
assertNotEquals(recording.hashCode(), other.hashCode());
}
@Test
public void testEqualsAndHashCodeWithBothIDsNull() {
final Recording recording = this.randomRecording();
final Recording other = this.cloneRecording(null, recording);
assertNotEquals(recording, other);
assertEquals(recording.hashCode(), other.hashCode());
}
@Test
public void testEqualsWithAnotherType() {
final Recording recording = this.randomRecording();
final List<Integer> other = new ArrayList<>();
assertFalse(recording.equals(other));
}
@Test
public void testEqualsWithNull() {
final Recording recording = this.randomRecording();
assertFalse(recording.equals(null));
}
}
|
package br.com.opensig.comercial.server.acao;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import br.com.opensig.comercial.client.servico.ComercialException;
import br.com.opensig.comercial.shared.modelo.ComVenda;
import br.com.opensig.comercial.shared.modelo.ComVendaProduto;
import br.com.opensig.core.client.controlador.filtro.ECompara;
import br.com.opensig.core.client.controlador.filtro.EJuncao;
import br.com.opensig.core.client.controlador.filtro.FiltroNumero;
import br.com.opensig.core.client.controlador.filtro.FiltroObjeto;
import br.com.opensig.core.client.controlador.filtro.GrupoFiltro;
import br.com.opensig.core.client.controlador.filtro.IFiltro;
import br.com.opensig.core.client.controlador.parametro.ParametroFormula;
import br.com.opensig.core.client.padroes.Chain;
import br.com.opensig.core.client.servico.OpenSigException;
import br.com.opensig.core.server.Conexao;
import br.com.opensig.core.server.CoreServiceImpl;
import br.com.opensig.core.server.UtilServer;
import br.com.opensig.core.shared.modelo.Autenticacao;
import br.com.opensig.core.shared.modelo.EComando;
import br.com.opensig.core.shared.modelo.Sql;
import br.com.opensig.financeiro.shared.modelo.FinConta;
import br.com.opensig.financeiro.shared.modelo.FinReceber;
import br.com.opensig.financeiro.shared.modelo.FinRecebimento;
import br.com.opensig.fiscal.server.acao.GerarNfeCanceladaSaida;
import br.com.opensig.fiscal.server.acao.GerarNfeInutilizadaSaida;
import br.com.opensig.fiscal.shared.modelo.ENotaStatus;
import br.com.opensig.fiscal.shared.modelo.FisNotaSaida;
import br.com.opensig.produto.shared.modelo.ProdEmbalagem;
import br.com.opensig.produto.shared.modelo.ProdEstoque;
public class CancelarVenda extends Chain {
private CoreServiceImpl servico;
private ComVenda venda;
private Autenticacao auth;
public CancelarVenda(Chain next, CoreServiceImpl servico, ComVenda venda, Autenticacao auth) throws OpenSigException {
super(null);
this.servico = servico;
this.venda = venda;
this.auth = auth;
FiltroNumero fn = new FiltroNumero("fisNotaSaidaId", ECompara.IGUAL, venda.getFisNotaSaida().getId());
FisNotaSaida saida = (FisNotaSaida) servico.selecionar(venda.getFisNotaSaida(), fn, false);
// atualiza venda
AtualizarVenda atuVenda = new AtualizarVenda(next);
if (saida != null) {
if (saida.getFisNotaStatus().getFisNotaStatusId() == ENotaStatus.AUTORIZADO.getId()) {
// valida se a data da nota ainda pode ser cancelada
int dias = Integer.valueOf(auth.getConf().get("nfe.tempo_cancela"));
Calendar cal = Calendar.getInstance();
cal.setTime(saida.getFisNotaSaidaData());
cal.add(Calendar.DATE, dias);
Date hoje = new Date();
if (hoje.compareTo(cal.getTime()) > 0) {
throw new OpenSigException("Data limite para cancelamento desta NFe era " + UtilServer.formataData(cal.getTime(), "dd/MM/yyyy"));
}
// cancela nota
GerarNfeCanceladaSaida canNota = new GerarNfeCanceladaSaida(next, servico, saida, venda.getComVendaObservacao(), auth);
atuVenda.setNext(canNota);
} else {
// inutiliza nota
int num = venda.getFisNotaSaida().getFisNotaSaidaNumero();
GerarNfeInutilizadaSaida inuNota = new GerarNfeInutilizadaSaida(next, servico, saida, venda.getComVendaObservacao(), num, num, auth);
atuVenda.setNext(inuNota);
}
}
// atualiza os conta
AtualizarConta atuConta = new AtualizarConta(atuVenda);
// valida o estoque
AtualizarEstoque atuEst = new AtualizarEstoque(atuConta);
if (auth.getConf().get("estoque.ativo").equalsIgnoreCase("sim")) {
this.setNext(atuEst);
} else {
this.setNext(atuConta);
}
}
@Override
public void execute() throws OpenSigException {
// seta a venda
FiltroNumero fn = new FiltroNumero("comVendaId", ECompara.IGUAL, venda.getId());
String motivo = venda.getComVendaObservacao();
venda = (ComVenda) servico.selecionar(venda, fn, false);
venda.setComVendaObservacao(motivo);
if (next != null) {
next.execute();
}
}
private class AtualizarEstoque extends Chain {
private List<ProdEmbalagem> embalagens;
public AtualizarEstoque(Chain next) throws OpenSigException {
super(next);
}
@Override
public void execute() throws OpenSigException {
EntityManagerFactory emf = null;
EntityManager em = null;
try {
// recupera uma instância do gerenciador de entidades
FiltroObjeto fo1 = new FiltroObjeto("empEmpresa", ECompara.IGUAL, venda.getEmpEmpresa());
emf = Conexao.getInstancia(new ProdEstoque().getPu());
em = emf.createEntityManager();
em.getTransaction().begin();
if (auth.getConf().get("estoque.ativo").equalsIgnoreCase("sim")) {
for (ComVendaProduto comVen : venda.getComVendaProdutos()) {
// fatorando a quantida no estoque
double qtd = comVen.getComVendaProdutoQuantidade();
if (comVen.getProdEmbalagem().getProdEmbalagemId() != comVen.getProdProduto().getProdEmbalagem().getProdEmbalagemId()) {
qtd *= getQtdEmbalagem(comVen.getProdEmbalagem().getProdEmbalagemId());
qtd /= getQtdEmbalagem(comVen.getProdProduto().getProdEmbalagem().getProdEmbalagemId());
}
// formando os parametros
ParametroFormula pn1 = new ParametroFormula("prodEstoqueQuantidade", qtd);
// formando o filtro
FiltroObjeto fo2 = new FiltroObjeto("prodProduto", ECompara.IGUAL, comVen.getProdProduto());
GrupoFiltro gf = new GrupoFiltro(EJuncao.E, new IFiltro[] { fo1, fo2 });
// busca o item
ProdEstoque est = new ProdEstoque();
// formando o sql
Sql sql = new Sql(est, EComando.ATUALIZAR, gf, pn1);
servico.executar(em, sql);
}
}
if (next != null) {
next.execute();
}
em.getTransaction().commit();
} catch (Exception ex) {
if (em != null && em.getTransaction().isActive()) {
em.getTransaction().rollback();
}
UtilServer.LOG.error("Erro ao atualizar o estoque.", ex);
throw new ComercialException(ex.getMessage());
} finally {
em.close();
emf.close();
}
}
private int getQtdEmbalagem(int embalagemId) throws Exception {
int unid = 1;
if (embalagens == null) {
embalagens = servico.selecionar(new ProdEmbalagem(), 0, 0, null, false).getLista();
}
for (ProdEmbalagem emb : embalagens) {
if (emb.getProdEmbalagemId() == embalagemId) {
unid = emb.getProdEmbalagemUnidade();
break;
}
}
return unid;
}
}
private class AtualizarConta extends Chain {
public AtualizarConta(Chain next) throws OpenSigException {
super(next);
}
@Override
public void execute() throws OpenSigException {
EntityManagerFactory emf = null;
EntityManager em = null;
try {
// recupera uma instância do gerenciador de entidades
FinConta conta = new FinConta();
emf = Conexao.getInstancia(conta.getPu());
em = emf.createEntityManager();
em.getTransaction().begin();
if (venda.getFinReceber() != null) {
conta = venda.getFinReceber().getFinConta();
double valPag = 0.00;
for (FinRecebimento rec : venda.getFinReceber().getFinRecebimentos()) {
if (!rec.getFinRecebimentoStatus().equalsIgnoreCase(auth.getConf().get("txtAberto"))) {
valPag += rec.getFinRecebimentoValor();
}
}
if (valPag > 0) {
conta.setFinContaSaldo(conta.getFinContaSaldo() - valPag);
servico.salvar(em, conta);
}
}
if (next != null) {
next.execute();
}
em.getTransaction().commit();
} catch (Exception ex) {
if (em != null && em.getTransaction().isActive()) {
em.getTransaction().rollback();
}
UtilServer.LOG.error("Erro ao atualizar a conta.", ex);
throw new ComercialException(ex.getMessage());
} finally {
em.close();
emf.close();
}
}
}
private class AtualizarVenda extends Chain {
public AtualizarVenda(Chain next) throws OpenSigException {
super(next);
}
@Override
public void execute() throws OpenSigException {
EntityManagerFactory emf = null;
EntityManager em = null;
try {
// recupera uma instância do gerenciador de entidades
emf = Conexao.getInstancia(venda.getPu());
em = emf.createEntityManager();
em.getTransaction().begin();
FinReceber receber = venda.getFinReceber();
venda.setComVendaCancelada(true);
venda.setFinReceber(null);
servico.salvar(em, venda);
if (next != null) {
next.execute();
}
em.getTransaction().commit();
if (receber != null) {
deletarReceber(receber);
}
} catch (Exception ex) {
if (em != null && em.getTransaction().isActive()) {
em.getTransaction().rollback();
}
UtilServer.LOG.error("Erro ao atualizar a venda.", ex);
throw new ComercialException(ex.getMessage());
} finally {
em.close();
emf.close();
}
}
private void deletarReceber(FinReceber receber) {
EntityManagerFactory emf = null;
EntityManager em = null;
try {
// recupera uma instância do gerenciador de entidades
emf = Conexao.getInstancia(receber.getPu());
em = emf.createEntityManager();
em.getTransaction().begin();
servico.deletar(receber);
} catch (Exception ex) {
UtilServer.LOG.error("Erro ao deletar o receber.", ex);
} finally {
em.close();
emf.close();
}
}
}
}
|
package icu.fordring.voter.controller;
import icu.fordring.voter.beans.ImageBean;
import icu.fordring.voter.beans.User;
import icu.fordring.voter.constant.Constants;
import icu.fordring.voter.constant.State;
import icu.fordring.voter.dao.ImageManager;
import icu.fordring.voter.dao.UserManager;
import icu.fordring.voter.intercepters.VoteChecker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.transaction.Transactional;
import java.util.Map;
import java.util.Optional;
@Controller
@RequestMapping("/vote")
public class VoteController {
@Resource
private ImageManager imageManager;
@Resource
private UserManager userManager;
private Logger logger = LoggerFactory.getLogger(VoteController.class);
@RequestMapping("")
public String votePage(Map map){
map.put("ImageList",imageManager.getList());
return "vote";
}
@RequestMapping("/submit")
public String vote(HttpSession session,String[] voteList){
User user = userManager.refresh((User) session.getAttribute(Constants.USER));
if(voteList==null){
return "redirect:/";
}
for(String s:voteList){
ImageBean imageBean = imageManager.findById(Long.valueOf(s));
if(imageBean!=null){
user.getImages().add(imageBean);
}
}
logger.info("id:"+user.getId()+" voted!");
user.setState(State.VOTED);
session.setAttribute(Constants.USER,userManager.insertUser(user));
return "redirect:/";
}
}
|
package com.appdear.client.commctrls;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.LinearLayout;
import android.widget.ImageView.ScaleType;
import com.appdear.client.R;
import com.appdear.client.Adapter.ViewPicAdapter;
/**
* 图片浏览布局
* @author zqm
*
*/
public class ViewPicLayout extends LinearLayout implements OnTouchListener
{
/**
* 适配器
*/
private ViewPicAdapter adapter;
/**
* 宽度
*/
private int width;
/**
* 高度
*/
private int height;
/**
* 是否加载图片
*/
public boolean isLoadotherpic = false;
public ViewPicLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
/**
* 设置布局格式
* @param adapter
* @param width
* @param height
*/
public void setAdapter(ViewPicAdapter adapter, View layoutview, int width, int height,Context context ) {
this.adapter = adapter;
this.width = width;
this.height = height;
layoutview.setOnTouchListener(this);
removeAllViews();
for (int i = 0; i < adapter.getCount(); i ++) {
if (i==3)
break;
View view=null;
if(i==2)
{
view = LayoutInflater.from(context).inflate(R.layout.viewpic_layout, null);
AsynLoadDetailImageView imgview = (AsynLoadDetailImageView) view.findViewById(R.id.software_image);
imgview.setImageResource(R.drawable.software_default_img);
imgview.setBackgroundResource(R.drawable.soft_shot_bg);
imgview.setScaleType(ScaleType.FIT_XY);
}else
{
view = adapter.getView(i, null, null);
// adapter.notifyDataSetChanged();
}
setOrientation(HORIZONTAL);
width = (height/7*3)/3*2;
LayoutParams layout = new LinearLayout.LayoutParams(width, height/7*3);
layout.setMargins(1, 0, 1, 0);
if(i==0){
layout.setMargins(10, 0, 1, 0);
}
if (i==3) {
layout.setMargins(1, 0, 10, 0);
}
addView(view, layout);
}
isLoadotherpic = true;
}
@Override
public boolean onTouch(View v, MotionEvent event) {
if (isLoadotherpic) {
if(adapter.getCount()>2)
removeViewAt(2);
for (int i = 2; i < adapter.getCount(); i ++) {
View view = adapter.getView(i, null, null);
adapter.notifyDataSetChanged();
setOrientation(HORIZONTAL);
width = (height/7*3)/3*2;
LayoutParams layout = new LinearLayout.LayoutParams(width, height/7*3);
layout.setMargins(1, 0, 1, 0);
if(i==0){
layout.setMargins(10, 0, 1, 0);
}
if (i==3) {
layout.setMargins(1, 0, 10, 0);
}
addView(view, layout);
}
isLoadotherpic = false;
}
return false;
}
}
|
package User;
public class Check {
private int check_num;
Check(){
this.check_num = 0;
}
Check(int check_num){
this.check_num = check_num;
}
public int getCheck_num() {
return this.check_num;
}
public void setCheck_num(int check_num) {
this.check_num = check_num;
}
}
|
package com.espendwise.manta.service;
import com.espendwise.manta.auth.ApplicationDataSource;
import com.espendwise.manta.spi.AppDS;
import com.espendwise.manta.util.TxUtil;
import org.springframework.beans.factory.annotation.Autowired;
import javax.persistence.EntityManager;
public abstract class DataAccessService extends DatabaseAccess {
@Autowired
protected ApplicationDataSource dataSource;
private ApplicationDataSource getDataSource() {
return dataSource;
}
public EntityManager getEntityManager() {
return getEntityManager(
getDataSource()
.getDataSourceIdent()
.getDataSourceName()
);
}
public boolean isAliveUnit(@AppDS String unit) {
return TxUtil.isAliveEntityManager(unit, getEntityManager(unit));
}
public String getDataSourceUrl(String datasource) {
return TxUtil.getDataSourceUrl(getEntityManager(datasource));
}
}
|
package cn.canlnac.onlinecourse.presentation.mapper;
import javax.inject.Inject;
import cn.canlnac.onlinecourse.domain.ChatList;
import cn.canlnac.onlinecourse.presentation.internal.di.PerActivity;
import cn.canlnac.onlinecourse.presentation.model.ChatListModel;
@PerActivity
public class ChatListModelDataMapper {
private final ChatModelDataMapper chatModelDataMapper;
@Inject
public ChatListModelDataMapper(ChatModelDataMapper chatModelDataMapper) {
this.chatModelDataMapper = chatModelDataMapper;
}
public ChatListModel transform(ChatList chatList) {
if (chatList == null) {
throw new IllegalArgumentException("Cannot transform a null value");
}
ChatListModel chatListModel = new ChatListModel();
chatListModel.setTotal(chatList.getTotal());
chatListModel.setChats(chatModelDataMapper.transform(chatList.getChats()));
return chatListModel;
}
}
|
package i_ninthexp;
import java.util.Scanner;
// 用分治法来求一串数中的逆序数的个数
public class NumOfReservedOrder {
private static int[] arr;
private static int count = 0;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("please input the quantity of numbers");
int n = scanner.nextInt();
arr = new int[n];
System.out.println("please input the content in array");
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}
divideAndConquerMethod(0, n - 1);
System.out.println(count);
}
private static int[] divideAndConquerMethod(int left, int right) {
if (left == right) {
return new int[]{arr[left], arr[left]};
} else if (right - left == 1) {
if (arr[right] < arr[left]) {
count++;
}
return new int[]{arr[left], arr[right]};
} else {
int mid = (left + right) / 2;
int[] lResult = divideAndConquerMethod(left, mid);
int[] rResult = divideAndConquerMethod(mid + 1, right);
if (lResult[1] > rResult[0]) {
count++;
}
return new int[]{lResult[0], rResult[1]};
}
}
}
|
package datastructure.linked;
/**
* @Author weimin
* @Date 2020/10/13 0013 15:51
* 双向链表
*/
public class DoubleLinked {
private int size;
private Node init = new Node("init", 0);
public boolean isEmpty() {
return size == 0;
}
public int getSize(){
return size;
}
public void addNext(Node node) {
Node temp = init;
while (temp.next!=null){
temp = temp.next;
}
temp.next = node;
node.pre = temp;
size++;
}
public void addPre(Node node) {
node.pre = init;
node.next = init.next;
init.next.pre = node;
init.next = node;
size++;
}
public void delete(int num){
if(isEmpty()){
return;
}
for (Node node = init.next;node != null;node = node.next){
if(node.num == num){
if(node.next==null){
node.pre.next = null;
node.pre = null;
}else {
node.next.pre = node.pre;
node.pre.next = node.next;
}
}
}
}
public void show(){
if(isEmpty()){
throw new RuntimeException("empty!!");
}else {
for (Node node = init.next;node!=null;node = node.next){
System.out.println(node);
}
}
}
static class Node {
private Node next;
private Node pre;
private String name;
private Integer num;
public Node(String name, Integer num) {
this.name = name;
this.num = num;
}
@Override
public String toString() {
return "Node{" +
"name='" + name + '\'' +
", num=" + num +
'}';
}
}
public static void main(String[] args) {
DoubleLinked doubleLinked = new DoubleLinked();
doubleLinked.addNext(new Node("lion",1));
doubleLinked.addNext(new Node("tiger",2));
doubleLinked.addNext(new Node("dog",3));
doubleLinked.addNext(new Node("fish",4));
doubleLinked.addPre(new Node("cat",0));
System.out.println(doubleLinked.getSize());
doubleLinked.show();
System.out.println("====================");
doubleLinked.delete(3);
doubleLinked.show();
System.out.println("====================");
doubleLinked.delete(4);
doubleLinked.show();
}
}
|
package ga.islandcrawl.state;
import java.util.HashMap;
import java.util.Iterator;
import ga.islandcrawl.map.Time;
import ga.islandcrawl.object.TimeListener;
import ga.islandcrawl.object.unit.Unit;
/**
* Created by Ga on 9/29/2015.
*/
public class UnitState extends State implements TimeListener{
public UnitState(Unit host){
super(host);
stats.put("speed",new Stat(.01f));
stats.put("aspeed",new Stat(30f));
stats.put("damage",new Stat(0f));
stats.put("sprint",new Stat(.4f));
stats.put("stamina",new Stat(50f));
stats.put("energy",new Stat(10f));
stats.get("energy").maxLimit = true;
}
@Override
public void renewStat(){
super.renewStat();
Iterator it = stats.entrySet().iterator();
while (it.hasNext()){
HashMap.Entry<String, Stat> i = (HashMap.Entry)it.next();
i.getValue().renew();
}
}
public boolean isTired(){
return stats.get("energy").getPercentage() < .2f;
}
public float getStrength(){
return stats.get("health").get() * stats.get("damage").get();
}
public boolean immobilized(){
if (effects.get("Immobilize") != null) return true;
return false;
}
public void eat(float amount){
addHealth(amount);
}
@Override
protected boolean validEffect(Effect effect){
return true;
}
@Override
public void timeEvent(Time p) {
stats.get("energy").doAdd(stats.get("energy").getPercentage(.1f));
}
}
|
/* Generated By:JavaCC: Do not edit this line. Parser.java */
package edu.utexas.cs345.jdblisp.parser;
import edu.utexas.cs345.jdblisp.*;
public class Parser implements ParserConstants {
private static Symbol QUOTE_SYMB = new Symbol("QUOTE");
private static Symbol FUNCTION_SYMB = new Symbol("FUNCTION");
/**
* sql_cmd -> sql_define | sql_control | sql_modify
*/
static final public SExp sql_cmd() throws ParseException {
SExp s;
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case ALTER:
case COMMENT:
case CREATE:
case DROP:
case RENAME:
case ANALYZE:
case EXPLAIN:
s = sql_define();
{if (true) return s;}
break;
default:
jj_la1[0] = jj_gen;
if (jj_2_1(2)) {
s = sql_control();
{if (true) return s;}
} else if (jj_2_2(2)) {
s = sql_modify();
{if (true) return s;}
} else {
jj_consume_token(-1);
throw new ParseException();
}
}
throw new Error("Missing return statement in function");
}
/**
* sql_define -> alter | comment | create | drop | rename | analyze | explain
*/
static final public SExp sql_define() throws ParseException {
Symbol s;
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case ALTER:
jj_consume_token(ALTER);
break;
case COMMENT:
jj_consume_token(COMMENT);
break;
case CREATE:
jj_consume_token(CREATE);
s = sql_create();
{if (true) return s;}
break;
case DROP:
jj_consume_token(DROP);
break;
case RENAME:
jj_consume_token(RENAME);
break;
case ANALYZE:
jj_consume_token(ANALYZE);
break;
case EXPLAIN:
jj_consume_token(EXPLAIN);
break;
default:
jj_la1[1] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
throw new Error("Missing return statement in function");
}
/**
* sql_create -> database | table
*/
static final public Symbol sql_create() throws ParseException {
Token t; List colList;
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case DATABASE:
jj_consume_token(DATABASE);
t = jj_consume_token(SYMB);
{if (true) return SQL.SQLQuery("CREATE DATABASE " + new Symbol(t.image));}
break;
default:
jj_la1[2] = jj_gen;
if (jj_2_3(3)) {
jj_consume_token(TABLE);
t = jj_consume_token(SYMB);
{if (true) return SQL.SQLQuery("CREATE TABLE " + new Symbol(t.image));}
} else if (jj_2_4(3)) {
jj_consume_token(TABLE);
t = jj_consume_token(SYMB);
colList = list();
{if (true) return SQL.SQLQuery("CREATE TABLE " + new Symbol(t.image) + listToSQL(colList));}
} else {
jj_consume_token(-1);
throw new ParseException();
}
}
throw new Error("Missing return statement in function");
}
/**SExp
* sql_control -> audit | noaudit | grant | revoke | set role
*/
static final public SExp sql_control() throws ParseException {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case AUDIT:
jj_consume_token(AUDIT);
break;
case NOAUDIT:
jj_consume_token(NOAUDIT);
break;
case GRANT:
jj_consume_token(GRANT);
break;
case REVOKE:
jj_consume_token(REVOKE);
break;
case SET:
jj_consume_token(SET);
jj_consume_token(ROLE);
break;
default:
jj_la1[3] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
}
/**
* sql_modify -> select | insert | update | delete | truncate | transaction | set transaction | lock
*/
static final public SExp sql_modify() throws ParseException {
Symbol s;
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case SELECT:
jj_consume_token(SELECT);
s = sql_select();
{if (true) return s;}
break;
case INSERT:
jj_consume_token(INSERT);
break;
case UPDATE:
jj_consume_token(UPDATE);
break;
case DELETE:
jj_consume_token(DELETE);
break;
case TRUNCATE:
jj_consume_token(TRUNCATE);
break;
case TRANSACTION:
jj_consume_token(TRANSACTION);
break;
case SET:
jj_consume_token(SET);
jj_consume_token(TRANSACTION);
break;
case LOCK:
jj_consume_token(LOCK);
break;
default:
jj_la1[4] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
throw new Error("Missing return statement in function");
}
/**
* sql_select ->
* TODO: WHERE isnt able to work yet
*/
static final public Symbol sql_select() throws ParseException {
Token table; List tables; SExp condition;
if (jj_2_5(3)) {
jj_consume_token(ALL);
jj_consume_token(AST);
jj_consume_token(FROM);
table = jj_consume_token(SYMB);
{if (true) return SQL.SQLQuery("SELECT ALL * FROM " + new Symbol(table.image));}
} else if (jj_2_6(3)) {
jj_consume_token(ALL);
jj_consume_token(AST);
jj_consume_token(FROM);
tables = list();
{if (true) return SQL.SQLQuery("SELECT ALL * FROM " + listToSQL(tables));}
} else if (jj_2_7(3)) {
jj_consume_token(DISTINCT);
jj_consume_token(AST);
jj_consume_token(FROM);
table = jj_consume_token(SYMB);
{if (true) return SQL.SQLQuery("SELECT DISTINCT * FROM " + new Symbol(table.image)) ;}
} else if (jj_2_8(3)) {
jj_consume_token(DISTINCT);
jj_consume_token(AST);
jj_consume_token(FROM);
tables = list();
{if (true) return SQL.SQLQuery("SELECT DISTINCT * FROM " + listToSQL(tables));}
} else if (jj_2_9(3)) {
jj_consume_token(AST);
jj_consume_token(FROM);
table = jj_consume_token(SYMB);
{if (true) return SQL.SQLQuery("SELECT * FROM " + new Symbol(table.image));}
} else if (jj_2_10(3)) {
jj_consume_token(AST);
jj_consume_token(FROM);
tables = list();
{if (true) return SQL.SQLQuery("SELECT * FROM " + listToSQL(tables));}
} else {
jj_consume_token(-1);
throw new ParseException();
}
throw new Error("Missing return statement in function");
}
/**
* sql_condition -> logical_term {or logical_term}* | not logical_term {or logical_term}*
*/
/*SExp sql_condition():
{ Symbol t;}//this doesn't do anything, filler.
{
//TODO how do you implement this one?..., should we have some substitution possible with lisp
}*/
/**
* SExp -> Symbol | Str | Num | List | SQL_CMD
*/
static final public SExp sexp() throws ParseException {
SExp s = null; Token t;
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case KEYWORD:
case SYMB:
s = symbol();
{if (true) return s;}
break;
case STRG:
t = jj_consume_token(STRG);
{if (true) return new Str(t.image);}
break;
case NUMB:
t = jj_consume_token(NUMB);
{if (true) return new Num(t.image);}
break;
case QUOTE:
t = jj_consume_token(QUOTE);
s = sexp();
{if (true) return new List(new Seq(QUOTE_SYMB, s));}
break;
case FUNCTION:
t = jj_consume_token(FUNCTION);
s = sexp();
{if (true) return new List(new Seq(FUNCTION_SYMB, s));}
break;
case LPAREN:
case NIL:
s = list();
{if (true) return s;}
break;
case ALTER:
case COMMENT:
case CREATE:
case DROP:
case RENAME:
case ANALYZE:
case EXPLAIN:
case AUDIT:
case NOAUDIT:
case GRANT:
case REVOKE:
case SET:
case SELECT:
case UPDATE:
case DELETE:
case INSERT:
case TRUNCATE:
case TRANSACTION:
case LOCK:
s = sql_cmd();
{if (true) return s;}
break;
default:
jj_la1[5] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
throw new Error("Missing return statement in function");
}
/**
* List -> "(" Seq ")"
*/
static final public List list() throws ParseException {
Seq s;
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case LPAREN:
jj_consume_token(LPAREN);
s = seq();
jj_consume_token(RPAREN);
{if (true) return new List(s);}
break;
case NIL:
jj_consume_token(NIL);
{if (true) return new List(null);}
break;
default:
jj_la1[6] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
throw new Error("Missing return statement in function");
}
/**
* Seq -> null | SExp Seq
*/
static final public Seq seq() throws ParseException {
Seq sq; SExp se;
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case ALTER:
case COMMENT:
case CREATE:
case DROP:
case RENAME:
case ANALYZE:
case EXPLAIN:
case AUDIT:
case NOAUDIT:
case GRANT:
case REVOKE:
case SET:
case SELECT:
case UPDATE:
case DELETE:
case INSERT:
case TRUNCATE:
case TRANSACTION:
case LOCK:
case LPAREN:
case NIL:
case QUOTE:
case FUNCTION:
case KEYWORD:
case NUMB:
case STRG:
case SYMB:
se = sexp();
sq = seq();
{if (true) return new Seq(se, sq);}
break;
default:
jj_la1[7] = jj_gen;
;
}
{if (true) return null;}
throw new Error("Missing return statement in function");
}
/**
* Symbol -> Symbol | Keyword Symbol
*/
static final public Symbol symbol() throws ParseException {
Token t;
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case SYMB:
t = jj_consume_token(SYMB);
{if (true) return new Symbol(t.image.toUpperCase());}
break;
case KEYWORD:
jj_consume_token(KEYWORD);
t = jj_consume_token(SYMB);
{if (true) return new Keyword(t.image.toUpperCase());}
break;
default:
jj_la1[8] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
throw new Error("Missing return statement in function");
}
static private boolean jj_2_1(int xla) {
jj_la = xla; jj_lastpos = jj_scanpos = token;
try { return !jj_3_1(); }
catch(LookaheadSuccess ls) { return true; }
finally { jj_save(0, xla); }
}
static private boolean jj_2_2(int xla) {
jj_la = xla; jj_lastpos = jj_scanpos = token;
try { return !jj_3_2(); }
catch(LookaheadSuccess ls) { return true; }
finally { jj_save(1, xla); }
}
static private boolean jj_2_3(int xla) {
jj_la = xla; jj_lastpos = jj_scanpos = token;
try { return !jj_3_3(); }
catch(LookaheadSuccess ls) { return true; }
finally { jj_save(2, xla); }
}
static private boolean jj_2_4(int xla) {
jj_la = xla; jj_lastpos = jj_scanpos = token;
try { return !jj_3_4(); }
catch(LookaheadSuccess ls) { return true; }
finally { jj_save(3, xla); }
}
static private boolean jj_2_5(int xla) {
jj_la = xla; jj_lastpos = jj_scanpos = token;
try { return !jj_3_5(); }
catch(LookaheadSuccess ls) { return true; }
finally { jj_save(4, xla); }
}
static private boolean jj_2_6(int xla) {
jj_la = xla; jj_lastpos = jj_scanpos = token;
try { return !jj_3_6(); }
catch(LookaheadSuccess ls) { return true; }
finally { jj_save(5, xla); }
}
static private boolean jj_2_7(int xla) {
jj_la = xla; jj_lastpos = jj_scanpos = token;
try { return !jj_3_7(); }
catch(LookaheadSuccess ls) { return true; }
finally { jj_save(6, xla); }
}
static private boolean jj_2_8(int xla) {
jj_la = xla; jj_lastpos = jj_scanpos = token;
try { return !jj_3_8(); }
catch(LookaheadSuccess ls) { return true; }
finally { jj_save(7, xla); }
}
static private boolean jj_2_9(int xla) {
jj_la = xla; jj_lastpos = jj_scanpos = token;
try { return !jj_3_9(); }
catch(LookaheadSuccess ls) { return true; }
finally { jj_save(8, xla); }
}
static private boolean jj_2_10(int xla) {
jj_la = xla; jj_lastpos = jj_scanpos = token;
try { return !jj_3_10(); }
catch(LookaheadSuccess ls) { return true; }
finally { jj_save(9, xla); }
}
static private boolean jj_3_2() {
if (jj_3R_2()) return true;
return false;
}
static private boolean jj_3R_2() {
Token xsp;
xsp = jj_scanpos;
if (jj_3R_5()) {
jj_scanpos = xsp;
if (jj_scan_token(17)) {
jj_scanpos = xsp;
if (jj_scan_token(15)) {
jj_scanpos = xsp;
if (jj_scan_token(16)) {
jj_scanpos = xsp;
if (jj_scan_token(18)) {
jj_scanpos = xsp;
if (jj_scan_token(19)) {
jj_scanpos = xsp;
if (jj_3R_6()) {
jj_scanpos = xsp;
if (jj_scan_token(20)) return true;
}
}
}
}
}
}
}
return false;
}
static private boolean jj_3R_5() {
if (jj_scan_token(SELECT)) return true;
if (jj_3R_9()) return true;
return false;
}
static private boolean jj_3_1() {
if (jj_3R_1()) return true;
return false;
}
static private boolean jj_3R_4() {
if (jj_scan_token(SET)) return true;
if (jj_scan_token(ROLE)) return true;
return false;
}
static private boolean jj_3R_1() {
Token xsp;
xsp = jj_scanpos;
if (jj_scan_token(8)) {
jj_scanpos = xsp;
if (jj_scan_token(9)) {
jj_scanpos = xsp;
if (jj_scan_token(10)) {
jj_scanpos = xsp;
if (jj_scan_token(11)) {
jj_scanpos = xsp;
if (jj_3R_4()) return true;
}
}
}
}
return false;
}
static private boolean jj_3_10() {
if (jj_scan_token(AST)) return true;
if (jj_scan_token(FROM)) return true;
if (jj_3R_3()) return true;
return false;
}
static private boolean jj_3_9() {
if (jj_scan_token(AST)) return true;
if (jj_scan_token(FROM)) return true;
if (jj_scan_token(SYMB)) return true;
return false;
}
static private boolean jj_3_4() {
if (jj_scan_token(TABLE)) return true;
if (jj_scan_token(SYMB)) return true;
if (jj_3R_3()) return true;
return false;
}
static private boolean jj_3_8() {
if (jj_scan_token(DISTINCT)) return true;
if (jj_scan_token(AST)) return true;
if (jj_scan_token(FROM)) return true;
return false;
}
static private boolean jj_3_3() {
if (jj_scan_token(TABLE)) return true;
if (jj_scan_token(SYMB)) return true;
return false;
}
static private boolean jj_3_7() {
if (jj_scan_token(DISTINCT)) return true;
if (jj_scan_token(AST)) return true;
if (jj_scan_token(FROM)) return true;
return false;
}
static private boolean jj_3R_8() {
if (jj_scan_token(NIL)) return true;
return false;
}
static private boolean jj_3_6() {
if (jj_scan_token(ALL)) return true;
if (jj_scan_token(AST)) return true;
if (jj_scan_token(FROM)) return true;
return false;
}
static private boolean jj_3R_3() {
Token xsp;
xsp = jj_scanpos;
if (jj_3R_7()) {
jj_scanpos = xsp;
if (jj_3R_8()) return true;
}
return false;
}
static private boolean jj_3R_7() {
if (jj_scan_token(LPAREN)) return true;
return false;
}
static private boolean jj_3R_9() {
Token xsp;
xsp = jj_scanpos;
if (jj_3_5()) {
jj_scanpos = xsp;
if (jj_3_6()) {
jj_scanpos = xsp;
if (jj_3_7()) {
jj_scanpos = xsp;
if (jj_3_8()) {
jj_scanpos = xsp;
if (jj_3_9()) {
jj_scanpos = xsp;
if (jj_3_10()) return true;
}
}
}
}
}
return false;
}
static private boolean jj_3_5() {
if (jj_scan_token(ALL)) return true;
if (jj_scan_token(AST)) return true;
if (jj_scan_token(FROM)) return true;
return false;
}
static private boolean jj_3R_6() {
if (jj_scan_token(SET)) return true;
if (jj_scan_token(TRANSACTION)) return true;
return false;
}
static private boolean jj_initialized_once = false;
/** Generated Token Manager. */
static public ParserTokenManager token_source;
static SimpleCharStream jj_input_stream;
/** Current token. */
static public Token token;
/** Next token. */
static public Token jj_nt;
static private int jj_ntk;
static private Token jj_scanpos, jj_lastpos;
static private int jj_la;
static private int jj_gen;
static final private int[] jj_la1 = new int[9];
static private int[] jj_la1_0;
static private int[] jj_la1_1;
static {
jj_la1_init_0();
jj_la1_init_1();
}
private static void jj_la1_init_0() {
jj_la1_0 = new int[] {0xfe,0xfe,0x200000,0x1f00,0x1fd000,0x1fdffe,0x0,0x1fdffe,0x0,};
}
private static void jj_la1_init_1() {
jj_la1_1 = new int[] {0x0,0x0,0x0,0x0,0x0,0xfe8,0x28,0xfe8,0x900,};
}
static final private JJCalls[] jj_2_rtns = new JJCalls[10];
static private boolean jj_rescan = false;
static private int jj_gc = 0;
/** Constructor with InputStream. */
public Parser(java.io.InputStream stream) {
this(stream, null);
}
/** Constructor with InputStream and supplied encoding */
public Parser(java.io.InputStream stream, String encoding) {
if (jj_initialized_once) {
System.out.println("ERROR: Second call to constructor of static parser. ");
System.out.println(" You must either use ReInit() or set the JavaCC option STATIC to false");
System.out.println(" during parser generation.");
throw new Error();
}
jj_initialized_once = true;
try { jj_input_stream = new SimpleCharStream(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); }
token_source = new ParserTokenManager(jj_input_stream);
token = new Token();
jj_ntk = -1;
jj_gen = 0;
for (int i = 0; i < 9; i++) jj_la1[i] = -1;
for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();
}
/** Reinitialise. */
static public void ReInit(java.io.InputStream stream) {
ReInit(stream, null);
}
/** Reinitialise. */
static public void ReInit(java.io.InputStream stream, String encoding) {
try { jj_input_stream.ReInit(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); }
token_source.ReInit(jj_input_stream);
token = new Token();
jj_ntk = -1;
jj_gen = 0;
for (int i = 0; i < 9; i++) jj_la1[i] = -1;
for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();
}
/** Constructor. */
public Parser(java.io.Reader stream) {
if (jj_initialized_once) {
System.out.println("ERROR: Second call to constructor of static parser. ");
System.out.println(" You must either use ReInit() or set the JavaCC option STATIC to false");
System.out.println(" during parser generation.");
throw new Error();
}
jj_initialized_once = true;
jj_input_stream = new SimpleCharStream(stream, 1, 1);
token_source = new ParserTokenManager(jj_input_stream);
token = new Token();
jj_ntk = -1;
jj_gen = 0;
for (int i = 0; i < 9; i++) jj_la1[i] = -1;
for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();
}
/** Reinitialise. */
static public void ReInit(java.io.Reader stream) {
jj_input_stream.ReInit(stream, 1, 1);
token_source.ReInit(jj_input_stream);
token = new Token();
jj_ntk = -1;
jj_gen = 0;
for (int i = 0; i < 9; i++) jj_la1[i] = -1;
for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();
}
/** Constructor with generated Token Manager. */
public Parser(ParserTokenManager tm) {
if (jj_initialized_once) {
System.out.println("ERROR: Second call to constructor of static parser. ");
System.out.println(" You must either use ReInit() or set the JavaCC option STATIC to false");
System.out.println(" during parser generation.");
throw new Error();
}
jj_initialized_once = true;
token_source = tm;
token = new Token();
jj_ntk = -1;
jj_gen = 0;
for (int i = 0; i < 9; i++) jj_la1[i] = -1;
for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();
}
/** Reinitialise. */
public void ReInit(ParserTokenManager tm) {
token_source = tm;
token = new Token();
jj_ntk = -1;
jj_gen = 0;
for (int i = 0; i < 9; i++) jj_la1[i] = -1;
for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();
}
static private Token jj_consume_token(int kind) throws ParseException {
Token oldToken;
if ((oldToken = token).next != null) token = token.next;
else token = token.next = token_source.getNextToken();
jj_ntk = -1;
if (token.kind == kind) {
jj_gen++;
if (++jj_gc > 100) {
jj_gc = 0;
for (int i = 0; i < jj_2_rtns.length; i++) {
JJCalls c = jj_2_rtns[i];
while (c != null) {
if (c.gen < jj_gen) c.first = null;
c = c.next;
}
}
}
return token;
}
token = oldToken;
jj_kind = kind;
throw generateParseException();
}
static private final class LookaheadSuccess extends java.lang.Error { }
static final private LookaheadSuccess jj_ls = new LookaheadSuccess();
static private boolean jj_scan_token(int kind) {
if (jj_scanpos == jj_lastpos) {
jj_la--;
if (jj_scanpos.next == null) {
jj_lastpos = jj_scanpos = jj_scanpos.next = token_source.getNextToken();
} else {
jj_lastpos = jj_scanpos = jj_scanpos.next;
}
} else {
jj_scanpos = jj_scanpos.next;
}
if (jj_rescan) {
int i = 0; Token tok = token;
while (tok != null && tok != jj_scanpos) { i++; tok = tok.next; }
if (tok != null) jj_add_error_token(kind, i);
}
if (jj_scanpos.kind != kind) return true;
if (jj_la == 0 && jj_scanpos == jj_lastpos) throw jj_ls;
return false;
}
/** Get the next Token. */
static final public Token getNextToken() {
if (token.next != null) token = token.next;
else token = token.next = token_source.getNextToken();
jj_ntk = -1;
jj_gen++;
return token;
}
/** Get the specific Token. */
static final public Token getToken(int index) {
Token t = token;
for (int i = 0; i < index; i++) {
if (t.next != null) t = t.next;
else t = t.next = token_source.getNextToken();
}
return t;
}
static private int jj_ntk() {
if ((jj_nt=token.next) == null)
return (jj_ntk = (token.next=token_source.getNextToken()).kind);
else
return (jj_ntk = jj_nt.kind);
}
static private java.util.List<int[]> jj_expentries = new java.util.ArrayList<int[]>();
static private int[] jj_expentry;
static private int jj_kind = -1;
static private int[] jj_lasttokens = new int[100];
static private int jj_endpos;
static private void jj_add_error_token(int kind, int pos) {
if (pos >= 100) return;
if (pos == jj_endpos + 1) {
jj_lasttokens[jj_endpos++] = kind;
} else if (jj_endpos != 0) {
jj_expentry = new int[jj_endpos];
for (int i = 0; i < jj_endpos; i++) {
jj_expentry[i] = jj_lasttokens[i];
}
jj_entries_loop: for (java.util.Iterator<?> it = jj_expentries.iterator(); it.hasNext();) {
int[] oldentry = (int[])(it.next());
if (oldentry.length == jj_expentry.length) {
for (int i = 0; i < jj_expentry.length; i++) {
if (oldentry[i] != jj_expentry[i]) {
continue jj_entries_loop;
}
}
jj_expentries.add(jj_expentry);
break jj_entries_loop;
}
}
if (pos != 0) jj_lasttokens[(jj_endpos = pos) - 1] = kind;
}
}
/** Generate ParseException. */
static public ParseException generateParseException() {
jj_expentries.clear();
boolean[] la1tokens = new boolean[44];
if (jj_kind >= 0) {
la1tokens[jj_kind] = true;
jj_kind = -1;
}
for (int i = 0; i < 9; i++) {
if (jj_la1[i] == jj_gen) {
for (int j = 0; j < 32; j++) {
if ((jj_la1_0[i] & (1<<j)) != 0) {
la1tokens[j] = true;
}
if ((jj_la1_1[i] & (1<<j)) != 0) {
la1tokens[32+j] = true;
}
}
}
}
for (int i = 0; i < 44; i++) {
if (la1tokens[i]) {
jj_expentry = new int[1];
jj_expentry[0] = i;
jj_expentries.add(jj_expentry);
}
}
jj_endpos = 0;
jj_rescan_token();
jj_add_error_token(0, 0);
int[][] exptokseq = new int[jj_expentries.size()][];
for (int i = 0; i < jj_expentries.size(); i++) {
exptokseq[i] = jj_expentries.get(i);
}
return new ParseException(token, exptokseq, tokenImage);
}
/** Enable tracing. */
static final public void enable_tracing() {
}
/** Disable tracing. */
static final public void disable_tracing() {
}
static private void jj_rescan_token() {
jj_rescan = true;
for (int i = 0; i < 10; i++) {
try {
JJCalls p = jj_2_rtns[i];
do {
if (p.gen > jj_gen) {
jj_la = p.arg; jj_lastpos = jj_scanpos = p.first;
switch (i) {
case 0: jj_3_1(); break;
case 1: jj_3_2(); break;
case 2: jj_3_3(); break;
case 3: jj_3_4(); break;
case 4: jj_3_5(); break;
case 5: jj_3_6(); break;
case 6: jj_3_7(); break;
case 7: jj_3_8(); break;
case 8: jj_3_9(); break;
case 9: jj_3_10(); break;
}
}
p = p.next;
} while (p != null);
} catch(LookaheadSuccess ls) { }
}
jj_rescan = false;
}
static private void jj_save(int index, int xla) {
JJCalls p = jj_2_rtns[index];
while (p.gen > jj_gen) {
if (p.next == null) { p = p.next = new JJCalls(); break; }
p = p.next;
}
p.gen = jj_gen + xla - jj_la; p.first = token; p.arg = xla;
}
static final class JJCalls {
int gen;
Token first;
int arg;
JJCalls next;
}
}
|
package me.saurpuss.recap;
import me.saurpuss.recap.util.FileWriteCallback;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.configuration.file.FileConfiguration;
import java.io.*;
import java.nio.charset.Charset;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.logging.Level;
/**
* Recap Manager Utility class, implements command functionality and file access.
*/
public class RecapManager {
private RecapMain plugin;
private final DateTimeFormatter formatter;
// Config preferences
private final int maxSize;
private final boolean logAuthor;
private final boolean allowColors;
// Recap file things
private final File recapFile;
private final ReadWriteLock fileLock = new ReentrantReadWriteLock();
private final Lock fileWriteLock = fileLock.writeLock();
private final Lock fileReadLock = fileLock.readLock();
// Runtime recap
private final ReadWriteLock queueLock = new ReentrantReadWriteLock();
private final Lock queueWriteLock = queueLock.writeLock();
private Deque<String> recent;
public RecapManager(RecapMain recap) {
plugin = recap;
// Get preferences
final FileConfiguration config = plugin.getConfig();
final String format = config.getString("date-format");
formatter = DateTimeFormatter.ofPattern(format != null ? format : "MMM dd");
maxSize = Math.abs(config.getInt("max-size"));
logAuthor = config.getBoolean("log-author");
allowColors = config.getBoolean("allow-colors");
// Set up recap.txt (if necessary)
recapFile = new File(plugin.getDataFolder(), "recap.txt");
if (!recapFile.exists()) {
try {
recapFile.createNewFile();
} catch (IOException e) {
plugin.getLogger().log(Level.WARNING, "Can't load file writer/reader, " +
"disabling plugin!", e);
Bukkit.getPluginManager().disablePlugin(plugin);
return;
}
}
// Try to retrieve existing recap logs
if (recapFile.length() == 0) setupRecapFile();
recent = setupRecapQueue();
}
public List<String> getRecent() {
final ArrayList<String> result;
result = new ArrayList<>(recent);
return result;
}
public String getLogString(final String sender, final String message) {
return ChatColor.RED + LocalDate.now().format(formatter) + " §6-§c " +
(logAuthor ? sender + "§6: §r" : "§r") + (allowColors ?
ChatColor.translateAlternateColorCodes('&', message) : message);
}
public void writeLog(String log, FileWriteCallback callback) {
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
final boolean toFile = writeToFile(log);
final boolean toQueue = writeToQueue(log);
Bukkit.getScheduler().runTask(plugin, () -> callback.fileWriteCallback(toFile, toQueue));
});
}
private boolean writeToQueue(String log) {
queueWriteLock.lock();
try {
recent.addLast(log);
if (recent.size() > maxSize) recent.removeFirst();
return true;
} finally {
queueWriteLock.unlock();
}
}
/**
* Add a line to the recap.txt file
* @param log date, author (optional), and message to be saved into the file
* @return true if successful
*/
private boolean writeToFile(String log) {
fileWriteLock.lock();
try (PrintWriter writer = new PrintWriter(new FileWriter(recapFile, true), true)) {
writer.println(log);
return true;
} catch (IOException e) {
plugin.getLogger().log(Level.SEVERE, "Failed to write to recap log!", e);
} finally {
fileWriteLock.unlock();
}
return false;
}
/**
* Populate the runtime recap log with information from the recap.txt file, sorted from
* newest to oldest.
*
* @return Linked List filled with the recap logs
*/
private Deque<String> setupRecapQueue() {
List<String> list = new ArrayList<>();
Deque<String> log = new LinkedList<>();
fileReadLock.lock();
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(new FileInputStream(recapFile), Charset.defaultCharset()))) {
String line;
while ((line = reader.readLine()) != null)
list.add(line);
} catch (IOException e) {
plugin.getLogger().log(Level.WARNING, "Error when trying to retrieve the logs " +
"from recap.txt! Printing StackTrace and disabling plugin!" + e);
plugin.getServer().getPluginManager().disablePlugin(plugin);
return log;
} finally {
fileReadLock.unlock();
}
Collections.reverse(list);
for (int i = 0; i < maxSize && i < list.size(); i++)
log.addFirst(list.get(i));
return log;
}
/**
* Create the recap.txt file in the config folder if necessary and attempt to write a line to
* the file. If either of these fails the plugin will be disabled.
*/
private void setupRecapFile() {
plugin.getLogger().log(Level.INFO, "Attempting to write to recap.txt!");
final String log = "§c" + LocalDateTime.now().format(formatter) + "§6 - §rUse " +
"§d/recap [message here...] §rto add a recap!";
writeToFile(log);
plugin.getLogger().log(Level.INFO, "Finished creating recap.txt!");
}
}
|
package com.tencent.mm.plugin.webview.ui.tools.bag;
public final class l$a {
}
|
package fr.onhenriquanne.Main;
public class Dezoom {
public Dezoom(){
int[][] map = new int[Main.getMap().length][Main.getMap()[0].length];
int[][] map1 = new int[map.length*2][map[0].length*2];
map = Main.getMap();
for (int i=0;i<map.length;i++){
for (int a=0;a<map[0].length;a++){
map1[(map1.length-map.length)/2+i][(map1[0].length-map.length)/2+a] = map[i][a];
}
}
Main.setSize(Main.Size()/2);
Main.setMap(map1);
}
}
|
package com.github.project.dao;
import com.github.project.checks.CheckOnNull;
import com.github.project.view.WorkCycle;
import com.github.project.view.menu.HelperMenu;
import com.github.project.view.menu.ShowMenu;
import static com.github.project.dao.DaoDelete.safeForFile;
public class DaoMenu {
public static java.util.Scanner scanner = new java.util.Scanner(System.in);
public static void showMenu() {
boolean flagfor = true;
while (flagfor) {
System.out.println(ShowMenu.menuCrudHelpers);
String menuChoise = scanner.next();
CheckOnNull.checkOnNull(menuChoise);
try {
if (menuChoise.equals("1")) {
System.out.println(ShowMenu.fileType);
while (!scanner.hasNextInt()) {
System.out.println("That not a number! Enter number: ");
scanner.next();
}
String typeOfFile = scanner.next();
getFileNameByTypeOfFile(typeOfFile);
System.out.println(ShowMenu.menuCrud);
String crudChoose = scanner.next();
WorkCycle.crudMenu(crudChoose, getFileNameByTypeOfFile(typeOfFile));
}
if (menuChoise.equals("2")) {
System.out.println(ShowMenu.menuHelpers);
String helpersChoose = scanner.next();
HelperMenu.helpersMethot(helpersChoose);
} else
{
System.out.println("select 1 or 2");
continue;
}
} catch (Exception e) {
System.out.println("Error :) data is written to file");
System.out.println(e.getMessage());
safeForFile(menuChoise);
}
}
}
private static String getFileNameByTypeOfFile(String typeOfFile) {
if (typeOfFile.equals("1")) {
return "js.json";
} else if (typeOfFile.equals("2")) {
return "xm.xml";
} else if (typeOfFile.equals("3")) {
return "cv.csv";
} else if (typeOfFile.equals("4")) {
return "ya.yaml";
} else if (typeOfFile.equals("5")) {
return "binary.bin";
} else if (typeOfFile.equals("6")) {
showMenu();
} else {
showMenu();
System.out.println("Error enter. Try again: ");
}
return "";
}
}
|
package chapter06;
public class Exercise06_35 {
public static void main(String[] args) {
System.out.println(area(5.5));
}
public static double area(double side) {
return (5 * Math.pow(side, 2)) / (4 * Math.tan(Math.PI / 5));
}
}
|
package com.cxjd.nvwabao.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.cxjd.nvwabao.R;
import com.cxjd.nvwabao.bean.PeopleReturn;
import com.cxjd.nvwabao.bean.User;
import org.litepal.crud.DataSupport;
import java.util.List;
/**
* Created by 白 on 2018/3/21.
* 用于 进行回帖 编辑页面
*/
public class PeopleChatOneActivity extends AppCompatActivity implements View.OnClickListener {
private String TAG;
private String returnChat;
//接收的 需要回复的用户id
private int peopleId;
//
private Boolean isPause;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.a1_say);
Intent intent = getIntent();
peopleId = intent.getIntExtra("id", 0);
System.out.println("id为---------"+peopleId);
Button sendButton = (Button) findViewById(R.id.send_button);
sendButton.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.send_button:
EditText editText = (EditText) findViewById(R.id.say_text);
returnChat = editText.getText().toString().trim();
if (TextUtils.isEmpty(returnChat)) {
Toast.makeText(this, "不可为空", Toast.LENGTH_SHORT).show();
} else {
List<User> users= DataSupport.findAll(User.class);
String username;
if (users != null && !users.isEmpty()) {
username=users.get(users.size()-1).getmName();
}else {
User user = new User();
user.setmName("游客账号");
user.setPassword("666");
user.save();
username = "游客账号";
}
PeopleReturn peopleReturn = new PeopleReturn();
peopleReturn.setPeopleId(peopleId);
peopleReturn.setReturnChat(returnChat);
peopleReturn.setReturnName(username);
peopleReturn.setImageId(R.drawable.a1_people);
peopleReturn.save();
Toast.makeText(this, "回复成功!", Toast.LENGTH_SHORT).show();
finish();
}
break;
}
}
}
|
package net.liuzd.spring.boot.v2.domain;
import java.util.Date;
import java.util.List;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter@Setter@ToString
@Document(indexName = "blog", type = "blog", shards = 3, replicas = 0) //本地测试,因此复制分片数设为0
public class Blog {
@Id//主键
private String id;
@Field(type = FieldType.Text, searchAnalyzer = "ik_smart", analyzer = "ik_smart")//指定为Text类型,参与全文检索。设置分词器
private String title;
@Field(type = FieldType.Text, searchAnalyzer = "ik_smart", analyzer = "ik_smart")
private String content;
@Field(type = FieldType.Keyword)
private String username; //blog 作者
@Field(type = FieldType.Date, index = false)//index设为false不做全文检索,默认为true
private Date createTime; //创建时间
@Field(type = FieldType.Integer, index = false)
private Integer readSize = 0; // 阅读量
@Field(type = FieldType.Keyword)
private List<String> tags; //标签 对应es中存储结构 ["Spring Data", "Spring Boot"]
}
|
package com.flipkart.assignment.service;
import com.flipkart.assignment.enums.Genre;
import com.flipkart.assignment.enums.ReviewerType;
import com.flipkart.assignment.model.Movie;
import com.flipkart.assignment.model.User;
import java.util.List;
public interface UserService {
boolean addUser(String name);
User getUser(String name);
boolean changeUserType(String name, ReviewerType reviewerType);
}
|
package com.jiw.dudu.listener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;
/**
* @Description RabbitMQ 生产者发送消息到交换机的confirm机制确认回调
* @Author pangh
* @Date 2022年09月27日
* @Version v1.0.0
*/
@Component
@Slf4j
public class RabbitExchangeCallback implements RabbitTemplate.ConfirmCallback {
/**
* Confirmation callback.
*
* @param correlationData correlation data for the callback.
* @param ack true for ack, false for nack
* @param cause An optional cause, for nack, when available, otherwise null.
*/
@Override
public void confirm(CorrelationData correlationData, boolean ack, String cause) {
// log.info("RabbitMQ交换机接收消息确认回调...");
// 消息ID
String id = correlationData.getId();
// 消息
String message = new String(correlationData.getReturned().getMessage().getBody());
if(ack){
// log.info("交换机收到消息ID为{},消息内容为{}",id,message);
}else{
// log.info("交换机未收到消息ID为{},消息内容为{},原因为{}",id,message,cause);
}
}
}
|
package com.ad.system.service.impl;
import com.ad.system.dao.SysResourcesMapper;
import com.ad.system.dao.SysUserMapper;
import com.ad.system.model.SysUser;
import com.ad.system.service.SysRoleService;
import com.ad.system.service.UserService;
import com.ad.system.utils.UrlUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private SysUserMapper sysUserMapper;
@Autowired
private SysResourcesMapper sysResourcesMapper;
@Override
public SysUser getUser(SysUser user) {
List<SysUser> sysUsers = sysUserMapper.selectBySysUser(user);
if (!ObjectUtils.isEmpty(sysUsers) && sysUsers.size() == 1) {
return sysUsers.get(0);
}
return null;
}
@Override
public Set<String> findPermissionsByUserId(Integer userId) {
Set<String> permissions = sysResourcesMapper.findPermissionsByUserId(userId);
Set<String> result = new HashSet<>();
for (String permission : permissions) {
if (StringUtils.isBlank(permission)) {
continue;
}
permission = StringUtils.trim(permission);
result.add(UrlUtils.getCurrentURI(permission,null));
}
result.add((UrlUtils.getCurrentURI("/auth/index",null)));
return result;
}
}
|
package com.qswy.app.activity.affairremind;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.qswy.app.R;
import com.qswy.app.activity.BaseActivity;
import com.qswy.app.fragment.ARemindListFragment;
import com.shizhefei.view.indicator.Indicator;
import com.shizhefei.view.indicator.IndicatorViewPager;
import com.shizhefei.view.indicator.slidebar.ColorBar;
public class AffairRemindActivity extends BaseActivity implements View.OnClickListener{
private IndicatorViewPager indicatorViewPager;
private LayoutInflater inflate;
private ViewPager viewPager;
private Indicator indicator;
private static String[] tabName = {"未读","已读"};
public static final String ISREAD = "isRead";
@Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_affair_remind);
super.onCreate(savedInstanceState);
}
@Override
protected void initView() {
viewPager = (ViewPager) findViewById(R.id.vp_remind_page);
indicator = (Indicator) findViewById(R.id.indicator_remind_tab);
viewPager.setOffscreenPageLimit(2);
indicator.setScrollBar(new ColorBar(getApplicationContext(), getResources().getColor(R.color.main_bottom_tag), 5));
indicatorViewPager = new IndicatorViewPager(indicator, viewPager);
inflate = LayoutInflater.from(getApplicationContext());
ivBack = (ImageView) findViewById(R.id.iv_public_back);
tvTitle = (TextView) findViewById(R.id.tv_public_title);
}
@Override
protected void initialization() {
indicatorViewPager.setAdapter(new MyAdapter(getSupportFragmentManager()));
tvTitle.setText(R.string.affair_remind);
}
@Override
protected void loadData() {
}
@Override
protected void initListener() {
ivBack.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.iv_public_back:
finish();
break;
}
}
private class MyAdapter extends IndicatorViewPager.IndicatorFragmentPagerAdapter {
public MyAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
@Override
public int getCount() {
return 2;
}
@Override
public View getViewForTab(int position, View convertView, ViewGroup container) {
if (convertView == null) {
convertView = inflate.inflate(R.layout.affair_remind_tab_top, container, false);
}
TextView textView = (TextView) convertView;
textView.setText(tabName[position]);
return convertView;
}
@Override
public Fragment getFragmentForPage(int position) {
ARemindListFragment mFragment = new ARemindListFragment();
Bundle bundle = new Bundle();
if (position==0){
bundle.putBoolean(ISREAD,false);
}else if (position==1){
bundle.putBoolean(ISREAD,true);
}
mFragment.setArguments(bundle);
return mFragment;
}
}
}
|
package projectprogweb.dao;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.mysql.jdbc.PreparedStatement;
import projectprogweb.cripto.BCrypt;
import projectprogweb.jdbc.ConexaoBD;
import projectprogweb.modelo.Usuario;
@Repository
public class UsuarioDAO {
private Connection connection;
/*@Autowired
public UsuarioDAO(DataSource dataSource) {
try {
this.connection = dataSource.getConnection();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
*/
public UsuarioDAO(){
this.connection = new ConexaoBD().getConexaoBD();
}
public void cadastra(Usuario user){
String sql = "insert into usuarios (nome, login, password, email, nascimento) values(?,?,?,?,?)";
try{
PreparedStatement stmt = (PreparedStatement) connection.prepareStatement(sql);
String senha = BCrypt.hashpw(user.getPassword(), BCrypt.gensalt());
stmt.setString(1, user.getNome());
stmt.setString(2, user.getLogin());
stmt.setString(3, senha);
stmt.setString(4, user.getEmail());
stmt.setString(5, user.getNascimento());
stmt.execute();
stmt.close();
}catch (SQLException e){
throw new RuntimeException(e);
}
}
public void remove(Usuario user){
String sql = "delete from usuarios where login=?";
try{
PreparedStatement stmt = (PreparedStatement) connection.prepareStatement(sql);
String login = user.getLogin();
stmt.setString(1, login);
stmt.execute();
stmt.close();
}catch (SQLException e){
throw new RuntimeException(e);
}
}
public void alteraEmail(Usuario user){
String sql = "update usuarios set email=? where login=?";
try{
PreparedStatement stmt = (PreparedStatement) connection.prepareStatement(sql);
stmt.setString(1, user.getEmail());
stmt.setString(2, user.getLogin());
stmt.execute();
stmt.close();
}catch (SQLException e){
throw new RuntimeException(e);
}
}
public void alteraSenha(Usuario user){
String sql = "update usuarios set password=? where login=?";
try{
PreparedStatement stmt = (PreparedStatement) connection.prepareStatement(sql);
String senha = BCrypt.hashpw(user.getPassword(), BCrypt.gensalt());
stmt.setString(1, senha);
stmt.setString(2, user.getLogin());
stmt.execute();
stmt.close();
}catch (SQLException e){
throw new RuntimeException(e);
}
}
public boolean checaPermissao(Usuario usuario){
boolean permissao = false;
Usuario user = getUsuario(usuario.getLogin());
if(estaCadastrado(usuario.getLogin()) || (usuario != null && user != null)){
permissao = BCrypt.checkpw(usuario.getPassword(), user.getPassword());
System.out.println("usuario est� cadastrado");
}
else{
System.out.println("usuario nao cadastrado");
}
return permissao;
}
public boolean estaCadastrado(String login){
PreparedStatement stmt;
String sql = "select * from usuarios where login=?";
try{
stmt = (PreparedStatement) connection.prepareStatement(sql);
stmt.setString(1, login);
ResultSet rs = stmt.executeQuery();
if(rs.next())
return true;
rs.close();
stmt.close();
} catch(SQLException e){
throw new RuntimeException(e);
}
return false;
}
public Usuario getUsuario(String login){
Usuario user = null;
PreparedStatement stmt;
String sql = "select * from usuarios where login=?";
try{
stmt = (PreparedStatement) connection.prepareStatement(sql);
stmt.setString(1, login);
ResultSet rs = stmt.executeQuery();
if(rs.next()){
user = new Usuario();
user.setLogin(rs.getString("login"));
user.setPassword(rs.getString("password"));
}
rs.close();
stmt.close();
}catch(SQLException e){
throw new RuntimeException(e);
}
return user;
}
}
|
package model;
import entities.Article;
import entities.Category;
import entities.HibernateUtil;
import entities.LeadingArticle;
import entities.User;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.exception.SQLGrammarException;
import org.hibernate.transform.AliasToEntityMapResultTransformer;
public class DataBase {
private static Session session = null;
public static boolean saveArticle(Article art, String[] categories) {
try {
session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
for (int i = 0; i < categories.length; i++) {
int id = Integer.parseInt(categories[i]);
Category cat = (Category)session.load(Category.class, id);
art.getCategories().add(cat);
}
session.save(art);
session.getTransaction().commit();
session.close();
} catch (Exception e) {
if (session.getTransaction() != null) {
session.getTransaction().rollback();
return false;
}
} finally {
if (session.isOpen())
session.close();
}
return true;
}
public static boolean updateArticle(Article art, String[] categories) {
try {
session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
art.getCategories().clear();
for (int i = 0; i < categories.length; i++) {
int id = Integer.parseInt(categories[i]);
Category cat = (Category)session.load(Category.class, id);
art.getCategories().add(cat);
}
session.saveOrUpdate(art);
session.getTransaction().commit();
} catch (Exception e) {
if (session.getTransaction() != null) {
session.getTransaction().rollback();
return false;
}
} finally {
if (session.isOpen())
session.close();
}
return true;
}
public static boolean deleteArticle(String id) {
try {
session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
int artId = Integer.parseInt(id);
Article art = (Article) session.get(Article.class, (long)artId);
session.delete(art);
session.getTransaction().commit();
} catch (Exception e) {
if (session.getTransaction() != null) {
session.getTransaction().rollback();
return false;
}
} finally {
if (session.isOpen())
session.close();
}
return true;
}
public static Article getSingleArticle(String id) {
Article art = null;
try {
session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
long artId = Long.parseLong(id);
art = (Article) session.get(Article.class, artId);
art.getCategories().size();
session.getTransaction().commit();
} catch (Exception e) {
if (session.getTransaction() != null) {
session.getTransaction().rollback();
}
} finally {
if (session.isOpen())
session.close();
}
return art;
}
public static int getTypeOfArticle(String id) {
int type = -1;
try {
session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
long artId = Long.parseLong(id);
LeadingArticle la = (LeadingArticle) session.load(LeadingArticle.class, artId);
if (la.isMainOrNot())
type = 1;
else if (!la.isMainOrNot())
type = 0;
session.getTransaction().commit();
} catch (Exception e) {
if (session.getTransaction() != null) {
session.getTransaction().rollback();
}
} finally {
if (session.isOpen())
session.close();
}
return type;
}
public static boolean updateLeadingToHome() {
try {
session.beginTransaction();
Criteria critUpdate = session.createCriteria(LeadingArticle.class);
critUpdate.add(Restrictions.eq("mainOrNot", Boolean.TRUE));
List<LeadingArticle> list = critUpdate.list();
for (LeadingArticle l: list) {
l.setMainOrNot(false);
session.update(l);
}
session.getTransaction().commit();
} catch (HibernateException he) {
if (session.getTransaction() != null)
session.getTransaction().rollback();
return false;
}
return true;
}
public static boolean deleteOldestHome() {
try {
session.beginTransaction();
Criteria critOldest = session.createCriteria(LeadingArticle.class);
critOldest.add(Restrictions.eq("mainOrNot", Boolean.FALSE));
critOldest.setProjection(Projections.min("id"));
LeadingArticle laDel = (LeadingArticle) critOldest.uniqueResult();
session.delete(laDel);
session.getTransaction().commit();
} catch (HibernateException he) {
if (session.getTransaction() != null)
session.getTransaction().rollback();
return false;
}
return true;
}
public static boolean saveLeadingHomeArticle(LeadingArticle la) {
try {
session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
Integer numberHome = null;
Integer numberLeading = null;
Criteria critHome = session.createCriteria(LeadingArticle.class);
critHome.add(Restrictions.eq("mainOrNot", Boolean.FALSE));
critHome.setProjection(Projections.rowCount());
numberHome = ((Number)critHome.uniqueResult()).intValue();
Criteria critLeading = session.createCriteria(LeadingArticle.class);
critLeading.add(Restrictions.eq("mainOrNot", Boolean.TRUE));
critLeading.setProjection(Projections.rowCount());
numberLeading = ((Number)critLeading.uniqueResult()).intValue();
session.getTransaction().commit();
if (la.isMainOrNot()) {
if (numberLeading == 0) {
session.beginTransaction();
session.save(la);
session.getTransaction().commit();
} else {
if (numberHome > 5) {
deleteOldestHome();
updateLeadingToHome();
session.beginTransaction();
session.save(la);
session.getTransaction().commit();
} else {
updateLeadingToHome();
session.beginTransaction();
session.save(la);
session.getTransaction().commit();
}
}
} else {
if (numberHome > 5) {
deleteOldestHome();
session.beginTransaction();
session.save(la);
session.getTransaction().commit();
} else {
session.beginTransaction();
session.save(la);
session.getTransaction().commit();
}
}
} catch (Exception e) {
if (session.getTransaction() != null)
session.getTransaction().rollback();
} finally {
if (session.isOpen())
session.close();
}
return true;
}
public static boolean updateLeadingHomeArticle(long id) {
try {
session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
LeadingArticle l = (LeadingArticle) session.get(LeadingArticle.class, id);
if (l != null)
session.delete(l);
session.getTransaction().commit();
} catch (Exception e) {
if (session.getTransaction() != null)
session.getTransaction().rollback();
} finally {
if (session.isOpen())
session.close();
}
return true;
}
public static List<Category> getCategories() {
List<Category> list = null;
try {
System.out.println("STARTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT");
session = HibernateUtil.getSessionFactory().openSession();
System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
session.beginTransaction();
list = session.createCriteria(Category.class).list();
session.getTransaction().commit();
} catch (Exception e) {
if (session.getTransaction() != null)
session.getTransaction().rollback();
} finally {
if (session.isOpen())
session.close();
}
return list;
}
public static boolean updateCategory(String id, String name) {
try {
session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
int catId = Integer.parseInt(id);
Category cat = (Category) session.get(Category.class, catId);
if (!cat.getName().equals(name)) {
cat.setName(name);
session.update(cat);
}
session.getTransaction().commit();
} catch (Exception e) {
if (session.getTransaction() != null) {
session.getTransaction().rollback();
return false;
}
} finally {
if (session.isOpen())
session.close();
}
return true;
}
public static boolean deleteCategory(String id) {
try {
session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
int catId = Integer.parseInt(id);
Category cat = (Category) session.get(Category.class, catId);
session.delete(cat);
session.getTransaction().commit();
} catch (Exception e) {
if (session.getTransaction() != null) {
session.getTransaction().rollback();
return false;
}
} finally {
if (session.isOpen())
session.close();
}
return true;
}
public static boolean saveCategory(String name) {
try {
session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
Category cat = new Category(name);
session.save(cat);
session.getTransaction().commit();
} catch (Exception e) {
if (session.getTransaction() != null) {
session.getTransaction().rollback();
return false;
}
} finally {
if (session.isOpen())
session.close();
}
return true;
}
public static List<Article> getAllArticles(int page) {
List<Article> list = null;
try {
session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
list = session.createCriteria(Article.class).setFirstResult((page - 1) * Constants.MAX_ARTICLES_ON_PAGE).setMaxResults(Constants.MAX_ARTICLES_ON_PAGE).list();
for (Article a : list)
a.getCategories().size();
session.getTransaction().commit();
} catch (Exception e) {
if (session.getTransaction() != null)
session.getTransaction().rollback();
} finally {
if (session.isOpen())
session.close();
}
return list;
}
public static List<Article> getArticles(int page, String restriction) {
List<Article> list = null;
try {
session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
String sql = "SELECT * FROM ARTICLES WHERE ";
sql += restriction;
SQLQuery query = session.createSQLQuery(sql);
query.addEntity(Article.class);
list = query.setFirstResult((page - 1) * Constants.MAX_ARTICLES_ON_PAGE).setMaxResults(Constants.MAX_ARTICLES_ON_PAGE).list();
for (Article a : list)
a.getCategories().size();
session.getTransaction().commit();
} catch (Exception e) {
if (session.getTransaction() != null)
session.getTransaction().rollback();
} finally {
if (session.isOpen())
session.close();
}
return list;
}
public static int getAllArticlesNumber(){
int result = 0;
try {
session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
result = ((Number)session.createCriteria(Article.class).setProjection(Projections.rowCount()).uniqueResult()).intValue();
session.getTransaction().commit();
} catch (Exception e) {
if (session.getTransaction() != null)
session.getTransaction().rollback();
} finally {
if (session.isOpen())
session.close();
}
return result;
}
public static int getArticlesNumber(String restriction){
int result = 0;
try {
session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
String sql = "SELECT COUNT(*) FROM ARTICLES WHERE ";
sql += restriction;
SQLQuery query = session.createSQLQuery(sql);
result = ((Number)query.uniqueResult()).intValue();
session.getTransaction().commit();
} catch (Exception e) {
if (session.getTransaction() != null)
session.getTransaction().rollback();
} finally {
if (session.isOpen())
session.close();
}
return result;
}
public static Article getLeadingArticle() {
Article leading = null;
try {
session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
LeadingArticle la = (LeadingArticle) session.createCriteria(LeadingArticle.class).add(Restrictions.eq("mainOrNot", Boolean.TRUE)).uniqueResult();
leading = la.getArticle();
session.getTransaction().commit();
} catch (Exception e) {
if (session.getTransaction() != null)
session.getTransaction().rollback();
} finally {
if (session.isOpen())
session.close();
}
return leading;
}
public static List<Article> getHomeArticles() {
List<Article> homeList = new ArrayList<>();
try {
session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
List<LeadingArticle> artList = session.createCriteria(LeadingArticle.class).add(Restrictions.eq("mainOrNot", Boolean.FALSE)).addOrder(Order.desc("id")).list();
for (LeadingArticle l: artList)
homeList.add(l.getArticle());
session.getTransaction().commit();
} catch (Exception e) {
if (session.getTransaction() != null)
session.getTransaction().rollback();
} finally {
if (session.isOpen())
session.close();
}
return homeList;
}
public static List<Map<String,Object>> runSQLQuery(String statement) {
List<Map<String,Object>> resultSet = new ArrayList<>();
Map<String,Object> m = new HashMap<>();
try {
session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
SQLQuery query = session.createSQLQuery(statement);
query.setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE);
query.setFirstResult(0).setMaxResults(Constants.MAX_SQL_RESULT_ON_PAGE);
resultSet = query.list();
session.getTransaction().commit();
} catch (SQLGrammarException me) {
if (session.getTransaction() != null)
session.getTransaction().rollback();
m.put("error_number", -1);
resultSet.add(m);
} catch (HibernateException he) {
if (session.getTransaction() != null)
session.getTransaction().rollback();
m.put("error_number", -2);
resultSet.add(m);
} catch (Exception e) {
if (session.getTransaction() != null)
session.getTransaction().rollback();
m.put("error_number", -99);
resultSet.add(m);
} finally {
if (session.isOpen())
session.close();
}
return resultSet;
}
public static int runSQLUpdate(String statement) {
int result = 0;
try {
session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
SQLQuery query = session.createSQLQuery(statement);
result = query.executeUpdate();
session.getTransaction().commit();
} catch (SQLGrammarException me) {
if (session.getTransaction() != null)
session.getTransaction().rollback();
result = -1;
} catch (HibernateException he) {
if (session.getTransaction() != null)
session.getTransaction().rollback();
result = -2;
} catch (Exception e) {
if (session.getTransaction() != null)
session.getTransaction().rollback();
result = -99;
} finally {
if (session.isOpen())
session.close();
}
return result;
}
public static boolean checkUser(String userName) {
boolean exists = false;
try {
session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
int count = 0;
Criteria critHome = session.createCriteria(User.class).add(Restrictions.eq("userName", userName)).setProjection(Projections.rowCount());
count = ((Number)critHome.uniqueResult()).intValue();
if (count > 0)
exists = true;
session.getTransaction().commit();
} catch (Exception e) {
if (session.getTransaction() != null)
session.getTransaction().rollback();
} finally {
if (session.isOpen())
session.close();
}
return exists;
}
public static boolean saveUser(User user) {
boolean saved = false;
try {
session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
saved = true;
} catch (Exception e) {
if (session.getTransaction() != null)
session.getTransaction().rollback();
saved = false;
} finally {
if (session.isOpen())
session.close();
}
return saved;
}
public static int checkUserLogin(String userName, String pwd) {
try {
session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
User user = (User) session.createCriteria(User.class).add(Restrictions.eq("userName", userName)).add(Restrictions.eq("password", pwd)).uniqueResult();
if (user == null) {
throw new NoSuchUserException();
}
session.getTransaction().commit();
} catch (NoSuchUserException nue) {
if (session.getTransaction() != null) {
session.getTransaction().rollback();
return 0;
}
} catch (Exception e) {
if (session.getTransaction() != null) {
session.getTransaction().rollback();
return -1;
}
} finally {
if (session.isOpen())
session.close();
}
return 1;
}
public static int changeUserPassword(String userName, String pwd) {
try {
session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
User user = (User) session.createCriteria(User.class).add(Restrictions.eq("userName", userName)).uniqueResult();
if (user == null) {
throw new NoSuchUserException();
}
user.setPassword(pwd);
session.saveOrUpdate(user);
session.getTransaction().commit();
} catch (Exception e) {
if (session.getTransaction() != null) {
session.getTransaction().rollback();
return -1;
}
} finally {
if (session.isOpen())
session.close();
}
return 1;
}
/////////////////////////////////
public static void setAdminInitialData() {
try {
System.out.println("RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR");
session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
User user = new User(Constants.ADMIN_USERNAME, "admin@email.hu", true, 1991, PasswordEncryptor.encryptPassword("alma"));
session.saveOrUpdate(user);
session.getTransaction().commit();
} catch (Exception e) {
if (session.getTransaction() != null) {
session.getTransaction().rollback();
}
} finally {
if (session.isOpen())
session.close();
}
}
}
|
package me.jul1an_k.tablist.bukkit.api.impl.tablistapi;
import me.jul1an_k.tablist.api.bukkit.sTablistAPI;
import org.bukkit.entity.Player;
import me.jul1an_k.tablist.bukkit.variables.VariableManager;
import net.glowstone.entity.GlowPlayer;
import net.md_5.bungee.api.chat.TextComponent;
public class TablistAPI_Glowstone extends sTablistAPI {
public void sendTabList(Player player, String header, String footer) {
if(header != null)
header = VariableManager.replaceTab(header, player);
if(footer != null)
footer = VariableManager.replaceTab(footer, player);
((GlowPlayer) player).setPlayerListHeaderFooter(new TextComponent(header), new TextComponent(footer));
}
public void sendActionBar(Player player, String message) {
if(message != null)
message = VariableManager.replace(message, player);
((GlowPlayer) player).sendActionBar(message);
}
public void sendTitle(Player player, String title, String subtitle, int fadein, int stay, int fadeout, boolean clear, boolean reset) {
title = VariableManager.replace(title, player);
subtitle = VariableManager.replace(subtitle, player);
GlowPlayer glowPlayer = (GlowPlayer) player;
glowPlayer.sendTitle(title, subtitle, fadein, stay, fadeout);
if(clear)
glowPlayer.clearTitle();
if(reset)
glowPlayer.resetTitle();
}
public int getPing(Player player) {
//TODO: Fix me
return 0;
}
public String getVersion() {
return "Glowstone";
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package talaash.Indexer;
/**
*
* @author asheesh
*/
public class similarity {
public double similaritymeasure(double[]queryimg,double[]folderimg)
{
double max=0,min=0;
int length=queryimg.length;
int n=length;
double []c=new double[n];
double sim=0;
double alpha[]=new double[n];
double nsqr=n*n;
for(int i=0;i<queryimg.length;i++)
{
c[i]=(((2*i)-1)/nsqr);
alpha[i]=1;
if(queryimg[i]>=folderimg[i])
{
max=queryimg[i];
min=folderimg[i];
if(queryimg[i]!=0&&folderimg[i]!=0)
{
alpha[i]=min/max;
}
else
alpha[i]=1;
}
sim+=(c[i]*alpha[i]);
}
// System.out.println("sim value="+sim);
return sim;
}
}
|
package step._07_String;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.text.ChoiceFormat;
/* date : 2021-07-14 (수)
* author : develiberta
* number : 05622
*
* [단계]
* 07. 문자열
* 문자열을 다루는 문제들을 해결해 봅시다.
* [제목]
* 08. 다이얼 (05622)
* 규칙에 따라 문자에 대응하는 수를 출력하는 문제
* [문제]
* 상근이의 할머니는 아래 그림과 같이 오래된 다이얼 전화기를 사용한다.
* 전화를 걸고 싶은 번호가 있다면, 숫자를 하나를 누른 다음에 금속 핀이 있는 곳 까지 시계방향으로 돌려야 한다.
* 숫자를 하나 누르면 다이얼이 처음 위치로 돌아가고, 다음 숫자를 누르려면 다이얼을 처음 위치에서 다시 돌려야 한다.
* 숫자 1을 걸려면 총 2초가 필요하다. 1보다 큰 수를 거는데 걸리는 시간은 이보다 더 걸리며, 한 칸 옆에 있는 숫자를 걸기 위해선 1초씩 더 걸린다.
* 상근이의 할머니는 전화 번호를 각 숫자에 해당하는 문자로 외운다. 즉, 어떤 단어를 걸 때, 각 알파벳에 해당하는 숫자를 걸면 된다. 예를 들어, UNUCIC는 868242와 같다.
* 할머니가 외운 단어가 주어졌을 때, 이 전화를 걸기 위해서 필요한 최소 시간을 구하는 프로그램을 작성하시오.
* [입력]
* 첫째 줄에 알파벳 대문자로 이루어진 단어가 주어진다. 단어의 길이는 2보다 크거나 같고, 15보다 작거나 같다.
* [출력]
* 첫째 줄에 다이얼을 걸기 위해서 필요한 최소 시간을 출력한다.
* (예제 입력 1)
* WA
* (예제 출력 1)
* 13
* (예제 입력 2)
* UNUCIC
* (예제 출력 2)
* 36
*/
public class _08_05622_Dial {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
String dial = br.readLine();
int second = 0;
// for (int i=0; i<dial.length(); i++) {
// second += 2;
// char ch = dial.charAt(i);
// if (ch <= 'C') {
// second += 1;
// } else if (ch <= 'F') {
// second += 2;
// } else if (ch <= 'I') {
// second += 3;
// } else if (ch <= 'L') {
// second += 4;
// } else if (ch <= 'O') {
// second += 5;
// } else if (ch <= 'S') {
// second += 6;
// } else if (ch <= 'V') {
// second += 7;
// } else {
// second += 8;
// }
// }
//
double[] limits = {'A', 'D', 'G', 'J', 'M', 'P', 'T', 'W'};
String[] seconds = {"3", "4", "5", "6", "7", "8", "9", "10"};
ChoiceFormat form = new ChoiceFormat(limits, seconds);
for (int i=0; i<dial.length(); i++) {
second += Integer.parseInt(form.format(dial.charAt(i)));
}
bw.write("" + second);
br.close();
bw.flush();
bw.close();
}
}
|
public class Account {
public static void account_admin() {
System.out.println("Welcome to the library admin account, please select what option you would like below: ");
}
}
|
package com.company.c4q.unit08practice;
public class ReverseString {
public static void main(String[] args) {
System.out.println(flipItAndReverseIt("Potato Sack"));
}
public static String flipItAndReverseIt(String s) {
String reversed = "";
for (int i = s.length() - 1; i >= 0; i--) {
reversed += "" + s.charAt(i);
}
return reversed;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.