text
stringlengths 10
2.72M
|
|---|
package cl.cehd.ocr.algorithm.entity;
import java.util.Map;
import java.util.Optional;
public class IndividualDigitIdentifier {
private final DigitRepresentationDictionary digitRepresentationDictionary;
public IndividualDigitIdentifier(DigitRepresentationDictionary accountDigitRepresentationDictionary) {
this.digitRepresentationDictionary = accountDigitRepresentationDictionary;
}
public String readDigitValue(AccountDigit accountDigit) {
Map<AccountDigit, String> accountDigitToDigitMap = digitRepresentationDictionary.createNumberFactory();
return Optional.ofNullable(accountDigitToDigitMap.get(accountDigit)).orElse("?");
}
}
|
package Termin2;
import java.util.Scanner;
public class Switch {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Bitte geben Sie einen Wochentag ein");
String dayOfWeek = scanner.nextLine();
scanner.close();
System.out.println("Methode liefert: " + getDayOfWeekId(dayOfWeek));
}
public static int getDayOfWeekId(String dayOfWeek) {
switch (dayOfWeek.toLowerCase()) { // in Kleinbuchstaben umwandeln, damit User sowohl klein als auch groß schreiben kann
case "montag": return 0;
case "dienstag": return 1;
case "mittwoch": return 2;
case "donnerstag": return 3;
case "freitag": return 4;
case "samstag": return 5;
case "sonntag": return 6;
default: return -1;
}
}
}
|
package slimeknights.tconstruct.library.utils;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import slimeknights.tconstruct.library.modifiers.ModifierNBT;
public class ModifierTagHolder {
private final ItemStack itemStack;
private final NBTTagList tagList;
private final int index;
public final NBTTagCompound tag;
private ModifierNBT modifierNBT;
private ModifierTagHolder(ItemStack itemStack, String modifier) {
this.itemStack = itemStack;
this.tagList = TagUtil.getModifiersTagList(itemStack);
this.index = TinkerUtil.getIndexInCompoundList(tagList, modifier);
this.tag = tagList.getCompoundTagAt(index);
}
public <T extends ModifierNBT> T getTagData(Class<T> clazz) {
T data = ModifierNBT.readTag(tag, clazz);
modifierNBT = data;
return data;
}
public void save() {
if(modifierNBT != null) {
modifierNBT.write(tag);
}
tagList.set(index, tag);
TagUtil.setModifiersTagList(itemStack, tagList);
}
public static ModifierTagHolder getModifier(ItemStack itemStack, String modifier) {
return new ModifierTagHolder(itemStack, modifier);
}
}
|
package be.openclinic.medical;
import be.mxs.common.util.db.MedwanQuery;
import be.mxs.common.util.system.Debug;
import be.mxs.common.util.system.ScreenHelper;
import be.openclinic.common.OC_Object;
import net.admin.AdminPerson;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.Vector;
public class Problem extends OC_Object {
private AdminPerson patient;
private String patientuid;
private String codeType;
private String code;
private String comment;
private Date begin;
private Date end;
private int gravity;
private int certainty;
public Problem(String patientuid, String codeType, String code, String comment, Date begin, Date end) {
this.patientuid = patientuid;
this.codeType = codeType;
this.code = code;
this.comment = comment;
this.begin = begin;
this.end = end;
}
public Problem(){
super();
}
public AdminPerson getPatient() {
if(patient==null && patientuid!=null){
Connection ad_conn = MedwanQuery.getInstance().getAdminConnection();
patient = AdminPerson.getAdminPerson(ad_conn,patientuid);
try {
ad_conn.close();
}
catch (SQLException e) {
e.printStackTrace();
}
}
return patient;
}
public void setPatient(AdminPerson patient) {
this.patient = patient;
}
public String getCodeType() {
return codeType;
}
public void setCodeType(String codeType) {
this.codeType = codeType;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public Date getBegin() {
return begin;
}
public void setBegin(Date begin) {
this.begin = begin;
}
public Date getEnd() {
return end;
}
public void setEnd(Date end) {
this.end = end;
}
public String getPatientuid() {
return patientuid;
}
public void setPatientuid(String patientuid) {
this.patientuid = patientuid;
}
public int getGravity() {
return gravity;
}
public void setGravity(int gravity) {
this.gravity = gravity;
}
public int getCertainty() {
return certainty;
}
public void setCertainty(int certainty) {
this.certainty = certainty;
}
public void store(){
PreparedStatement ps;
ResultSet rs;
String sSelect,sInsert,sDelete;
int iVersion = 1;
String ids[];
Connection oc_conn=MedwanQuery.getInstance().getOpenclinicConnection();
try{
if(this.getUid()!=null && this.getUid().length() >0){
ids = this.getUid().split("\\.");
if(ids.length == 2){
sSelect = " SELECT * FROM OC_PROBLEMS " +
" WHERE OC_PROBLEM_SERVERID = ? " +
" AND OC_PROBLEM_OBJECTID = ?";
ps = oc_conn.prepareStatement(sSelect);
ps.setInt(1,Integer.parseInt(ids[0]));
ps.setInt(2,Integer.parseInt(ids[1]));
rs = ps.executeQuery();
if(rs.next()){
iVersion = rs.getInt("OC_PROBLEM_VERSION") + 1;
}
rs.close();
ps.close();
sInsert = " INSERT INTO OC_PROBLEMS_HISTORY " +
" SELECT OC_PROBLEM_PATIENTUID," +
" OC_PROBLEM_CODETYPE," +
" OC_PROBLEM_CODE," +
" OC_PROBLEM_BEGIN," +
" OC_PROBLEM_END," +
" OC_PROBLEM_SERVERID," +
" OC_PROBLEM_OBJECTID," +
" OC_PROBLEM_CREATETIME," +
" OC_PROBLEM_UPDATETIME," +
" OC_PROBLEM_UPDATEUID," +
" OC_PROBLEM_VERSION," +
" OC_PROBLEM_GRAVITY," +
" OC_PROBLEM_CERTAINTY," +
" OC_PROBLEM_COMMENT" +
" FROM OC_PROBLEMS " +
" WHERE OC_PROBLEM_SERVERID = ?" +
" AND OC_PROBLEM_OBJECTID = ?";
ps = oc_conn.prepareStatement(sInsert);
ps.setInt(1,Integer.parseInt(ids[0]));
ps.setInt(2,Integer.parseInt(ids[1]));
ps.executeUpdate();
ps.close();
sDelete = " DELETE FROM OC_PROBLEMS " +
" WHERE OC_PROBLEM_SERVERID = ? " +
" AND OC_PROBLEM_OBJECTID = ? ";
ps = oc_conn.prepareStatement(sDelete);
ps.setInt(1,Integer.parseInt(ids[0]));
ps.setInt(2,Integer.parseInt(ids[1]));
ps.executeUpdate();
ps.close();
}
}
else{
ids = new String[] {MedwanQuery.getInstance().getConfigString("serverId"),MedwanQuery.getInstance().getOpenclinicCounter("OC_PROBLEMS")+""};
}
if(ids.length == 2){
sInsert = " INSERT INTO OC_PROBLEMS" +
"(" +
" OC_PROBLEM_SERVERID," +
" OC_PROBLEM_OBJECTID," +
" OC_PROBLEM_CODETYPE," +
" OC_PROBLEM_CODE," +
" OC_PROBLEM_CERTAINTY," +
" OC_PROBLEM_GRAVITY," +
" OC_PROBLEM_BEGIN," +
" OC_PROBLEM_END," +
" OC_PROBLEM_PATIENTUID," +
" OC_PROBLEM_COMMENT," +
" OC_PROBLEM_CREATETIME," +
" OC_PROBLEM_UPDATETIME," +
" OC_PROBLEM_UPDATEUID," +
" OC_PROBLEM_VERSION" +
") " +
" VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
ps = oc_conn.prepareStatement(sInsert);
ps.setInt(1,Integer.parseInt(ids[0]));
ps.setInt(2,Integer.parseInt(ids[1]));
ps.setString(3,this.getCodeType());
ps.setString(4,this.getCode());
ps.setInt(5,this.getCertainty());
ps.setInt(6,this.getGravity());
if(this.getBegin() == null){
ps.setNull(7, java.sql.Types.TIMESTAMP);
}else{
ps.setTimestamp(7, new Timestamp(this.getBegin().getTime()));
}
if(this.getEnd() == null){
ps.setNull(8, java.sql.Types.TIMESTAMP);
}else{
ps.setTimestamp(8, new Timestamp(this.getEnd().getTime()));
}
if(this.getPatient() != null){
ps.setString(9,ScreenHelper.checkString(this.getPatient().personid));
}else{
ps.setString(9,"");
}
ps.setString(10,this.getComment());
if(this.getCreateDateTime() != null){
ps.setTimestamp(11,new Timestamp(this.getCreateDateTime().getTime()));
}else{
ps.setTimestamp(11,new Timestamp(ScreenHelper.getSQLDate(ScreenHelper.getDate()).getTime()));
}
ps.setTimestamp(12,new Timestamp(new java.util.Date().getTime()));
ps.setString(13,this.getUpdateUser());
ps.setInt(14,iVersion);
ps.executeUpdate();
ps.close();
this.setUid(ids[0] + "." + ids[1]);
}
}
catch(Exception e){
Debug.println("OpenClinic => Problem.java => store => "+e.getMessage());
e.printStackTrace();
}
try {
oc_conn.close();
}
catch (SQLException e) {
e.printStackTrace();
}
}
public static Problem get(String uid){
PreparedStatement ps;
ResultSet rs;
Problem problem = new Problem();
if(uid != null && uid.length() > 0){
String sUids[] = uid.split("\\.");
if(sUids.length == 2){
Connection oc_conn=MedwanQuery.getInstance().getOpenclinicConnection();
try{
String sSelect = "SELECT * FROM OC_PROBLEMS "+
" WHERE OC_PROBLEM_SERVERID = ?"+
" AND OC_PROBLEM_OBJECTID = ?";
ps = oc_conn.prepareStatement(sSelect);
ps.setInt(1,Integer.parseInt(sUids[0]));
ps.setInt(2,Integer.parseInt(sUids[1]));
rs = ps.executeQuery();
if(rs.next()){
problem.patientuid = ScreenHelper.checkString(rs.getString("OC_PROBLEM_PATIENTUID"));
problem.setUid(ScreenHelper.checkString(rs.getString("OC_PROBLEM_SERVERID")) + "." + ScreenHelper.checkString(rs.getString("OC_PROBLEM_OBJECTID")));
problem.setCreateDateTime(rs.getTimestamp("OC_PROBLEM_CREATETIME"));
problem.setUpdateDateTime(rs.getTimestamp("OC_PROBLEM_UPDATETIME"));
problem.setUpdateUser(ScreenHelper.checkString(rs.getString("OC_PROBLEM_UPDATEUID")));
problem.setVersion(rs.getInt("OC_PROBLEM_VERSION"));
problem.setBegin(rs.getDate("OC_PROBLEM_BEGIN"));
problem.setEnd(rs.getDate("OC_PROBLEM_END"));
problem.setCodeType(ScreenHelper.checkString(rs.getString("OC_PROBLEM_CODETYPE")));
problem.setCode(ScreenHelper.checkString(rs.getString("OC_PROBLEM_CODE")));
problem.setComment(ScreenHelper.checkString(rs.getString("OC_PROBLEM_COMMENT")));
problem.setGravity(rs.getInt("OC_PROBLEM_GRAVITY"));
problem.setCertainty(rs.getInt("OC_PROBLEM_CERTAINTY"));
}
rs.close();
ps.close();
}
catch(Exception e){
Debug.println("OpenClinic =>Problem.java => get => "+e.getMessage());
e.printStackTrace();
}
try {
oc_conn.close();
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
return problem;
}
//--- DELETE ----------------------------------------------------------------------------------
public void delete(){
PreparedStatement ps;
String ids[];
String sInsert,sDelete;
Connection oc_conn = MedwanQuery.getInstance().getOpenclinicConnection();
try{
if(this.getUid() != null && this.getUid().length() > 0){
ids = this.getUid().split("\\.");
if(ids.length == 2){
sInsert = " INSERT INTO OC_PROBLEMS_HISTORY " +
" SELECT OC_PROBLEM_PATIENTUID," +
" OC_PROBLEM_CODETYPE," +
" OC_PROBLEM_CODE," +
" OC_PROBLEM_BEGIN," +
" OC_PROBLEM_END," +
" OC_PROBLEM_SERVERID," +
" OC_PROBLEM_OBJECTID," +
" OC_PROBLEM_CREATETIME," +
" OC_PROBLEM_UPDATETIME," +
" OC_PROBLEM_UPDATEUID," +
" OC_PROBLEM_VERSION," +
" OC_PROBLEM_GRAVITY," +
" OC_PROBLEM_CERTAINTY," +
" OC_PROBLEM_COMMENT" +
" FROM OC_PROBLEMS " +
" WHERE OC_PROBLEM_SERVERID = ?" +
" AND OC_PROBLEM_OBJECTID = ?";
ps = oc_conn.prepareStatement(sInsert);
ps.setInt(1,Integer.parseInt(ids[0]));
ps.setInt(2,Integer.parseInt(ids[1]));
ps.executeUpdate();
ps.close();
sDelete = " DELETE FROM OC_PROBLEMS " +
" WHERE OC_PROBLEM_SERVERID = ? " +
" AND OC_PROBLEM_OBJECTID = ? ";
ps = oc_conn.prepareStatement(sDelete);
ps.setInt(1,Integer.parseInt(ids[0]));
ps.setInt(2,Integer.parseInt(ids[1]));
ps.executeUpdate();
ps.close();
}
}
}
catch(Exception e){
e.printStackTrace();
}
// close connection
try{
oc_conn.close();
}
catch(SQLException e){
e.printStackTrace();
}
}
public static Vector selectProblems(String serverID, String objectID, String codeType, String code, String comment,
String patientID, String beginDate, String endDate, String certainty,
String gravity, String sortColumn){
Vector vProblems = new Vector();
PreparedStatement ps;
ResultSet rs;
String sConditions = "";
String sSelect = "SELECT * FROM OC_PROBLEMS ";
if(serverID.length() > 0) {sConditions += " OC_PROBLEM_SERVERID = ? AND";}
if(objectID.length() > 0) {sConditions += " OC_PROBLEM_OBJECTID = ? AND";}
if(certainty.length() > 0) {sConditions += " OC_PROBLEM_CERTAINTY = ? AND";}
if(gravity.length() > 0) {sConditions += " OC_PROBLEM_GRAVITY = ? AND";}
if(codeType.length() > 0) {sConditions += " " + MedwanQuery.getInstance().getConfigString("lowerCompare").replaceAll("<param>","OC_PROBLEM_CODETYPE") + " LIKE ? AND";}
if(code.length() > 0) {sConditions += " " + MedwanQuery.getInstance().getConfigString("lowerCompare").replaceAll("<param>","OC_PROBLEM_CODE") + " LIKE ? AND";}
if(comment.length() > 0) {sConditions += " " + MedwanQuery.getInstance().getConfigString("lowerCompare").replaceAll("<param>","OC_PROBLEM_COMMENT") + " LIKE ? AND";}
if(patientID.length() > 0) {sConditions += " OC_PROBLEM_PATIENTUID = ? AND";}
if(beginDate.length() > 0) {sConditions += " OC_PROBLEM_BEGIN <= ? AND";}
if(endDate.length() > 0) {sConditions += " (OC_PROBLEM_END IS NULL OR OC_PROBLEM_END >= ?) AND";}
if(sConditions.length() > 0){
sSelect += " WHERE " + sConditions;
sSelect = sSelect.substring(0,sSelect.length()-3);
}
if(sortColumn.length() > 0){
sSelect += " ORDER BY " + sortColumn;
}
Connection oc_conn = MedwanQuery.getInstance().getOpenclinicConnection();
try{
int i = 1;
ps = oc_conn.prepareStatement(sSelect);
if(serverID.length() > 0) {ps.setInt(i++,Integer.parseInt(serverID));}
if(objectID.length() > 0) {ps.setInt(i++,Integer.parseInt(objectID));}
if(certainty.length() > 0) {ps.setInt(i++,Integer.parseInt(certainty));}
if(gravity.length() > 0) {ps.setInt(i++,Integer.parseInt(gravity));}
if(codeType.length() > 0) {ps.setString(i++,codeType.toLowerCase() + "%");}
if(code.length() > 0) {ps.setString(i++,code.toLowerCase() +"%");}
if(comment.length() > 0) {ps.setString(i++,"%" + comment.toLowerCase() + "%");}
if(patientID.length() > 0) {ps.setString(i++,patientID);}
if(beginDate.length() > 0) {ps.setTimestamp(i++,new Timestamp(ScreenHelper.getSQLDate(beginDate).getTime()));}
if(endDate.length() > 0) {ps.setTimestamp(i++,new Timestamp(ScreenHelper.getSQLDate(endDate).getTime()));}
rs = ps.executeQuery();
Problem pTmp;
String sUID;
while(rs.next()){
pTmp = new Problem();
sUID = ScreenHelper.checkString(rs.getString("OC_PROBLEM_SERVERID")) + "." + ScreenHelper.checkString(rs.getString("OC_PROBLEM_OBJECTID"));
pTmp.setUid(sUID);
pTmp.setCodeType(ScreenHelper.checkString(rs.getString("OC_PROBLEM_CODETYPE")));
pTmp.setCode(ScreenHelper.checkString(rs.getString("OC_PROBLEM_CODE")));
pTmp.setComment(ScreenHelper.checkString(rs.getString("OC_PROBLEM_COMMENT")));
pTmp.setPatientuid(ScreenHelper.checkString(rs.getString("OC_PROBLEM_PATIENTUID")));
pTmp.setCertainty(rs.getInt("OC_PROBLEM_CERTAINTY"));
pTmp.setGravity(rs.getInt("OC_PROBLEM_GRAVITY"));
pTmp.setBegin(rs.getDate("OC_PROBLEM_BEGIN"));
pTmp.setEnd(rs.getDate("OC_PROBLEM_END"));
vProblems.addElement(pTmp);
}
rs.close();
ps.close();
}
catch(Exception e){
e.printStackTrace();
}
// close connection
try{
oc_conn.close();
}
catch(SQLException e){
e.printStackTrace();
}
return vProblems;
}
//--- GET ACTIVE PROBLEMS ---------------------------------------------------------------------
public static Vector getActiveProblems(String personid){
Vector activeProblems = new Vector();
Connection conn = MedwanQuery.getInstance().getOpenclinicConnection();
PreparedStatement ps = null;
ResultSet rs = null;
try{
String sSql = "SELECT * FROM OC_PROBLEMS"+
" WHERE OC_PROBLEM_PATIENTUID = ?"+
" AND (OC_PROBLEM_END IS NULL OR OC_PROBLEM_END > ?)"+
" ORDER BY OC_PROBLEM_BEGIN DESC";
ps = conn.prepareStatement(sSql);
ps.setString(1,personid);
ps.setDate(2,new java.sql.Date(new java.util.Date().getTime()));
rs = ps.executeQuery();
while(rs.next()){
activeProblems.add(new Problem(rs.getString("OC_PROBLEM_PATIENTUID"),
rs.getString("OC_PROBLEM_CODETYPE"),
rs.getString("OC_PROBLEM_CODE"),
rs.getString("OC_PROBLEM_COMMENT"),
rs.getDate("OC_PROBLEM_BEGIN"),
rs.getDate("OC_PROBLEM_END")));
}
}
catch(SQLException e){
e.printStackTrace();
}
finally{
try{
if(rs!=null) rs.close();
if(ps!=null) ps.close();
}
catch(Exception e){
e.printStackTrace();
}
}
// close connection
try{
conn.close();
}
catch(SQLException e){
e.printStackTrace();
}
return activeProblems;
}
//--- GET INACTIVE PROBLEMS -------------------------------------------------------------------
public static Vector getInactiveProblems(String personid){
Vector inactiveProblems = new Vector();
Connection conn = MedwanQuery.getInstance().getOpenclinicConnection();
PreparedStatement ps = null;
ResultSet rs = null;
try{
String sSql = "SELECT * FROM OC_PROBLEMS"+
" WHERE OC_PROBLEM_PATIENTUID = ?"+
" AND OC_PROBLEM_END IS NOT NULL AND OC_PROBLEM_END <= ?"+ // difference
" ORDER BY OC_PROBLEM_BEGIN DESC";
ps = conn.prepareStatement(sSql);
ps.setString(1,personid);
ps.setDate(2,new java.sql.Date(new java.util.Date().getTime()));
rs = ps.executeQuery();
while(rs.next()){
inactiveProblems.add(new Problem(rs.getString("OC_PROBLEM_PATIENTUID"),
rs.getString("OC_PROBLEM_CODETYPE"),
rs.getString("OC_PROBLEM_CODE"),
rs.getString("OC_PROBLEM_COMMENT"),
rs.getDate("OC_PROBLEM_BEGIN"),
rs.getDate("OC_PROBLEM_END")));
}
}
catch(SQLException e){
e.printStackTrace();
}
finally{
try{
if(rs!=null) rs.close();
if(ps!=null) ps.close();
}
catch(Exception e){
e.printStackTrace();
}
}
// close connection
try{
conn.close();
}
catch(SQLException e){
e.printStackTrace();
}
return inactiveProblems;
}
}
|
package com.kuang.controller;
import com.alibaba.fastjson.JSONObject;
import com.kuang.utils.EditormdFileUpload;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
@Controller
@RequestMapping("/blog")
public class BlogController {
@GetMapping("/toBlogIndex")
public String toBlogIndex(){
return "views/blog/index";
}
@GetMapping("/toArticle")
public String toArticle(){
return "views/blog/article";
}
@GetMapping("/toPostArticle")
public String toPostArticle(){
return "views/blog/postblog";
}
//文件上传回调() editormd
@RequestMapping("/file/upload")
@ResponseBody
public static JSONObject fileUpload(@RequestParam(value = "editormd-image-file", required = true) MultipartFile file, HttpServletRequest request) throws IOException {
return EditormdFileUpload.fileUpload(file,request);
}
}
|
//package treinamentojava.file;
//
//import java.io.File;
//import java.io.FileNotFoundException;
//import java.math.BigDecimal;
//import java.util.Scanner;
//
//import treinamentojava.temp.Util;
//
//public class ReadFile {
//
// public static void main(String[] args) {
// try {
//
//// BigDecimal teste = new BigDecimal(123422345);
//// String retorno = Util.removerPontoERetornarCom2CasasDecimais(teste);
//// System.out.println("A" + retorno + "A");
////
//// String teste2 = Util.removeAllExceptNumbers((1) + "");
//// System.out.println(teste2);
////
//// if (true) {
//// return;
//// }
////
//
// File myObj = new File("res/PG07072020.REM");
// Scanner myReader = new Scanner(myObj);
//
// BigDecimal somatorio = BigDecimal.ZERO;
//
// int i = 0;
// while (myReader.hasNextLine()) {
// i++;
// String linha = myReader.nextLine();
//
// //if (i > 2) {
// if (i >= 1787) {
// break;
// }
// else if (i == 1) {
// continue;
// }
//
// //System.out.println(data);
// //String valor = linha.substring(195, 204);
// String valor2 = linha.substring((195 - 1), 202) + "." + linha.substring((203 -1), 204);
// //System.out.println(valor2);
//
// if (!valor2.contains("2964.08")) {
// System.out.println(valor2);
// }
//
// BigDecimal bigDecimalValor = new BigDecimal(valor2);
//
// somatorio = somatorio.add(bigDecimalValor);
//
// }
//
// myReader.close();
//
//// System.out.println(somatorio);
////
//// System.out.println("double value:");
//// System.out.println(somatorio.doubleValue());
//
// // Total dos Valores de pagamento
// String valorDocumento = Util.removeAllExceptNumbers(somatorio.doubleValue() + "");
// System.out.println("valorDocumento:" + valorDocumento);
// Integer valorTotalPagamento = Integer.parseInt(valorDocumento);
// String valorTotal = valorTotalPagamento.toString();
//
// while (valorTotal.length() < 17) {
// valorTotal = "0" + valorTotal;
// }
// System.out.println(valorTotal);
//
// ///
// ///
// ///
// // Total dos Valores de pagamento
//// String valorDocumento2 = Util.removerPontoERetornarCom2CasasDecimais(somatorio);
//// System.out.println("valorDocumento:" + valorDocumento2);
//// Integer valorTotalPagamento2 = Integer.parseInt(valorDocumento2);
//// String valorTotal2 = valorTotalPagamento2.toString();
////
//// while (valorTotal2.length() < 17) {
//// valorTotal2 = "0" + valorTotal2;
//// }
//// System.out.println(valorTotal2);
//
//
// } catch (FileNotFoundException e) {
// System.out.println("An error occurred.");
// e.printStackTrace();
// }
// }
//}
|
package com.getkhaki.api.bff.persistence.models;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
@Entity
@Getter
@Setter
@Accessors(chain = true)
public class EmailDao extends EntityBaseDao {
@Column(nullable = false)
String user;
@ManyToOne(optional = false)
DomainDao domain;
@ManyToMany
@JoinTable(joinColumns = {@JoinColumn(unique = true)}, inverseJoinColumns = {@JoinColumn})
List<PersonDao> people = new ArrayList<>();
@ManyToMany
Set<FlagDao> flags = new HashSet<>();
@Transient
public EmailDao setPerson(PersonDao person) {
this.getPeople().clear();
this.getPeople().add(person);
return this;
}
@Transient
public Optional<PersonDao> getPerson() {
return getPeople().stream().findFirst();
}
@Transient
public String getEmailString() {
return getUser() + "@" + getDomain().getName();
}
}
|
package com.techelevator;
import java.util.Scanner;
public class UserInput {
private static Scanner scanner = new Scanner(System.in);
/**
* @return a string of input provided by the user.
*/
public static String get() {
return scanner.nextLine();
}
/**
* @param prompt the prompt to output to the user
* @return a string of input provided by the user
*/
public static String get(String prompt) {
Printer.print(prompt);
return scanner.nextLine();
}
}
|
package com.logzc.webzic.annotation;
/**
* Created by lishuang on 2016/7/21.
*/
public class TestBean0 {
}
|
package moon_lander;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
/**
* Landing area where rocket will land.
*
* @author www.gametutorial.net
*/
public class Asteroid {
/**
* X coordinate of the landing area.
*/
public int x;
/**
* Y coordinate of the landing area.
*/
public int y;
/**
* Image of landing area.
*/
public static BufferedImage asteroidImg;
/**
* Width of landing area.
*/
public int asteroidImgWidth;
public int asteroidImgHeight;
public Asteroid()
{
Initialize();
LoadContent();
}
private void Initialize()
{
Random rand = new Random();
// X coordinate of the landing area is at 46% frame width.
x = rand.nextInt((Framework.frameWidth - 50) + 1) + 50;
// Y coordinate of the landing area is at 86% frame height.
y = rand.nextInt((835 - 100) + 1) + 50;
}
private void LoadContent()
{
try
{
URL landingAreaImgUrl = this.getClass().getResource("/moon_lander/resources/images/asteroid.png");
asteroidImg = ImageIO.read(landingAreaImgUrl);
asteroidImg.getScaledInstance(100, 95, Image.SCALE_DEFAULT);
asteroidImgWidth = asteroidImg.getWidth();
asteroidImgHeight = asteroidImg.getHeight();
}
catch (IOException ex) {
Logger.getLogger(Asteroid.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void Draw(Graphics2D g2d)
{
g2d.drawImage(asteroidImg, x, y, null);
}
}
|
package com.netcracker.app.domain.shop.repositories;
import com.netcracker.app.domain.shop.entities.Tech;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
@Repository
public interface TechRepository extends DevicesRepository<Tech> {
@Query("select m from Tech m where m.name like :name")
Iterable<Tech> getAllByName(@Param("name") String pointName);
@Query("select m from Tech m where m.id = :id")
Tech getById(@Param("id") int id);
}
|
package com.common.pdf;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;
import com.common.pdf.mode.XmlMode;
import com.common.pdf.util.LoadConfig;
import com.common.pdf.util.UtilConfiguration;
import com.common.pdf.xml.XmlMsg;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
public class CreatPdfUtils
{
private static Map<String, String> creatMap(ArrayList<XmlMode> alx, String MsgConfigName)
{
Map map = new HashMap();
String TrsDateName = UtilConfiguration.getValueByParam("TrsDate", MsgConfigName);
String TrsTimeName = UtilConfiguration.getValueByParam("TrsTime", MsgConfigName);
String AmountName = UtilConfiguration.getValueByParam("Amount", MsgConfigName);
String BigNumName = UtilConfiguration.getValueByParam("BigNum", MsgConfigName);
String TrsDateV1Name = UtilConfiguration.getValueByParam("TrsDateV1", MsgConfigName);
String PrintCountName = UtilConfiguration.getValueByParam("PrintCount", MsgConfigName);
String TrsDateValue = null;
String TrsTimeValue = null;
String BigNumValue = null;
String PrintCountValue = "1";
for (XmlMode xm : alx)
{
if (TrsDateName.equals(xm.getXmlName())) {
TrsDateValue = xm.getXmlValue();
} else if (TrsTimeName.equals(xm.getXmlName())) {
TrsTimeValue = xm.getXmlValue();
}
else if (AmountName.equals(xm.getXmlName())) {
map.put(xm.getXmlName(), xm.getXmlValue());
if( !StringUtils.isBlank(xm.getXmlValue())){
BigNumValue = digitUppercase(Double.parseDouble(xm.getXmlValue()));
}
}
else {
if (BigNumName.equals(xm.getXmlName())) {
continue;
}
if (PrintCountName.equals(xm.getXmlName())) {
map.put(xm.getXmlName(), PrintCountValue);
}
else if (TrsDateV1Name.equals(xm.getXmlName()))
map.put(xm.getXmlName(), getNowDate("yyyy-MM-dd HH:mm:ss"));
else {
map.put(xm.getXmlName(), xm.getXmlValue());
}
}
}
map.put(BigNumName, BigNumValue);
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
try {
if( !StringUtils.isBlank(TrsDateValue)){
TrsDateValue = sdf1.format(parseDate(TrsDateValue));
}
}
catch (ParseException e) {
e.printStackTrace();
}
map.put(TrsDateName, TrsDateValue + " " + TrsTimeValue);
map.put("DebitMark", "0");
return map;
}
public static Date parseDate(String s)
throws ParseException
{
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMdd");
return sdf1.parse(s);
}
public static String getNowDate(String dateType)
{
Date date = new Date();
SimpleDateFormat sdf1 = new SimpleDateFormat(dateType);
return sdf1.format(date);
}
public static String digitUppercase(double n)
{
String[] fraction = { "角", "分" };
String[] digit = { "零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖" };
String[][] unit = { { "元", "万", "亿" }, { "", "拾", "佰", "仟" } };
String head = (n < 0.0D) ? "负" : "";
n = Math.abs(n);
String s = "";
for (int i = 0; i < fraction.length; ++i) {
s = s + new StringBuilder(String.valueOf(digit[(int)(Math.floor(n * 10.0D * Math.pow(10.0D, i)) % 10.0D)])).append(fraction[i]).toString().replaceAll("(零.)+", "");
}
if (s.length() < 1) {
s = "整";
}
int integerPart = (int)Math.floor(n);
for (int i = 0; (i < unit[0].length) && (integerPart > 0); ++i) {
String p = "";
for (int j = 0; (j < unit[1].length) && (n > 0.0D); ++j) {
p = digit[(integerPart % 10)] + unit[1][j] + p;
integerPart /= 10;
}
s = p.replaceAll("(零.)*零$", "").replaceAll("^$", "零") + unit[0][i] + s;
}
return head + s.replaceAll("(零.)*零元", "元").replaceFirst("(零.)+", "").replaceAll("(零.)+", "零").replaceAll("^整$",
"零元整");
}
public static ArrayList<Object> creatPdF(byte[] msg, String MsgPropertiesName, String coding, String PDFPropertiesName, String pdfName)
{
String Name = null;
ArrayList alx = LoadConfig.GetXmlMode(MsgPropertiesName);
alx = XmlMsg.GetXMLValues(msg, alx, coding);
String pdfPath = System.getProperty("user.dir") + "/";
if (pdfName.equals("")) {
Name = getNowDate("yyyyMMddHHmmss") + ".pdf";
System.out.println("pdfname为默认规则");
} else {
Name = pdfName;
System.out.println("pdfname可配置规则");
}
ArrayList file = creatPdfReceipt(alx, pdfPath, MsgPropertiesName, Name);
return file;
}
public static ArrayList<Object> creatPdfReceipt(ArrayList<XmlMode> alx, String PDFPath, String MsgPropertiesName, String pdfName)
{
ArrayList alFile = new ArrayList();
ByteArrayOutputStream os = null;
Configuration cfg = new Configuration();
try
{
System.out.println("读取模板存放路径[" + PDFPath + "]");
cfg.setDirectoryForTemplateLoading(new File(PDFPath + "src/main/java/com/common/pdf/pdfmodel"));
cfg.setDefaultEncoding("UTF-8");
Template temp = cfg.getTemplate("newslinkmail2.ftl");
Writer writer = new StringWriter();
temp.process(creatMap(alx, MsgPropertiesName), writer);
String EmailText = writer.toString();
ITextRenderer renderer = new ITextRenderer();
ITextFontResolver fontResolver = renderer.getFontResolver();
System.out.println("载入字体[" + PDFPath + "src/main/java/com/common/pdf/pdfmodel/" + "simsun.ttc]");
fontResolver.addFont(PDFPath + "src/main/java/com/common/pdf/pdfmodel/" + "simsun.ttc", "Identity-H", false);
renderer.setDocumentFromString(EmailText);
System.out.println("载入印章[" + PDFPath + "pictures/]");
renderer.getSharedContext().setBaseURL("file:///" + PDFPath + "pictures/");
renderer.layout();
os = new ByteArrayOutputStream();
renderer.createPDF(os);
os.flush();
alFile.add(pdfName);
alFile.add(os.toByteArray());
System.out.println("生成PDF文件[" + pdfName + "]");
}
catch (IOException e)
{
System.out.println("未找到模板存放路径" + e);
} catch (TemplateException e) {
System.out.println("temp.process(addMap(), out)步骤异常" + e);
} catch (Exception e) {
System.out.println("生成dpf异常" + e);
}
finally {
try {
os.close();
}
catch (IOException e) {
System.out.println("关闭流时发生异常" + e);
}
}
return alFile;
}
public static void saveFile(String filename, byte[] data)
throws Exception
{
if (data == null)
return;
String filepath = System.getProperty("user.dir") + "/" + filename;
System.out.println("File:" + filepath);
File file = new File(filepath);
if (file.exists()) {
file.delete();
}
FileOutputStream fos = new FileOutputStream(file);
fos.write(data, 0, data.length);
fos.flush();
fos.close();
}
}
|
/**
* MIT License
* <p>
* Copyright (c) 2019-2022 nerve.network
* <p>
* 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:
* <p>
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* <p>
* 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 network.nerve.converter.core.validator;
import io.nuls.base.basic.AddressTool;
import io.nuls.base.data.*;
import io.nuls.core.constant.TxType;
import io.nuls.core.core.annotation.Autowired;
import io.nuls.core.core.annotation.Component;
import io.nuls.core.exception.NulsException;
import io.nuls.core.model.StringUtils;
import network.nerve.converter.config.ConverterContext;
import network.nerve.converter.constant.ConverterErrorCode;
import network.nerve.converter.core.api.ConverterCoreApi;
import network.nerve.converter.core.heterogeneous.docking.interfaces.IHeterogeneousChainDocking;
import network.nerve.converter.core.heterogeneous.docking.management.HeterogeneousDockingManager;
import network.nerve.converter.enums.HeterogeneousTxTypeEnum;
import network.nerve.converter.enums.ProposalTypeEnum;
import network.nerve.converter.helper.HeterogeneousAssetHelper;
import network.nerve.converter.manager.ChainManager;
import network.nerve.converter.model.bo.*;
import network.nerve.converter.model.po.ConfirmWithdrawalPO;
import network.nerve.converter.model.po.ProposalPO;
import network.nerve.converter.model.txdata.OneClickCrossChainTxData;
import network.nerve.converter.model.txdata.RechargeTxData;
import network.nerve.converter.model.txdata.WithdrawalAddFeeByCrossChainTxData;
import network.nerve.converter.rpc.call.TransactionCall;
import network.nerve.converter.storage.ConfirmWithdrawalStorageService;
import network.nerve.converter.storage.ProposalStorageService;
import network.nerve.converter.storage.RechargeStorageService;
import network.nerve.converter.utils.ConverterUtil;
import network.nerve.converter.utils.HeterogeneousUtil;
import network.nerve.converter.utils.VirtualBankUtil;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.List;
/**
* 充值交易业务验证器
* (创建交易后)
*
* @author: Loki
* @date: 2020/4/15
*/
@Component
public class RechargeVerifier {
@Autowired
private ChainManager chainManager;
@Autowired
private HeterogeneousDockingManager heterogeneousDockingManager;
@Autowired
private ProposalStorageService proposalStorageService;
@Autowired
private HeterogeneousAssetHelper heterogeneousAssetHelper;
@Autowired
private RechargeStorageService rechargeStorageService;
@Autowired
private ConverterCoreApi converterCoreApi;
@Autowired
private ConfirmWithdrawalStorageService confirmWithdrawalStorageService;
public void validate(Chain chain, Transaction tx) throws NulsException {
if (converterCoreApi.isProtocol16()) {
this.validateProtocol16(chain, tx);
} else {
this._validate(chain, tx);
}
}
public void _validate(Chain chain, Transaction tx) throws NulsException {
CoinData coinData = ConverterUtil.getInstance(tx.getCoinData(), CoinData.class);
if (null != coinData.getFrom() && !coinData.getFrom().isEmpty()) {
throw new NulsException(ConverterErrorCode.RECHARGE_NOT_INCLUDE_COINFROM);
}
List<CoinTo> listCoinTo = coinData.getTo();
if (null == listCoinTo || listCoinTo.size() > 1) {
throw new NulsException(ConverterErrorCode.RECHARGE_HAVE_EXACTLY_ONE_COINTO);
}
CoinTo coinTo = listCoinTo.get(0);
RechargeTxData txData = ConverterUtil.getInstance(tx.getTxData(), RechargeTxData.class);
if(null != rechargeStorageService.find(chain, txData.getOriginalTxHash())){
// 该原始交易已执行过充值
chain.getLogger().error("The originalTxHash already confirmed (Repeat business) txHash:{}, originalTxHash:{}",
tx.getHash().toHex(), txData.getOriginalTxHash());
throw new NulsException(ConverterErrorCode.TX_DUPLICATION);
}
// 通过链内资产id 获取异构链信息
HeterogeneousAssetInfo heterogeneousAssetInfo = heterogeneousAssetHelper.getHeterogeneousAssetInfo(txData.getHeterogeneousChainId(), coinTo.getAssetsChainId(), coinTo.getAssetsId());
HeterogeneousTransactionInfo info = HeterogeneousUtil.getTxInfo(chain,
heterogeneousAssetInfo.getChainId(),
txData.getOriginalTxHash(),
HeterogeneousTxTypeEnum.DEPOSIT,
this.heterogeneousDockingManager);
if (null != info) {
heterogeneousRechargeValid(info, coinTo, heterogeneousAssetInfo);
} else {
// 查提案 (OriginalTxHash 不是异构链交易hash, 或可能是一个提案hash)
ProposalPO proposalPO = proposalStorageService.find(chain, NulsHash.fromHex(txData.getOriginalTxHash()));
if (null == proposalPO) {
throw new NulsException(ConverterErrorCode.HETEROGENEOUS_TX_NOT_EXIST);
}
proposalRechargeValid(chain, proposalPO, coinTo, heterogeneousAssetInfo);
}
}
public void validateProtocol16(Chain chain, Transaction tx) throws NulsException {
CoinData coinData = ConverterUtil.getInstance(tx.getCoinData(), CoinData.class);
if (null != coinData.getFrom() && !coinData.getFrom().isEmpty()) {
throw new NulsException(ConverterErrorCode.RECHARGE_NOT_INCLUDE_COINFROM);
}
List<CoinTo> listCoinTo = coinData.getTo();
if (null == listCoinTo || listCoinTo.size() > 2) {
throw new NulsException(ConverterErrorCode.RECHARGE_HAVE_EXACTLY_ONE_COINTO);
}
RechargeTxData txData = ConverterUtil.getInstance(tx.getTxData(), RechargeTxData.class);
if(null != rechargeStorageService.find(chain, txData.getOriginalTxHash())){
// 该原始交易已执行过充值
chain.getLogger().error("The originalTxHash already confirmed (Repeat business) txHash:{}, originalTxHash:{}",
tx.getHash().toHex(), txData.getOriginalTxHash());
throw new NulsException(ConverterErrorCode.TX_DUPLICATION);
}
HeterogeneousTransactionInfo info = HeterogeneousUtil.getTxInfo(chain,
txData.getHeterogeneousChainId(),
txData.getOriginalTxHash(),
HeterogeneousTxTypeEnum.DEPOSIT,
this.heterogeneousDockingManager);
if (null != info) {
if (info.isDepositIIMainAndToken()) {
// 校验同时充值token和main
CoinTo tokenAmountTo, mainAmountTo;
HeterogeneousAssetInfo tokenInfo, mainInfo;
CoinTo coin0 = listCoinTo.get(0);
HeterogeneousAssetInfo info0 = heterogeneousAssetHelper.getHeterogeneousAssetInfo(txData.getHeterogeneousChainId(), coin0.getAssetsChainId(), coin0.getAssetsId());
CoinTo coin1 = listCoinTo.get(1);
HeterogeneousAssetInfo info1 = heterogeneousAssetHelper.getHeterogeneousAssetInfo(txData.getHeterogeneousChainId(), coin1.getAssetsChainId(), coin1.getAssetsId());
// 不能两个资产都是主资产, assetId:1 为主资产
if (info0.getAssetId() == 1 && info1.getAssetId() == 1) {
throw new NulsException(ConverterErrorCode.RECHARGE_ASSETID_ERROR);
}
if (info0.getAssetId() == 1) {
mainAmountTo = coin0;
mainInfo = info0;
tokenAmountTo = coin1;
tokenInfo = info1;
} else if (info1.getAssetId() == 1){
mainAmountTo = coin1;
mainInfo = info1;
tokenAmountTo = coin0;
tokenInfo = info0;
} else {
throw new NulsException(ConverterErrorCode.RECHARGE_ASSETID_ERROR);
}
this.heterogeneousRechargeValidForCrossOutII(info, tokenAmountTo, tokenInfo, mainAmountTo, mainInfo);
} else {
// 校验只充值token 或者 只充值 main
if (listCoinTo.size() > 1) {
throw new NulsException(ConverterErrorCode.RECHARGE_HAVE_EXACTLY_ONE_COINTO);
}
// 通过链内资产id 获取异构链信息
CoinTo coinTo = listCoinTo.get(0);
HeterogeneousAssetInfo heterogeneousAssetInfo = heterogeneousAssetHelper.getHeterogeneousAssetInfo(txData.getHeterogeneousChainId(), coinTo.getAssetsChainId(), coinTo.getAssetsId());
heterogeneousRechargeValid(info, coinTo, heterogeneousAssetInfo);
}
} else {
// 查提案 (OriginalTxHash 不是异构链交易hash, 或可能是一个提案hash)
ProposalPO proposalPO = proposalStorageService.find(chain, NulsHash.fromHex(txData.getOriginalTxHash()));
if (null == proposalPO) {
throw new NulsException(ConverterErrorCode.HETEROGENEOUS_TX_NOT_EXIST);
}
proposalRechargeValidProtocol16(chain, proposalPO, listCoinTo);
}
}
/**
* 验证异构链充值交易
*
* @param info
* @param coinTo
* @throws NulsException
*/
private void heterogeneousRechargeValid(HeterogeneousTransactionInfo info, CoinTo coinTo, HeterogeneousAssetInfo heterogeneousAssetInfo) throws NulsException {
if (info.getAssetId() != heterogeneousAssetInfo.getAssetId()) {
// 充值资产错误
throw new NulsException(ConverterErrorCode.RECHARGE_ASSETID_ERROR);
}
BigInteger infoValue = info.getValue();
if (converterCoreApi.isProtocol22()) {
infoValue = converterCoreApi.checkDecimalsSubtractedToNerveForDeposit(heterogeneousAssetInfo, info.getValue());
}
if (infoValue.compareTo(coinTo.getAmount()) != 0) {
// 充值金额错误
throw new NulsException(ConverterErrorCode.RECHARGE_AMOUNT_ERROR);
}
if (!info.getNerveAddress().equals(AddressTool.getStringAddressByBytes(coinTo.getAddress()))) {
throw new NulsException(ConverterErrorCode.RECHARGE_ARRIVE_ADDRESS_ERROR);
}
}
/**
* 验证异构链充值交易 - CrossOutII
*
* @throws NulsException
*/
private void heterogeneousRechargeValidForCrossOutII(HeterogeneousTransactionInfo info, CoinTo tokenAmountTo, HeterogeneousAssetInfo tokenInfo, CoinTo mainAmountTo, HeterogeneousAssetInfo mainInfo) throws NulsException {
if (info.getAssetId() != tokenInfo.getAssetId()) {
// 充值token资产错误
throw new NulsException(ConverterErrorCode.RECHARGE_ASSETID_ERROR);
}
if (info.getValue().compareTo(tokenAmountTo.getAmount()) != 0) {
// 充值token金额错误
throw new NulsException(ConverterErrorCode.RECHARGE_AMOUNT_ERROR);
}
if (info.getDepositIIMainAssetAssetId() != mainInfo.getAssetId()) {
// 充值主资产错误
throw new NulsException(ConverterErrorCode.RECHARGE_ASSETID_ERROR);
}
BigInteger depositIIMainAssetValue = info.getDepositIIMainAssetValue();
if (converterCoreApi.isProtocol22()) {
depositIIMainAssetValue = converterCoreApi.checkDecimalsSubtractedToNerveForDeposit(mainInfo, depositIIMainAssetValue);
}
if (depositIIMainAssetValue.compareTo(mainAmountTo.getAmount()) != 0) {
// 充值主金额错误
throw new NulsException(ConverterErrorCode.RECHARGE_AMOUNT_ERROR);
}
if (!info.getNerveAddress().equals(AddressTool.getStringAddressByBytes(tokenAmountTo.getAddress()))) {
throw new NulsException(ConverterErrorCode.RECHARGE_ARRIVE_ADDRESS_ERROR);
}
if (!info.getNerveAddress().equals(AddressTool.getStringAddressByBytes(mainAmountTo.getAddress()))) {
throw new NulsException(ConverterErrorCode.RECHARGE_ARRIVE_ADDRESS_ERROR);
}
}
private void heterogeneousRechargeValidForOneClickCrossChain(Chain chain, HeterogeneousTransactionInfo info, CoinTo tokenAmountTo, HeterogeneousAssetInfo tokenInfo, CoinTo mainAmountTo, HeterogeneousAssetInfo mainInfo, CoinTo coinTipping) throws NulsException {
if (info.getAssetId() != tokenInfo.getAssetId()) {
// 充值token资产错误
throw new NulsException(ConverterErrorCode.RECHARGE_ASSETID_ERROR);
}
BigInteger tipping = BigInteger.ZERO;
if (coinTipping != null) {
tipping = coinTipping.getAmount();
}
if (info.getValue().compareTo(tokenAmountTo.getAmount().add(tipping)) != 0) {
// 充值token金额错误
throw new NulsException(ConverterErrorCode.RECHARGE_AMOUNT_ERROR);
}
if (info.getDepositIIMainAssetAssetId() != mainInfo.getAssetId()) {
// 充值主资产错误
throw new NulsException(ConverterErrorCode.RECHARGE_ASSETID_ERROR);
}
BigInteger depositIIMainAssetValue = info.getDepositIIMainAssetValue();
if (converterCoreApi.isProtocol22()) {
depositIIMainAssetValue = converterCoreApi.checkDecimalsSubtractedToNerveForDeposit(mainInfo, depositIIMainAssetValue);
}
if (depositIIMainAssetValue.compareTo(mainAmountTo.getAmount()) != 0) {
// 充值主金额错误
throw new NulsException(ConverterErrorCode.RECHARGE_AMOUNT_ERROR);
}
if (!info.getNerveAddress().equals(AddressTool.getStringAddressByBytes(tokenAmountTo.getAddress()))) {
throw new NulsException(ConverterErrorCode.RECHARGE_ARRIVE_ADDRESS_ERROR);
}
}
/**
* 验证提案转到其他地址
*
* @param chain
* @param proposalPO
* @param coinTo
* @throws NulsException
*/
private void proposalRechargeValid(Chain chain, ProposalPO proposalPO, CoinTo coinTo, HeterogeneousAssetInfo heterogeneousAssetInfo) throws NulsException {
if (ProposalTypeEnum.TRANSFER.value() != proposalPO.getType()) {
// 提案类型错误
chain.getLogger().error("Proposal type is not transfer");
throw new NulsException(ConverterErrorCode.PROPOSAL_TYPE_ERROR);
}
// 虚拟银行节点签名数需要达到的拜占庭数
int byzantineCount = VirtualBankUtil.getByzantineCount(chain);
if (proposalPO.getFavorNumber() < byzantineCount) {
// 提案没有投票通过
chain.getLogger().error("Proposal type was rejected");
throw new NulsException(ConverterErrorCode.PROPOSAL_REJECTED);
}
// 获取提案中的异构链充值交易
HeterogeneousTransactionInfo info = HeterogeneousUtil.getTxInfo(chain,
proposalPO.getHeterogeneousChainId(),
proposalPO.getHeterogeneousTxHash(),
HeterogeneousTxTypeEnum.DEPOSIT,
this.heterogeneousDockingManager);
if (null == info) {
chain.getLogger().error("未查询到异构链交易 heterogeneousTxHash:{}", proposalPO.getHeterogeneousTxHash());
throw new NulsException(ConverterErrorCode.HETEROGENEOUS_TX_NOT_EXIST);
}
if (info.getAssetId() != heterogeneousAssetInfo.getAssetId()) {
// 充值资产错误
throw new NulsException(ConverterErrorCode.RECHARGE_ASSETID_ERROR);
}
if (info.getValue().compareTo(coinTo.getAmount()) != 0) {
// 充值金额错误
throw new NulsException(ConverterErrorCode.RECHARGE_AMOUNT_ERROR);
}
if (!Arrays.equals(proposalPO.getAddress(), coinTo.getAddress())) {
// 充值交易到账地址不是提案中的到账地址
chain.getLogger().error("充值交易到账地址不是提案中的到账地址");
throw new NulsException(ConverterErrorCode.RECHARGE_ARRIVE_ADDRESS_ERROR);
}
}
private void proposalRechargeValidProtocol16(Chain chain, ProposalPO proposalPO, List<CoinTo> listCoinTo) throws NulsException {
if (ProposalTypeEnum.TRANSFER.value() != proposalPO.getType()) {
// 提案类型错误
chain.getLogger().error("Proposal type is not transfer");
throw new NulsException(ConverterErrorCode.PROPOSAL_TYPE_ERROR);
}
// 虚拟银行节点签名数需要达到的拜占庭数
int byzantineCount = VirtualBankUtil.getByzantineCount(chain);
if (proposalPO.getFavorNumber() < byzantineCount) {
// 提案没有投票通过
chain.getLogger().error("Proposal type was rejected");
throw new NulsException(ConverterErrorCode.PROPOSAL_REJECTED);
}
// 获取提案中的异构链充值交易
int htgChainId = proposalPO.getHeterogeneousChainId();
HeterogeneousTransactionInfo info = HeterogeneousUtil.getTxInfo(chain,
htgChainId,
proposalPO.getHeterogeneousTxHash(),
HeterogeneousTxTypeEnum.DEPOSIT,
this.heterogeneousDockingManager);
if (null == info) {
chain.getLogger().error("未查询到异构链交易 heterogeneousTxHash:{}", proposalPO.getHeterogeneousTxHash());
throw new NulsException(ConverterErrorCode.HETEROGENEOUS_TX_NOT_EXIST);
}
if (info.isDepositIIMainAndToken()) {
if (listCoinTo.size() != 2) {
throw new NulsException(ConverterErrorCode.RECHARGE_ASSETID_ERROR);
}
// 校验同时充值token和main
CoinTo tokenAmountTo, mainAmountTo;
HeterogeneousAssetInfo tokenInfo, mainInfo;
CoinTo coin0 = listCoinTo.get(0);
HeterogeneousAssetInfo info0 = heterogeneousAssetHelper.getHeterogeneousAssetInfo(htgChainId, coin0.getAssetsChainId(), coin0.getAssetsId());
CoinTo coin1 = listCoinTo.get(1);
HeterogeneousAssetInfo info1 = heterogeneousAssetHelper.getHeterogeneousAssetInfo(htgChainId, coin1.getAssetsChainId(), coin1.getAssetsId());
// 必须为token和main资产
if (info0.getAssetId() == 1 && info1.getAssetId() == 1) {
throw new NulsException(ConverterErrorCode.RECHARGE_ASSETID_ERROR);
}
if (info0.getAssetId() == 1) {
mainAmountTo = coin0;
mainInfo = info0;
tokenAmountTo = coin1;
tokenInfo = info1;
} else if (info1.getAssetId() == 1){
mainAmountTo = coin1;
mainInfo = info1;
tokenAmountTo = coin0;
tokenInfo = info0;
} else {
throw new NulsException(ConverterErrorCode.RECHARGE_ASSETID_ERROR);
}
if (info.getAssetId() != tokenInfo.getAssetId()) {
// 充值token资产错误
throw new NulsException(ConverterErrorCode.RECHARGE_ASSETID_ERROR);
}
if (info.getValue().compareTo(tokenAmountTo.getAmount()) != 0) {
// 充值token金额错误
throw new NulsException(ConverterErrorCode.RECHARGE_AMOUNT_ERROR);
}
if (info.getDepositIIMainAssetAssetId() != mainInfo.getAssetId()) {
// 充值主资产错误
throw new NulsException(ConverterErrorCode.RECHARGE_ASSETID_ERROR);
}
if (info.getDepositIIMainAssetValue().compareTo(mainAmountTo.getAmount()) != 0) {
// 充值主金额错误
throw new NulsException(ConverterErrorCode.RECHARGE_AMOUNT_ERROR);
}
if (!Arrays.equals(proposalPO.getAddress(), tokenAmountTo.getAddress())) {
chain.getLogger().error("充值交易到账地址不是提案中的到账地址");
throw new NulsException(ConverterErrorCode.RECHARGE_ARRIVE_ADDRESS_ERROR);
}
if (!Arrays.equals(proposalPO.getAddress(), mainAmountTo.getAddress())) {
chain.getLogger().error("充值交易到账地址不是提案中的到账地址");
throw new NulsException(ConverterErrorCode.RECHARGE_ARRIVE_ADDRESS_ERROR);
}
} else {
CoinTo coinTo = listCoinTo.get(0);
HeterogeneousAssetInfo heterogeneousAssetInfo = heterogeneousAssetHelper.getHeterogeneousAssetInfo(htgChainId, coinTo.getAssetsChainId(), coinTo.getAssetsId());
if (info.getAssetId() != heterogeneousAssetInfo.getAssetId()) {
// 充值资产错误
throw new NulsException(ConverterErrorCode.RECHARGE_ASSETID_ERROR);
}
if (info.getValue().compareTo(coinTo.getAmount()) != 0) {
// 充值金额错误
throw new NulsException(ConverterErrorCode.RECHARGE_AMOUNT_ERROR);
}
if (!Arrays.equals(proposalPO.getAddress(), coinTo.getAddress())) {
// 充值交易到账地址不是提案中的到账地址
chain.getLogger().error("充值交易到账地址不是提案中的到账地址");
throw new NulsException(ConverterErrorCode.RECHARGE_ARRIVE_ADDRESS_ERROR);
}
}
}
public void validateOneClickCrossChain(Chain chain, Transaction tx) throws NulsException {
// 验证一键跨链交易, 验证提现金额, 手续费金额, tipping数据, 目标链信息
CoinData coinData = ConverterUtil.getInstance(tx.getCoinData(), CoinData.class);
if (null != coinData.getFrom() && !coinData.getFrom().isEmpty()) {
throw new NulsException(ConverterErrorCode.RECHARGE_NOT_INCLUDE_COINFROM);
}
List<CoinTo> listCoinTo = coinData.getTo();
if (null == listCoinTo || (listCoinTo.size() != 2 && listCoinTo.size() != 3)) {
throw new NulsException(ConverterErrorCode.RECHARGE_HAVE_EXACTLY_ONE_COINTO);
}
OneClickCrossChainTxData txData = ConverterUtil.getInstance(tx.getTxData(), OneClickCrossChainTxData.class);
HeterogeneousHash heterogeneousHash = txData.getOriginalTxHash();
String originalTxHash = heterogeneousHash.getHeterogeneousHash();
int htgChainId = heterogeneousHash.getHeterogeneousChainId();
if(null != rechargeStorageService.find(chain, originalTxHash)){
// 该原始交易已执行过充值
chain.getLogger().error("The originalTxHash already confirmed (Repeat business) txHash:{}, originalTxHash:{}",
tx.getHash().toHex(), originalTxHash);
throw new NulsException(ConverterErrorCode.TX_DUPLICATION);
}
HeterogeneousTransactionInfo info = HeterogeneousUtil.getTxInfo(chain,
htgChainId,
originalTxHash,
HeterogeneousTxTypeEnum.DEPOSIT,
this.heterogeneousDockingManager);
if (info == null) {
throw new NulsException(ConverterErrorCode.HETEROGENEOUS_TX_NOT_EXIST);
}
IHeterogeneousChainDocking docking = this.heterogeneousDockingManager.getHeterogeneousDocking(htgChainId);
String extend = info.getDepositIIExtend();
HeterogeneousOneClickCrossChainData data = docking.parseOneClickCrossChainData(extend);
if (data == null) {
chain.getLogger().error("[{}][一键跨链]交易验证失败, originalTxHash: {}, extend: {}", htgChainId, extend);
throw new NulsException(ConverterErrorCode.ONE_CLICK_CROSS_CHAIN_TX_ERROR);
}
BigInteger tipping = data.getTipping();
boolean hasTipping = tipping.compareTo(BigInteger.ZERO) > 0;
if (hasTipping) {
if (listCoinTo.size() != 3) {
throw new NulsException(ConverterErrorCode.RECHARGE_HAVE_EXACTLY_ONE_COINTO);
}
} else {
if (listCoinTo.size() != 2) {
throw new NulsException(ConverterErrorCode.RECHARGE_HAVE_EXACTLY_ONE_COINTO);
}
}
byte[] withdrawalBlackhole = AddressTool.getAddress(ConverterContext.WITHDRAWAL_BLACKHOLE_PUBKEY, chain.getChainId());
byte[] withdrawalFeeAddress = AddressTool.getAddress(ConverterContext.FEE_PUBKEY, chain.getChainId());
CoinTo coinWithdrawal = null, coinFee = null, coinTipping = null;
for (CoinTo to : listCoinTo) {
if (Arrays.equals(withdrawalBlackhole, to.getAddress())) {
coinWithdrawal = to;
} else if (Arrays.equals(withdrawalFeeAddress, to.getAddress())) {
coinFee = to;
} else {
coinTipping = to;
}
}
if (coinWithdrawal == null || coinFee == null || (hasTipping && coinTipping == null)) {
chain.getLogger().error("[{}][一键跨链]交易验证失败, CoinData缺失, originalTxHash: {}", htgChainId, originalTxHash);
throw new NulsException(ConverterErrorCode.ONE_CLICK_CROSS_CHAIN_TX_ERROR);
}
String desToAddress = data.getDesToAddress();
desToAddress = ConverterUtil.addressToLowerCase(desToAddress);
int desChainId = txData.getDesChainId();
if (txData.getDesChainId() != data.getDesChainId() ||
!txData.getDesToAddress().equals(desToAddress) ||
coinFee.getAmount().compareTo(data.getFeeAmount()) != 0) {
chain.getLogger().error("[{}][一键跨链]交易验证失败, 目标链信息错误, feeAmount: {}, desId: {}, desAddress: {}, originalTxHash: {}", htgChainId, coinFee.getAmount(), txData.getDesChainId(), txData.getDesToAddress(), originalTxHash);
throw new NulsException(ConverterErrorCode.ONE_CLICK_CROSS_CHAIN_TX_ERROR);
}
BigInteger tippingFromCoin = BigInteger.ZERO;
if (coinTipping != null) {
tippingFromCoin = coinTipping.getAmount();
if (coinWithdrawal.getAssetsChainId() != coinTipping.getAssetsChainId() || coinWithdrawal.getAssetsId() != coinTipping.getAssetsId()) {
throw new NulsException(ConverterErrorCode.RECHARGE_ASSETID_ERROR);
}
}
// Nerve一键跨链交易,必有一个资产是主资产,作为跨到目标链的手续费
boolean hasToken = info.isIfContractAsset();
if (hasToken) {
// 源链交易一定充值了token
HeterogeneousAssetInfo infoWithdrawal = heterogeneousAssetHelper.getHeterogeneousAssetInfo(htgChainId, coinWithdrawal.getAssetsChainId(), coinWithdrawal.getAssetsId());
HeterogeneousAssetInfo infoFee = heterogeneousAssetHelper.getHeterogeneousAssetInfo(htgChainId, coinFee.getAssetsChainId(), coinFee.getAssetsId());
// 跨链资产一定是token资产, 手续费资产一定是主资产, assetId:1 为主资产
if (infoWithdrawal.getAssetId() == 1 || infoFee.getAssetId() != 1) {
throw new NulsException(ConverterErrorCode.RECHARGE_ASSETID_ERROR);
}
if (info.isDepositIIMainAndToken()) {
// 校验同时充值token和main
this.heterogeneousRechargeValidForOneClickCrossChain(chain, info, coinWithdrawal, infoWithdrawal, coinFee, infoFee, coinTipping);
} else {
// 只充值了token
if (info.getAssetId() != infoWithdrawal.getAssetId()) {
// 充值资产错误
throw new NulsException(ConverterErrorCode.RECHARGE_ASSETID_ERROR);
}
if (info.getValue().compareTo(coinWithdrawal.getAmount().add(tippingFromCoin)) != 0) {
// 充值金额错误
throw new NulsException(ConverterErrorCode.RECHARGE_AMOUNT_ERROR);
}
if (!info.getNerveAddress().equals(AddressTool.getStringAddressByBytes(coinWithdrawal.getAddress()))) {
throw new NulsException(ConverterErrorCode.RECHARGE_ARRIVE_ADDRESS_ERROR);
}
if (coinFee.getAmount().compareTo(BigInteger.ZERO) != 0) {
// 手续费金额错误
throw new NulsException(ConverterErrorCode.ONE_CLICK_CROSS_CHAIN_FEE_ERROR);
}
}
} else {
// 源链只充值了主资产
if (coinWithdrawal.getAssetsChainId() != coinFee.getAssetsChainId() || coinWithdrawal.getAssetsId() != coinFee.getAssetsId()) {
throw new NulsException(ConverterErrorCode.RECHARGE_ASSETID_ERROR);
}
HeterogeneousAssetInfo infoMain = heterogeneousAssetHelper.getHeterogeneousAssetInfo(htgChainId, coinFee.getAssetsChainId(), coinFee.getAssetsId());
if (info.getAssetId() != infoMain.getAssetId()) {
// 充值资产错误
throw new NulsException(ConverterErrorCode.RECHARGE_ASSETID_ERROR);
}
BigInteger infoValue = info.getValue();
if (converterCoreApi.isProtocol22()) {
infoValue = converterCoreApi.checkDecimalsSubtractedToNerveForDeposit(infoMain, infoValue);
}
if (infoValue.compareTo(coinWithdrawal.getAmount().add(coinFee.getAmount()).add(tippingFromCoin)) != 0) {
// 充值金额错误
throw new NulsException(ConverterErrorCode.RECHARGE_AMOUNT_ERROR);
}
if (!info.getNerveAddress().equals(AddressTool.getStringAddressByBytes(coinWithdrawal.getAddress()))) {
throw new NulsException(ConverterErrorCode.RECHARGE_ARRIVE_ADDRESS_ERROR);
}
}
// 检查目标链数据
IHeterogeneousChainDocking desDocking = heterogeneousDockingManager.getHeterogeneousDocking(desChainId);
// 检查充值资产是否能跨链到目标链
HeterogeneousAssetInfo desChainAssetInfo = heterogeneousAssetHelper.getHeterogeneousAssetInfo(desChainId, coinWithdrawal.getAssetsChainId(), coinWithdrawal.getAssetsId());
if (desChainAssetInfo == null) {
chain.getLogger().error("[{}]OneClickCrossChain des error, desChainId:{}, desToAddress:{}, originalTxHash: {}", htgChainId, desChainId, desToAddress, originalTxHash);
throw new NulsException(ConverterErrorCode.ONE_CLICK_CROSS_CHAIN_DES_ERROR);
}
// 检查目标链地址是否合法
boolean validateAddress = desDocking.validateAddress(desToAddress);
if (!validateAddress) {
chain.getLogger().error("[{}]OneClickCrossChain desToAddress error, desChainId:{}, desToAddress:{}, originalTxHash: {}", htgChainId, desChainId, desToAddress, originalTxHash);
throw new NulsException(ConverterErrorCode.ONE_CLICK_CROSS_CHAIN_DES_ERROR);
}
}
public void validateAddFeeCrossChain(Chain chain, Transaction tx) throws NulsException {
// 跨链追加手续费的业务校验
String hash = tx.getHash().toHex();
CoinData coinData = ConverterUtil.getInstance(tx.getCoinData(), CoinData.class);
if (null != coinData.getFrom() && !coinData.getFrom().isEmpty()) {
throw new NulsException(ConverterErrorCode.RECHARGE_NOT_INCLUDE_COINFROM);
}
List<CoinTo> listCoinTo = coinData.getTo();
if (null == listCoinTo || listCoinTo.size() != 1) {
throw new NulsException(ConverterErrorCode.RECHARGE_HAVE_EXACTLY_ONE_COINTO);
}
WithdrawalAddFeeByCrossChainTxData txData = ConverterUtil.getInstance(tx.getTxData(), WithdrawalAddFeeByCrossChainTxData.class);
HeterogeneousHash heterogeneousHash = txData.getHtgTxHash();
String originalTxHash = heterogeneousHash.getHeterogeneousHash();
int htgChainId = heterogeneousHash.getHeterogeneousChainId();
if(null != rechargeStorageService.find(chain, originalTxHash)){
// 该原始交易已执行过充值
chain.getLogger().error("The originalTxHash already confirmed (Repeat business) txHash:{}, originalTxHash:{}",
hash, originalTxHash);
throw new NulsException(ConverterErrorCode.TX_DUPLICATION);
}
HeterogeneousTransactionInfo info = HeterogeneousUtil.getTxInfo(chain,
htgChainId,
originalTxHash,
HeterogeneousTxTypeEnum.DEPOSIT,
this.heterogeneousDockingManager);
if (info == null) {
throw new NulsException(ConverterErrorCode.HETEROGENEOUS_TX_NOT_EXIST);
}
IHeterogeneousChainDocking docking = this.heterogeneousDockingManager.getHeterogeneousDocking(htgChainId);
String extend = info.getDepositIIExtend();
HeterogeneousAddFeeCrossChainData data = docking.parseAddFeeCrossChainData(extend);
if (data == null) {
chain.getLogger().error("[{}][跨链追加手续费]交易验证失败, originalTxHash: {}, extend: {}", htgChainId, extend);
throw new NulsException(ConverterErrorCode.ONE_CLICK_CROSS_CHAIN_TX_ERROR);
}
byte[] withdrawalFeeAddress = AddressTool.getAddress(ConverterContext.FEE_PUBKEY, chain.getChainId());
CoinTo coinTo = listCoinTo.get(0);
if (!Arrays.equals(withdrawalFeeAddress, coinTo.getAddress())) {
chain.getLogger().error("[{}][跨链追加手续费]交易验证失败, 手续费收集地址与追加交易to地址不匹配, toAddress:{}, withdrawalFeeAddress:{} ",
htgChainId,
AddressTool.getStringAddressByBytes(coinTo.getAddress()),
AddressTool.getStringAddressByBytes(withdrawalFeeAddress));
throw new NulsException(ConverterErrorCode.DISTRIBUTION_ADDRESS_MISMATCH);
}
if (info.isIfContractAsset()) {
throw new NulsException(ConverterErrorCode.ADD_FEE_CROSS_CHAIN_COIN_ERROR);
}
HeterogeneousAssetInfo infoMain = heterogeneousAssetHelper.getHeterogeneousAssetInfo(htgChainId, coinTo.getAssetsChainId(), coinTo.getAssetsId());
if (info.getAssetId() != infoMain.getAssetId()) {
// 充值资产错误
throw new NulsException(ConverterErrorCode.RECHARGE_ASSETID_ERROR);
}
if (info.getValue().compareTo(coinTo.getAmount()) != 0) {
// 充值金额错误
throw new NulsException(ConverterErrorCode.RECHARGE_AMOUNT_ERROR);
}
if (!info.getNerveAddress().equals(AddressTool.getStringAddressByBytes(coinTo.getAddress()))) {
throw new NulsException(ConverterErrorCode.RECHARGE_ARRIVE_ADDRESS_ERROR);
}
// 验证提现交易
String basicTxHash = txData.getNerveTxHash();
if (StringUtils.isBlank(basicTxHash)) {
chain.getLogger().error("要追加手续费的原始提现交易hash不存在! " + ConverterErrorCode.WITHDRAWAL_TX_NOT_EXIST.getMsg());
// 提现交易hash
throw new NulsException(ConverterErrorCode.WITHDRAWAL_TX_NOT_EXIST);
}
Transaction basicTx = TransactionCall.getConfirmedTx(chain, basicTxHash);
if (null == basicTx) {
chain.getLogger().error("原始交易不存在 , hash:{}", basicTxHash);
throw new NulsException(ConverterErrorCode.WITHDRAWAL_TX_NOT_EXIST);
}
if (basicTx.getType() != TxType.WITHDRAWAL && basicTx.getType() != TxType.ONE_CLICK_CROSS_CHAIN) {
// 不是提现交易
chain.getLogger().error("txdata对应的交易不是提现交易/一键跨链 , hash:{}", basicTxHash);
throw new NulsException(ConverterErrorCode.WITHDRAWAL_TX_NOT_EXIST);
}
int feeAssetChainId = chain.getConfig().getChainId();
int feeAssetId = chain.getConfig().getAssetId();
if (basicTx.getType() == TxType.WITHDRAWAL || basicTx.getType() == TxType.ONE_CLICK_CROSS_CHAIN) {
// 判断该提现交易是否已经有对应的确认提现交易
ConfirmWithdrawalPO po = confirmWithdrawalStorageService.findByWithdrawalTxHash(chain, basicTx.getHash());
if (null != po) {
// 说明该提现交易 已经发出过确认提现交易, 不能再追加手续费
chain.getLogger().error("该提现交易已经完成,不能再追加异构链提现手续费, withdrawalTxhash:{}, hash:{}", basicTxHash, hash);
throw new NulsException(ConverterErrorCode.WITHDRAWAL_CONFIRMED);
}
// 提现交易的手续费资产ID
CoinData basicCoinData = ConverterUtil.getInstance(basicTx.getCoinData(), CoinData.class);
Coin feeCoin = null;
for (CoinTo basicCoinTo : basicCoinData.getTo()) {
if (Arrays.equals(withdrawalFeeAddress, basicCoinTo.getAddress())) {
feeCoin = basicCoinTo;
break;
}
}
feeAssetChainId = feeCoin.getAssetsChainId();
feeAssetId = feeCoin.getAssetsId();
}
// 检查追加的手续费资产,必须与提现交易的手续费资产一致
if (coinTo.getAssetsChainId() != feeAssetChainId || coinTo.getAssetsId() != feeAssetId) {
chain.getLogger().error("追加交易资产必须与提现交易的手续费资产一致, AssetsChainId:{}, AssetsId:{}",
coinTo.getAssetsChainId(), coinTo.getAssetsId());
throw new NulsException(ConverterErrorCode.WITHDRAWAL_ADDITIONAL_FEE_COIN_ERROR);
}
}
}
|
package com.nanyin.config.redis;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
/**
* redis 配置
* redisTemplate 设置序列化策略
* cacheManager 自定义 实现自定义ttl时间
* @Author nanyin
* @Date 22:12 2019-08-19
**/
@Configuration
public class WebRedisConfiguration extends CachingConfigurerSupport {
@Bean
public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<Object, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
FastJson2JsonRedisSerializer serializer = new FastJson2JsonRedisSerializer(Object.class);
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
serializer.setObjectMapper(mapper);
template.setHashKeySerializer(serializer);
template.setHashValueSerializer(serializer);
template.setDefaultSerializer(serializer);
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new StringRedisSerializer());
template.afterPropertiesSet();
return template;
}
/**
* 使用 @Cacheable(cacheManager="TtlCacheManager") 激活cacheManager
**/
@Bean(name = "TtlCacheManager")
public RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofSeconds(30))
.disableCachingNullValues();
RedisCacheManager.RedisCacheManagerBuilder builder =
RedisCacheManager.RedisCacheManagerBuilder.fromConnectionFactory(redisConnectionFactory);
return builder.transactionAware().cacheDefaults(config).build();
}
}
|
/**
* Created by Student8 on 15.04.2017.
*/
public class Square extends Figure implements toString {
private int aa;
public Square(int aa) {
this.aa = aa;
}
public int getA() {
return aa;
}
public String toString() {
return(getA() + " ");
}
}
|
package com.epam.training.sportsbetting.service;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import com.epam.training.sportsbetting.domain.Bet;
import com.epam.training.sportsbetting.domain.DataLoader;
import com.epam.training.sportsbetting.domain.DataLoader2;
import com.epam.training.sportsbetting.domain.Outcome;
import com.epam.training.sportsbetting.domain.Player;
import com.epam.training.sportsbetting.domain.SportEvent;
import com.epam.training.sportsbetting.domain.Wager;
public class SportsBettingServiceProvider implements SportsBettingService {
private Player player;
private List<Wager> wagers;
public SportsBettingServiceProvider() {
wagers = new ArrayList<Wager>();
}
public void savePlayer(Player player) {
this.player = player;
}
public Player findPlayer() {
return player;
}
public List<SportEvent> findAllSportEvents() {
List<SportEvent> sportEvents = DataLoader.loadData();
return sportEvents;
}
public void saveWager(Wager wager) {
wagers.add(wager);
findPlayer().subtractAmountFromBalance(wager.getAmount());
wager.setProcessed(true);
}
public List<Wager> findAllWagers() {
return wagers;
}
public void calculateResults() {
Random random = new Random();
for(SportEvent sportEvent : findAllSportEvents()) {
for(Bet bet : sportEvent.getBets()) {
if(bet.getOutcomes().size() > 1 ) {
int winner = random.nextInt(bet.getOutcomes().size());
int index = 0;
for(Outcome outcome : bet.getOutcomes()) {
if(index == winner) {
sportEvent.addResult(outcome);
setResultsInWagers(outcome);
}
index++;
}
} else if(bet.getOutcomes().size() == 1){
if(random.nextBoolean()) {
sportEvent.addResult(bet.getOutcomes().get(0));
setResultsInWagers(bet.getOutcomes().get(0));
}
}
}
}
addWinnerPrizeToPlayer();
}
private void addWinnerPrizeToPlayer() {
for(Wager wager : wagers) {
if(wager.isWin() && wager.isProcessed()) {
findPlayer().addAmountToBalance(wager.getAmount().multiply(wager.getActualOdd()));
}
}
}
private void setResultsInWagers(Outcome outcome) {
for(Wager wager : wagers) {
if(wager.getOutcome().equals(outcome)) {
wager.setWin(true);
}
}
}
}
|
import java.io.*;
import java.util.*;
class baek__10211 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine());
StringBuilder sb = new StringBuilder();
while (T-- > 0) {
int n = Integer.parseInt(br.readLine());
int[] nums = new int[n];
String[] temp = br.readLine().split(" ");
for (int i = 0; i < n; i++) {
nums[i] = Integer.parseInt(temp[i]);
}
int[] s = new int[n + 1];
s[0] = nums[0];
for (int i = 1; i < n; i++) {
s[i] = s[i - 1] + nums[i];
}
int answer = -1000 * n - 1;
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
answer = Math.max(answer, i - 1 < 0 ? s[j] : s[j] - s[i - 1]);
}
}
sb.append(answer + "\n");
}
System.out.print(sb);
}
}
|
package com.vpt.pw.demo.Controllers;
import com.vpt.pw.demo.dtos.crf2DTO.FormCrf2DTO;
import com.vpt.pw.demo.service.CRF2Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/form/crf/2")
public class CRF2Controller {
@Autowired
CRF2Service crf2Service;
@PostMapping(value = "/save", produces = "application/json", consumes = "application/json")
public FormCrf2DTO saveData(@RequestBody FormCrf2DTO formCrf2DTO) {
formCrf2DTO = crf2Service.saveData(formCrf2DTO);
return formCrf2DTO;
}
}
|
package egovframework.adm.book.dao;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Repository;
import egovframework.rte.psl.dataaccess.EgovAbstractDAO;
@Repository("cpBookAdminDAO")
public class CpBookAdminDAO extends EgovAbstractDAO{
public List selectCPList(Map<String, Object> commandMap) {
return list("cpBookAdminDAO.selectCPList", commandMap);
}
public List selectList(Map<String, Object> commandMap) {
return list("cpBookAdminDAO.selectList", commandMap);
}
public List selectSubj(Map<String, Object> commandMap) {
return list("cpBookAdminDAO.selectSubj", commandMap);
}
public int updateCpbookStatus(HashMap<String, Object> mm) {
return update("cpBookAdminDAO.updateCpbookStatus", mm);
}
public Map selectSubjInfo(Map<String, Object> commandMap) {
return (Map)selectByPk("cpBookAdminDAO.selectSubjInfo", commandMap);
}
public List selectDeliveryCompExcelList(Map<String, Object> commandMap) {
return list("cpBookAdminDAO.selectDeliveryCompExcelList", commandMap);
}
public Map selectDeliveryMemberInfo(Map<String, Object> mm) {
return (Map)selectByPk("cpBookAdminDAO.selectDeliveryMemberInfo", mm);
}
public void insertDeliveryMeber(HashMap<String, Object> mm) {
insert("cpBookAdminDAO.insertDeliveryMeber", mm);
}
public void updateDeliveryMeber(HashMap<String, Object> mm) {
insert("cpBookAdminDAO.updateDeliveryMeber", mm);
}
public int deleteCpBook(HashMap<String, Object> mm) {
return delete("cpBookAdminDAO.deleteCpBook", mm);
}
}
|
package com.qzkk.controller;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.node.BigIntegerNode;
import com.qzkk.domain.GoodApplication;
import com.qzkk.service.GoodService;
import com.qzkk.vo.GetGoodApplyInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.math.BigInteger;
/**
* @author: jzc
* @date: 18/7/2019-下午2:17
* @description:
*/
@RestController
public class GoodApplicationController {
@Autowired
private GoodService goodService;
@PostMapping("/addGoodApplication")
public JSONObject addGoodApplication(GoodApplication goodApplication) {
return goodService.addGoodApplication(goodApplication);
}
@GetMapping("/getGoodApplicationList")
public JSONObject getGoodApplicationList() {
return goodService.getGoodApplicationList(0);
}
@PostMapping("/examineGoodApplication")
public JSONObject examineGoodApplication(@RequestParam long gaId) {
return goodService.examineGoodApplication(gaId);
// 审批通过物资申请
}
@PostMapping("/refuseGoodApplication")
public JSONObject refuseGoodApplication(@RequestParam long gaId) {
return goodService.refuseGoodApplication(gaId);
// 拒绝物资申请
}
@PostMapping("/examineApplication")
public JSONObject examineApplication(@RequestParam long gaid) {
return goodService.examineApplication(gaid);
}
@PostMapping("/refuseApplication")
public JSONObject refuseApplication(@RequestParam long gaid) {
return goodService.refuseApplication(gaid);
}
@GetMapping("/getGoodTypes")
public JSONObject getGoodTypes() {
return goodService.getLeftGoodTypes();
}
@PostMapping("/getGoodAplyByUid")
public JSONObject getGoodAplyForUid(@RequestParam long uid) {
return goodService.getGoodAplyByUid(uid);
}
@PostMapping("/abandonApply")
public JSONObject abandonApply(@RequestParam long gaid,@RequestParam long gid,@RequestParam int number) {
return goodService.abandonApply(gaid,gid,number);
}
@PostMapping("/returnGoods")
public JSONObject returnGoods(@RequestParam long gaid,@RequestParam long gid,@RequestParam int number) {
return goodService.returnGoods(gaid,gid,number);
}
@PostMapping("/deleteApply")
public JSONObject deleteApply(@RequestParam long gaid) {
return goodService.deleteApply(gaid);
}
}
|
package com.taotao.rest.util;
/**
* redisKeyUtil
* @author fenguriqi
* 2017年5月14日 下午8:26:26
* RedisKeyUtil
*/
public class RedisKeyUtil {
/**广告的缓存*/
public static final String REDIS_ADVERTIES_CONTENT_KEY="adverties_content_key";
/**商品基本信息*/
public static final String ITEM_BASE_INFO_KEY="item_base_info";
/**商品描述*/
public static final String ITEM_DESC_KEY="item_desc";
/**商品规格参数*/
public static final String ITEM_PARAM_KEY="item_param";
/**redis中商品信息key*/
public static final String REDIS_ITEM_KEY="redis_item";
/**商品过期时间*/
public static final Integer REDIS_EXPIRE_SECOND=86400;
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author ntnrc
*/
public class TestMago {
public static void main(String args[]){
Mago mago = new Mago("El Blanco", 50, "gandalf", "Humano", 87454, 200);
System.out.println(mago);
}
}
|
package airlines;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
try(Scanner sc = new Scanner(System.in)) {
System.out.println("=====================AIRLINES===================");
}
}
}
|
package com.qx.wechat.comm.sdk.request.msg;
/**
* 所有发送类型的消息结构体
* 例如: 发送文本消息,图片消息
*
* 注意: 发送群@消息例外
*
* @author Macky(liuyunsh@cn.ibm.com)
*
* @date: Apr 12, 2020 12:02:50 PM
*
* @since: 1.0.0
*
*/
public class PassiveMsg implements java.io.Serializable{
private static final long serialVersionUID = -1403760141424370499L;
private String msg;
private String type;
private String to_wxid;
private String robot_wxid;
public String getMsg() {
return msg;
}
public PassiveMsg setMsg(String msg) {
this.msg = msg;
return this;
}
public String getType() {
return type;
}
public PassiveMsg setType(String type) {
this.type = type;
return this;
}
public String getTo_wxid() {
return to_wxid;
}
public PassiveMsg setTo_wxid(String to_wxid) {
this.to_wxid = to_wxid;
return this;
}
public String getRobot_wxid() {
return robot_wxid;
}
public PassiveMsg setRobot_wxid(String robot_wxid) {
this.robot_wxid = robot_wxid;
return this;
}
}
|
package com.sirma.itt.javacourse.chat.client.controller;
import java.util.List;
import org.apache.log4j.Logger;
import com.sirma.itt.javacourse.chat.client.interfaces.UserController;
import com.sirma.itt.javacourse.chat.client.managers.ClientInfo;
import com.sirma.itt.javacourse.chat.client.threads.ClientThread;
import com.sirma.itt.javacourse.chat.client.ui.ChatsPanel;
import com.sirma.itt.javacourse.chat.client.ui.MainClientWindow;
import com.sirma.itt.javacourse.chat.client.ui.componnents.PopUpMessages;
import com.sirma.itt.javacourse.chat.common.Message;
import com.sirma.itt.javacourse.chat.common.MessageType;
import com.sirma.itt.javacourse.chat.common.utils.CommonUtils;
import com.sirma.itt.javacourse.chat.common.utils.LanguageController;
/**
* This class holds references to UI components that interact together.
*
* @author siliev
*
*/
public class UIControler implements UserController {
private static final Logger LOGGER = Logger.getLogger(UIControler.class);
private ChatsPanel chatsPanel;
private MainClientWindow mainWindow;
private ClientThread clientThread;
private ClientInfo clientInfo;
private PopUpMessages popUps;
public UIControler() {
this.mainWindow = new MainClientWindow(this);
popUps = new PopUpMessages();
clientInfo = ClientInfo.getInstance();
}
public void registerChatPanel(ChatsPanel chatsPanel) {
this.chatsPanel = chatsPanel;
}
public ClientInfo getClientInfo() {
return clientInfo;
}
public void setClientInfo(ClientInfo clientInfo) {
this.clientInfo = clientInfo;
}
/**
* @return the chatsPanel
*/
public ChatsPanel getChatsPanel() {
return chatsPanel;
}
/**
* @return the thread
*/
public ClientThread getThread() {
return clientThread;
}
/**
* @param thread
* the thread to set
*/
public void setThread(ClientThread thread) {
this.clientThread = thread;
}
public PopUpMessages getPopUps() {
return popUps;
}
public void setPopUps(PopUpMessages popUps) {
this.popUps = popUps;
}
@Override
public void updateUserList(String usersList) {
String[] users = CommonUtils.splitList(usersList);
mainWindow.getUsers().clear();
for (String user : users) {
LOGGER.info(user);
mainWindow.getUsers().addElement(user);
}
mainWindow.getUserList().invalidate();
}
@Override
public void updateUserListAdd(Message message) {
mainWindow.getUsers().addElement(message.getContent());
mainWindow.getUserList().invalidate();
message.setContent(LanguageController.getWord("connectmessage") + " "
+ message.getContent());
displayMessage(message);
}
@Override
public void updateUserListRemove(String content) {
mainWindow.getUsers().removeElement(content);
mainWindow.getUserList().invalidate();
}
@Override
public void registerMainWindow(MainClientWindow mainClientWindow) {
this.mainWindow = mainClientWindow;
}
@Override
public void sendMessage(String text) {
clientThread.sendMessage(clientThread.getManager().generateMessage(
MessageType.MESSAGE, chatsPanel.getSelectedChat(), text,
clientInfo.getUserName()));
}
/**
* @return the mainWindow
*/
public MainClientWindow getMainWindow() {
return mainWindow;
}
@Override
public void createChatRoom(List<String> list) {
if (list.contains(clientInfo.getUserName())) {
list.remove(clientInfo.getUserName());
}
if (list.size() != 0 && chatsPanel.checkPanels(list)) {
clientThread.sendMessage(new Message(list.toString(), 0,
MessageType.STARTCHAT, clientInfo.getUserName()));
} else {
chatsPanel.showTab(list);
}
}
@Override
public void toogleText() {
mainWindow.toogleText();
}
@Override
public void serverDisconnect() {
popUps.serverDisconnect();
mainWindow.toogleText();
chatsPanel.resetChats();
}
@Override
public void welcomeClient(Message message) {
popUps.welcomeClient(message);
mainWindow.setTitle(LanguageController.getWord("titleclient") + " "
+ message.getContent());
}
@Override
public void userNameRejected(Message message) {
popUps.showDialog(message);
String username = inputUserName();
if (username != null) {
clientThread.sendMessage(clientThread.getManager().generateMessage(
MessageType.CONNECT, 0, username, null));
}
}
@Override
public String inputUserName() {
LOGGER.info("Input user name");
String name = null;
name = popUps.inputUserName();
if (name != null) {
chatsPanel.resetChats();
} else {
clientThread.interrupt();
}
mainWindow.toogleText();
return name;
}
@Override
public void createTab(Message message) {
chatsPanel.addNewTab(message);
}
@Override
public void displayMessage(Message message) {
chatsPanel.processMessage(message);
}
}
|
package com.gxtc.huchuan.ui.common;
import android.app.Activity;
import android.content.Context;
import android.media.MediaMetadataRetriever;
import android.text.TextUtils;
import android.util.SparseArray;
import com.gxtc.commlibrary.utils.EventBusUtil;
import com.gxtc.commlibrary.utils.NetworkUtil;
import com.gxtc.commlibrary.utils.ToastUtil;
import com.gxtc.huchuan.Constant;
import com.gxtc.huchuan.MyApplication;
import com.gxtc.huchuan.bean.event.EventLoadBean;
import com.gxtc.huchuan.data.UserManager;
import com.gxtc.huchuan.data.deal.DealRepository;
import com.gxtc.huchuan.data.deal.DealSource;
import com.gxtc.huchuan.helper.RxTaskHelper;
import com.gxtc.huchuan.helper.ShareHelper;
import com.gxtc.huchuan.http.ApiCallBack;
import com.gxtc.huchuan.im.ui.ConversationActivity;
import com.gxtc.huchuan.im.ui.ConversationListActivity;
import com.gxtc.huchuan.service.DownloadService;
import com.gxtc.huchuan.utils.StringUtil;
import java.net.SocketTimeoutException;
import java.util.HashMap;
import rx.Observable;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
/**
* 来自 伍玉南 的装逼小尾巴 on 18/2/9.
* 公共的视频详情页面控制器
*/
public class CommonVideoPresenter implements CommonVideoContract.Presenter{
private CommonVideoContract.View mView;
private DealSource mDealData;
private String cover;
private String url;
public CommonVideoPresenter(CommonVideoContract.View view, String url, String cover) {
mView = view;
mView.setVideoPrsenter(this);
mDealData = new DealRepository();
this.cover = cover;
this.url = url;
}
@Override
public void saveVideo(Context context) {
DownloadService.startDownload(context, url, DownloadService.TYPE_VIDEO);
}
@Override
public void shareVideoToFriends(Activity activity) {
if(UserManager.getInstance().isLogin(activity)){
ShareHelper.INSTANCE.getBuilder().videoUrl(url).videoCover(cover);
ConversationListActivity.startActivity(activity, ConversationActivity.REQUEST_SHARE_VIDEO, Constant.SELECT_TYPE_SHARE);
}
}
//收藏视频 妈个鸡 收藏还要传视频的封面
@Override
public void collectVideo(final Activity activity) {
if(UserManager.getInstance().isLogin(activity)){
String bizType = "11";
String content = url;
String token = UserManager.getInstance().getToken();
String name = UserManager.getInstance().getUserName();
String userPic = UserManager.getInstance().getHeadPic();
final HashMap<String,String> map = new HashMap<>();
map.put("content",content);
map.put("bizType",bizType);
if(!TextUtils.isEmpty(userPic)) map.put("userPic",userPic);
if(!TextUtils.isEmpty(token)) map.put("token",token);
if(!TextUtils.isEmpty(name)) map.put("userName",name);
EventBusUtil.post(new EventLoadBean(true));
Subscription sub =
Observable.just(url)
.subscribeOn(Schedulers.io())
.map(new Func1<String, SparseArray<String>>() {
@Override
public SparseArray<String> call(String s) {
MediaMetadataRetriever retr = new MediaMetadataRetriever();
retr.setDataSource(s, new HashMap<String, String>());
String height = retr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT); // 视频高度
String width = retr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH); // 视频宽度
String time = retr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION); // 视频时长
SparseArray<String> temp = new SparseArray<String>();
temp.put(0, width);
temp.put(1, height);
temp.put(2, time);
return temp;
}
})
.observeOn(AndroidSchedulers.mainThread())
.filter(new Func1<SparseArray<String>, Boolean>() {
@Override
public Boolean call(SparseArray<String> stringSparseArray) {
if(TextUtils.isEmpty(cover)){
ToastUtil.showShort(activity, "收藏视频失败");
EventBusUtil.post(new EventLoadBean(false));
return false;
}else{
return true;
}
}
})
.subscribe(new Subscriber<SparseArray<String>>() {
@Override
public void onCompleted() {}
@Override
public void onError(Throwable e) {
EventBusUtil.post(new EventLoadBean(false));
if(e instanceof SocketTimeoutException){
ToastUtil.showShort(activity, "网络连接超时,请检查网络设置");
}else if(!NetworkUtil.isConnected(activity)) {
ToastUtil.showShort(activity, "未发现网络连接,请检查网络设置");
}else{
ToastUtil.showShort(activity, "收藏视频失败");
}
}
@Override
public void onNext(SparseArray<String> param) {
EventBusUtil.post(new EventLoadBean(false));
if(mView != null && param != null){
int width = StringUtil.toInt(param.get(0));
int height = StringUtil.toInt(param.get(1));
int time = StringUtil.toInt(param.get(2));
String title;
if(cover.contains("?")){
title = cover + "*" + time;
}else{
title = cover + "?" + width + "*" + height + "*" + time;
}
map.put("title", title);
saveCollect(map);
}
}
});
RxTaskHelper.getInstance().addTask(this, sub);
}
}
//保存收藏
private void saveCollect(HashMap<String, String> map){
mDealData.saveCollect(map, new ApiCallBack<Object>() {
@Override
public void onSuccess(Object data) {
ToastUtil.showShort(MyApplication.getInstance().getBaseContext(),"收藏成功");
}
@Override
public void onError(String errorCode, String message) {
ToastUtil.showShort(MyApplication.getInstance().getBaseContext(),"收藏失败");
}
});
}
@Override
public void start() {
}
@Override
public void destroy() {
mView = null;
RxTaskHelper.getInstance().cancelTask(this);
}
}
|
package com.example.wastemanagement.Models;
import com.google.firebase.firestore.Exclude;
import java.io.Serializable;
public class FeedbackComplainData implements Serializable {
String text="";
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
@Exclude public String id;
public FeedbackComplainData(String text) {
this.text = text;
}
public String getText() {
return text;
}
}
|
package com.chinasoft.education_manage.web.teacherservlet;
import com.chinasoft.education_manage.domain.Page;
import com.chinasoft.education_manage.domain.Teacher;
import com.chinasoft.education_manage.domain.TeacherPage;
import com.chinasoft.education_manage.service.TeacherService;
import com.chinasoft.education_manage.service.impl.TeacherServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
import java.util.Map;
@WebServlet("/teacherMessageServlet")
public class TeacherMessageServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// request.setCharacterEncoding("utf-8");
// TeacherService service = new TeacherServiceImpl();
// List<Teacher> list = service.findAllTeacher();
// request.setAttribute("list",list);
// request.getRequestDispatcher("/teachermessage.jsp").forward(request,response);
request.setCharacterEncoding("utf-8");
String pageNum = request.getParameter("pageNum");
String rows = request.getParameter("rows");
// System.out.println(pageNum);
Map<String, String[]> map = request.getParameterMap();
TeacherService service = new TeacherServiceImpl();
TeacherPage<Teacher> page = service.findGroupPage(pageNum,rows,map);
request.setAttribute("page",page);
request.setAttribute("map",map);
request.getRequestDispatcher("/teachermessage.jsp").forward(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}
|
package org.demo;
import com.ctrip.framework.apollo.spring.annotation.EnableApolloConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @program: apollodemo
* @description:
* @author: Ya
* @create: 2018-12-27 15:15
**/
@SpringBootApplication
@EnableApolloConfig //用来指示Apollo注入application namespace的配置到Spring环境中
public class App {
public static void main(String[] args){
SpringApplication.run(App.class,args);
}
}
|
package com.examples.io.generics.boundedtypeparameters;
import java.util.ArrayList;
import java.util.List;
public class Cage<T extends Animal> {
void addAnimal(T t) {
t.addAnimal();
}
public static void main(String[] args) {
Cat cat = new Cat();
Dog dog = new Dog();
Cage<Cat> catCage = new Cage();
catCage.addAnimal(cat);
Cage<Dog> dogCage = new Cage();
dogCage.addAnimal(dog);
List<Animal> animals = new ArrayList<>();
animals.add(cat);
animals.add(dog);
for(Animal a : animals) {
a.addAnimal();
}
}
}
|
package cn.net.bluechips.zsystem.repository;
import cn.com.topit.base.GenericRepository;
import cn.net.bluechips.zsystem.entity.VAccessControl;
/**
* @author terry
*
*/
public interface VAccessControlRepository extends GenericRepository<VAccessControl, Long>{
}
|
package alvin.basic;
import alvin.basic.entities.Person;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Provides;
import com.google.inject.matcher.Matchers;
import com.google.inject.persist.Transactional;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import javax.inject.Provider;
import javax.inject.Singleton;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertThat;
public class PersistenceWithGuiceTest {
private static final Logger LOGGER = LoggerFactory.getLogger(PersistenceWithGuiceTest.class);
private static final String[] TABLE_LIST = {"person"};
@Inject
private EntityManager em;
@Before
public void setUp() {
Guice.createInjector(new TestModule()).injectMembers(this);
em.getTransaction().begin();
try {
for (String table : TABLE_LIST) {
em.createNativeQuery("truncate table " + table).executeUpdate();
}
em.getTransaction().commit();
} catch (Exception e) {
em.getTransaction().rollback();
throw e;
}
}
@Test
public void test_save_person() {
Person expectedPerson = createPerson();
LOGGER.info("before persist: {}", expectedPerson);
em.getTransaction().begin();
try {
em.persist(expectedPerson);
em.getTransaction().commit();
} catch (Exception e) {
em.getTransaction().rollback();
throw e;
}
assertThat(expectedPerson.getId(), is(notNullValue()));
LOGGER.info("after persist: {}", expectedPerson);
em.clear();
Person actualPerson = em.find(Person.class, expectedPerson.getId());
LOGGER.info("after load: {}", actualPerson);
assertThat(expectedPerson.toString(), is(actualPerson.toString()));
}
private Person createPerson() {
Person person = new Person();
person.setName("Alvin");
person.setGender("M");
person.setEmail("alvin@fakeaddr.com");
person.setTelephone("13999999999");
person.setBirthday(LocalDateTime.of(1981, 3, 17, 0, 0).atOffset(ZoneOffset.UTC).toLocalDateTime());
return person;
}
}
class TransactionInterceptor implements MethodInterceptor {
@Inject
private Provider<EntityManager> emProvides;
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
EntityManager em = emProvides.get();
em.getTransaction().begin();
try {
Object result = invocation.proceed();
em.getTransaction().commit();
return result;
} catch (Exception e) {
em.getTransaction().rollback();
throw e;
}
}
}
class TestModule extends AbstractModule {
private static final ThreadLocal<EntityManager> ENTITY_MANAGER_CACHE = new ThreadLocal<>();
@Override
protected void configure() {
MethodInterceptor transactionInterceptor = new TransactionInterceptor();
requestInjection(transactionInterceptor);
bindInterceptor(Matchers.any(), Matchers.annotatedWith(Transactional.class), transactionInterceptor);
}
@Provides
@Singleton
public EntityManagerFactory provideEntityManagerFactory() {
return Persistence.createEntityManagerFactory("default");
}
@Provides
@Inject
public EntityManager provideEntityManager(EntityManagerFactory entityManagerFactory) {
EntityManager em = ENTITY_MANAGER_CACHE.get();
if (em == null) {
em = entityManagerFactory.createEntityManager();
ENTITY_MANAGER_CACHE.set(em);
}
return em;
}
}
|
package bioskop.model;
import java.util.ArrayList;
public class Sala {
private int id;
private String naziv;
private ArrayList<TipProjekcije> tipProjekcije;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNaziv() {
return naziv;
}
public void setNaziv(String naziv) {
this.naziv = naziv;
}
public ArrayList<TipProjekcije> getTipProjekcije() {
return tipProjekcije;
}
public void setTipProjekcije(ArrayList<TipProjekcije> tipProjekcije) {
this.tipProjekcije = tipProjekcije;
}
public Sala(int id, String naziv, ArrayList<TipProjekcije> tipProjekcije) {
this.id = id;
this.naziv = naziv;
this.tipProjekcije = tipProjekcije;
}
public Sala() {
// TODO Auto-generated constructor stub
}
}
|
package com.prangbi.android.prnetworkstatus;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getName();
private TextView textView = null;
private BroadcastReceiver broadcastReceiver = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView)findViewById(R.id.textView);
textView.setText("Active network type : " + NetworkStatus.getActiveNetworkType(this));
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("com.prangbi.android.prnetworkstatus.CONNECTIVITY_CHANGE");
broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if("com.prangbi.android.prnetworkstatus.CONNECTIVITY_CHANGE" == action) {
textView.setText("Active network type : " +
NetworkStatus.getActiveNetworkType(MainActivity.this));
}
}
};
registerReceiver(broadcastReceiver, intentFilter);
}
@Override
protected void onDestroy() {
super.onDestroy();
if(null != broadcastReceiver) {
unregisterReceiver(broadcastReceiver);
}
}
}
|
//Problem URL: https://www.spoj.com/problems/CTTC/
// My solution uses Stack to solve the problem. Using DSU (Disjoint Union Set) is also preferable solution for this problem.
import java.util.Scanner;
import java.util.Stack;
public class CountingChild {
public static void main(String [] args) {
Scanner sc = new Scanner(System.in);
int testcases = sc.nextInt();
// Iterate for var testcases times
for(int i=1; i <= testcases; i++) {
int n = sc.nextInt();
int[] childs = new int[n];
Stack<Integer> stack = new Stack<Integer>();
// Getting the route of traversal and process the count child action
for(int k =0; k<n*2; k++) {
int element = sc.nextInt();
if(stack.size()>0 && stack.peek() == element ) {
stack.pop();
} else {
if(stack.size() > 0 )
childs[stack.peek()-1] = childs[stack.peek()-1]+1;
stack.push(element);
}
}
// Printing the result
System.out.println("Case "+i+":");
for(int j=0; j<n; j++) {
System.out.println(j+1+" -> "+childs[j]);
}
}
}
}
|
package onlineMall.web.dao.Impl;
import onlineMall.web.dao.Dbutil;
import onlineMall.web.dao.ForumTopicDao;
import onlineMall.web.pojo.ForumTopic;
import org.springframework.stereotype.Repository;
import java.sql.ResultSet;
import java.util.ArrayList;
/**
* @ Package: onlineMall.web.dao.Impl
* @ Author :linsola
* @ Date :Created in 16:51 2018/12/23
* @ Description:
* @ Modified By:
* @ Version:
*/
@Repository
public class ForumTopicDaoImpl implements ForumTopicDao {
private Dbutil dbutil;
public ForumTopicDaoImpl(Dbutil dbutil){
this.dbutil = Dbutil.getInstance();
try{
dbutil.getConnection();
}catch (Exception e){
e.printStackTrace();
}
}
@Override
public boolean deleteForumTopic(int forumTopicId) {
boolean flag = false;
String sql = "DELETE FROM forum_topic WHERE FORUM_TOPIC_ID=?";
try {
int r = dbutil.executeUpdate(sql,forumTopicId);
if(r!=0){
flag = true;
}else {
flag = false;
}
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
@Override
public boolean insertForumTopic(ForumTopic forumTopic) {
boolean flag = false;
String sql = "insert into forum_topic(FORUM_TOPIC_ID,USER_ID,TITLE,CONTENT,TIME) values(?,?,?,?,?)";
try {
int r = dbutil.executeUpdate(sql,forumTopic.getForumTopicId(),forumTopic.getUserId(),forumTopic.getTitle(),forumTopic.getContent(),forumTopic.getTime());
if(r!=0){
flag = true;
}else {
flag = false;
}
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
@Override
public ArrayList<ForumTopic> selectForumTopic(String content) {
ArrayList<ForumTopic> list = new ArrayList<>();
String sql = "SELECT FORUM_TOPIC_ID,USER_ID,TITLE,CONTENT,TIME FROM forum_topic WHERE CONTENT LIKE ?";
try {
ResultSet rs = dbutil.executeQuery(sql,content);
while (rs.next()){
ForumTopic forumTopic = new ForumTopic();
forumTopic.setForumTopicId(rs.getInt("FORUM_TOPIC_ID"));
forumTopic.setUserId(rs.getInt("USER_ID"));
forumTopic.setTitle(rs.getString("TITLE"));
forumTopic.setContent(rs.getString("CONTENT"));
forumTopic.setTime(rs.getDate("TIME"));
list.add(forumTopic);
}
return list;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
public ArrayList<ForumTopic> queryAllFormTopic() {
ArrayList<ForumTopic> list = new ArrayList<>();
String sql = "SELECT FORUM_TOPIC_ID,USER_ID,TITLE,CONTENT,TIME FROM forum_topic";
try {
ResultSet rs = dbutil.executeQuery(sql);
while (rs.next()){
ForumTopic forumTopic = new ForumTopic();
forumTopic.setForumTopicId(rs.getInt("FORUM_TOPIC_ID"));
forumTopic.setUserId(rs.getInt("USER_ID"));
forumTopic.setTitle(rs.getString("TITLE"));
forumTopic.setContent(rs.getString("CONTENT"));
forumTopic.setTime(rs.getDate("TIME"));
list.add(forumTopic);
}
return list;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
|
package ch.mitti.tierwelt;
public abstract class Lebewesen {
boolean lebt;
public Lebewesen(){
lebt = true;
}
public boolean gibLebt(){
return lebt;
}
public abstract String gibLaut();
}
|
/*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aot.hint;
import java.util.Collections;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link ExecutableHint}.
*
* @author Phillip Webb
* @since 6.0
*/
class ExecutableHintTests {
@Test
void builtWithAppliesMode() {
ExecutableHint.Builder builder = new ExecutableHint.Builder("test", Collections.emptyList());
assertThat(builder.build().getMode()).isEqualTo(ExecutableMode.INVOKE);
ExecutableHint.builtWith(ExecutableMode.INTROSPECT).accept(builder);
assertThat(builder.build().getMode()).isEqualTo(ExecutableMode.INTROSPECT);
}
}
|
package com.halayang.pojo;
import java.util.Date;
public class JudgeQuestions {
private Integer id;//id
private String chapter;//所属章节
private String subject;//题目
private String type;//题目类型
private String answer;//答案
private Date createtime;//上传时间
private Integer start;// 起始行
private Integer rows;// 所取行数
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getChapter() {
return chapter;
}
public void setChapter(String chapter) {
this.chapter = chapter;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getAnswer() {
return answer;
}
public void setAnswer(String answer) {
this.answer = answer;
}
public Date getCreatetime() {
return createtime;
}
public void setCreatetime(Date createtime) {
this.createtime = createtime;
}
public Integer getStart() {
return start;
}
public void setStart(Integer start) {
this.start = start;
}
public Integer getRows() {
return rows;
}
public void setRows(Integer rows) {
this.rows = rows;
}
@Override
public String toString() {
return "JudgeQuestions{" +
"id=" + id +
", chapter='" + chapter + '\'' +
", subject='" + subject + '\'' +
", type='" + type + '\'' +
", answer='" + answer + '\'' +
", createtime=" + createtime +
'}';
}
}
|
package org.testing.testscript;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.testing.pages.Menu;
import org.testing.utilities.Datafile;
import org.testing.utilities.Screenshot;
import org.testing.utilities.Selectclass;
import org.testing.utilities.Waits;
import org.testng.annotations.Test;
import org.testing.base.Base;
public class TC1 extends Base
{
@Test
public void QAopening() throws InterruptedException, IOException
{
try
{
Menu m=new Menu(driver,pr);
m.Menuclick();
WebElement QAEngg= driver.findElement(By.xpath(pr.getProperty("QAEngg")));
QAEngg.click();
WebElement Contactname=driver.findElement(By.xpath(pr.getProperty("Contactname")));
Contactname.sendKeys(Datafile.dataread(0, 2));
WebElement Contactnumber=driver.findElement(By.xpath(pr.getProperty("Contactnumber")));
Contactnumber.sendKeys(Datafile.dataread(1, 2));
WebElement ContactEmail=driver.findElement(By.xpath(pr.getProperty("ContactEmail")));
ContactEmail.sendKeys(Datafile.dataread(2,2));
WebElement Totalexp=driver.findElement(By.xpath(pr.getProperty("Totalexp")));
Totalexp.sendKeys(Datafile.dataread(2, 4));
WebElement CurrentCTC= driver.findElement(By.xpath(pr.getProperty("CurrentCTC")));
CurrentCTC.sendKeys(Datafile.dataread(2, 5));
WebElement ExpectedCTC=driver.findElement(By.xpath(pr.getProperty("ExpectedCTC")));
ExpectedCTC.sendKeys(Datafile.dataread(2, 6));
WebElement NoticePeriod=driver.findElement(By.xpath(pr.getProperty("NoticePeriod")));
Selectclass.dropdown(NoticePeriod, 1);
WebElement Message=driver.findElement(By.xpath(pr.getProperty("Message")));
Message.sendKeys(Datafile.dataread(2, 7));
/// JavascriptExecutor js=(JavascriptExecutor)driver;
// js.executeScript("window.scrollBy(0,500)");
driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
WebElement Resume= driver.findElement(By.xpath(pr.getProperty("Resume")));
Resume.sendKeys(Datafile.dataread(2, 8));
Screenshot.takescreenshots(driver, "C:\\Users\\Awanish\\Desktop\\Screenshot\\TC1 pass.png");
// Logs.takelogs("TC1", "TC1 PASSESD");
}
catch(Exception e)
{
Screenshot.takescreenshots(driver, "C:\\Users\\Awanish\\Desktop\\Screenshot\\TC1 failed.png");
//Logs.takelogs("TC1", "TC1 failed");
}
}
}
|
package by.academy.classwork.lesson6;
|
package io.github.stormdb;
import java.util.Objects;
public class Delta<T> {
private final int position;
private final DeltaType type;
private final T delta;
public Delta(int position, DeltaType type, T delta) {
this.position = position;
this.type = type;
this.delta = delta;
}
public int getPosition() {
return position;
}
public DeltaType getType() {
return type;
}
public T getDelta() {
return delta;
}
@Override
public String toString() {
return "Delta{" +
"position=" + position +
", type=" + type +
", delta=" + delta +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Delta<?> delta1 = (Delta<?>) o;
return position == delta1.position && type == delta1.type && delta.equals(delta1.delta);
}
@Override
public int hashCode() {
return Objects.hash(position, type, delta);
}
}
|
/*
* Copyright 2017 Rundeck, Inc. (http://rundeck.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.rundeck.client.tool.options;
import lombok.Getter;
import lombok.Setter;
import picocli.CommandLine;
@Getter @Setter
public class ExecutionsFollowOptions extends FollowOptions {
@CommandLine.Option(names = {"-e", "--eid"}, description = "Execution ID", required = true)
String id;
@CommandLine.Option(names = {"-%", "--outformat"},
description = "Output format specifier for execution logs. You can use \"%%key\" where key is one of:" +
"time,level,log,user,command,node. E.g. \"%%user@%%node/%%level: %%log\"")
String outputFormat;
public boolean isOutputFormat() {
return outputFormat != null;
}
}
|
package com.example.yinzixuan.calculator;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
int firstNumber=0;
int Number=0;
int sign=0;
int Result=0;
int Number1=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button1=(Button)findViewById(R.id.button);
button1.setOnClickListener(new Click1());
Button button2=(Button)findViewById(R.id.button2);
button2.setOnClickListener(new Click2());
Button button3=(Button)findViewById(R.id.button3);
button3.setOnClickListener(new Click3());
Button button4=(Button)findViewById(R.id.button4);
button4.setOnClickListener(new Click4());
Button button5=(Button)findViewById(R.id.button5);
button5.setOnClickListener(new Click5());
Button button6=(Button)findViewById(R.id.button6);
button6.setOnClickListener(new Click6());
Button button7=(Button)findViewById(R.id.button7);
button7.setOnClickListener(new Click7());
Button button8=(Button)findViewById(R.id.button8);
button8.setOnClickListener(new Click8());
Button button9=(Button)findViewById(R.id.button9);
button9.setOnClickListener(new Click9());
Button button0=(Button)findViewById(R.id.button10);
button0.setOnClickListener(new Click0());
Button buttonadd=(Button)findViewById(R.id.button11);
buttonadd.setOnClickListener(new Clickadd());
Button button_equal=(Button)findViewById(R.id.button12);
button_equal.setOnClickListener(new Click_equal());
Button Restart=(Button)findViewById(R.id.restart);
Restart.setOnClickListener(new Click_Restart());
Button button13=(Button)findViewById(R.id.button13);
button13.setOnClickListener(new Click_button13());
Button button14=(Button)findViewById(R.id.button14);
button14.setOnClickListener(new Click_button14());
Button button15=(Button)findViewById(R.id.button15);
button15.setOnClickListener(new Click_button15());
Button radiobutton2=(Button)findViewById(R.id.radioButton2);
radiobutton2.setOnClickListener(new Click_radioButton2());
Button radiobutton3=(Button)findViewById(R.id.radioButton);
radiobutton3.setOnClickListener(new Click_radioButton3());
}
class Click1 implements View.OnClickListener{
public void onClick(View v) {
if (sign == 0) {
EditText txt = (EditText) findViewById(R.id.editText);
txt.setText(txt.getText() + "1");
if (firstNumber == 0)
firstNumber = 1;
else firstNumber = firstNumber * 10 + 1;
}
else {
EditText txt = (EditText) findViewById(R.id.editText);
txt.setText(txt.getText() + "1");
if (Number == 0)
Number = 1;
else Number = Number * 10 + 1;
}
}
}
class Click2 implements View.OnClickListener{
public void onClick(View v){
if(sign==0)
{EditText txt=(EditText)findViewById(R.id.editText);
txt.setText(txt.getText()+"2");
if(firstNumber==0)
firstNumber=2;
else firstNumber=firstNumber*10+2;}
else {
EditText txt = (EditText) findViewById(R.id.editText);
txt.setText(txt.getText() + "2");
if (Number == 0)
Number = 2;
else Number = Number * 10 +2;
}
}
}
class Click3 implements View.OnClickListener{
public void onClick(View v){
if(sign==0){
EditText txt=(EditText)findViewById(R.id.editText);
txt.setText(txt.getText()+"3");
if(firstNumber==0)
firstNumber=3;
else firstNumber=firstNumber*10+3;}
else {
EditText txt = (EditText) findViewById(R.id.editText);
txt.setText(txt.getText() + "3");
if (Number == 0)
Number =3;
else Number = Number * 10 + 3;
}
}
}
class Click4 implements View.OnClickListener{
public void onClick(View v){
if(sign==0){
EditText txt=(EditText)findViewById(R.id.editText);
txt.setText(txt.getText()+"4");
if(firstNumber==0)
firstNumber=4;
else firstNumber=firstNumber*10+4;}
else {
EditText txt = (EditText) findViewById(R.id.editText);
txt.setText(txt.getText() + "4");
if (Number == 0)
Number = 4;
else Number = Number * 10 + 4;
}
}
}
class Click5 implements View.OnClickListener{
public void onClick(View v){
if(sign==0){
EditText txt=(EditText)findViewById(R.id.editText);
txt.setText(txt.getText()+"5");
if(firstNumber==0)
firstNumber=5;
else firstNumber=firstNumber*10+5;}
else {
EditText txt = (EditText) findViewById(R.id.editText);
txt.setText(txt.getText() + "5");
if (Number == 0)
Number = 5;
else Number = Number * 10 + 5;
}
}
}
class Click6 implements View.OnClickListener{
public void onClick(View v){
if(sign==0){
EditText txt=(EditText)findViewById(R.id.editText);
txt.setText(txt.getText()+"6");
if(firstNumber==0)
firstNumber=6;
else firstNumber=firstNumber*10+6;}
else {
EditText txt = (EditText) findViewById(R.id.editText);
txt.setText(txt.getText() + "6");
if (Number == 0)
Number = 6;
else Number = Number * 10 + 6;
}
}
}
class Click7 implements View.OnClickListener{
public void onClick(View v){
if(sign==0){
EditText txt=(EditText)findViewById(R.id.editText);
txt.setText(txt.getText()+"7");
if(firstNumber==0)
firstNumber=7;
else firstNumber=firstNumber*10+7;
}
else {
EditText txt = (EditText) findViewById(R.id.editText);
txt.setText(txt.getText() + "7");
if (Number == 0)
Number = 7;
else Number = Number * 10 + 7;
}
}
}
class Click8 implements View.OnClickListener{
public void onClick(View v){
if(sign==0){
EditText txt=(EditText)findViewById(R.id.editText);
txt.setText(txt.getText()+"8");
if(firstNumber==0)
firstNumber=8;
else firstNumber=firstNumber*10+8;}
else {
EditText txt = (EditText) findViewById(R.id.editText);
txt.setText(txt.getText() + "8");
if (Number == 0)
Number = 8;
else Number = Number * 10 + 8;
}
}
}
class Click9 implements View.OnClickListener{
public void onClick(View v){
if(sign==0){
EditText txt=(EditText)findViewById(R.id.editText);
txt.setText(txt.getText()+"9");
if(firstNumber==0)
firstNumber=9;
else firstNumber=firstNumber*10+9;}
else {
EditText txt = (EditText) findViewById(R.id.editText);
txt.setText(txt.getText() + "9");
if (Number == 0)
Number = 9;
else Number = Number * 10 + 9;
}
}
}
class Click0 implements View.OnClickListener{
public void onClick(View v){
if(sign==0){
EditText txt=(EditText)findViewById(R.id.editText);
txt.setText(txt.getText()+"0");
if(firstNumber==0)
firstNumber=0;
else firstNumber=firstNumber*10+0;}
else {
EditText txt = (EditText) findViewById(R.id.editText);
txt.setText(txt.getText() + "0");
if (Number == 0)
Number = 0;
else Number = Number * 10 + 0;
}
}
}
class Clickadd implements View.OnClickListener{
public void onClick(View v){
EditText TextfistNumber=(EditText) findViewById(R.id.editText2);
TextfistNumber.setText(""+firstNumber);
EditText txt=(EditText) findViewById(R.id.editText);
txt.setText("");
Number1=firstNumber;
firstNumber=0;
sign=1;
}
}
class Click_equal implements View.OnClickListener{
public void onClick(View v){
if(sign==1)
{
Result=Number1+Number;
}
else if(sign==2) {
Result=Number1-Number;
}
else if(sign==3){
Result=Number1*Number;
}
else if(sign==4){
Result=Number1/Number;
}
EditText a=(EditText) findViewById(R.id.editText3);
a.setText(""+Result);
}
}
class Click_button13 implements View.OnClickListener{
public void onClick(View v){
EditText TextfistNumber=(EditText) findViewById(R.id.editText2);
TextfistNumber.setText(""+firstNumber);
EditText txt=(EditText) findViewById(R.id.editText);
txt.setText("");
Number1=firstNumber;
firstNumber=0;
sign=2;
}
}
class Click_button14 implements View.OnClickListener{
public void onClick(View v){
EditText TextfistNumber=(EditText) findViewById(R.id.editText2);
TextfistNumber.setText(""+firstNumber);
EditText txt=(EditText) findViewById(R.id.editText);
txt.setText("");
Number1=firstNumber;
firstNumber=0;
sign=3;
}
}
class Click_button15 implements View.OnClickListener{
public void onClick(View v){
EditText TextfistNumber=(EditText) findViewById(R.id.editText2);
TextfistNumber.setText(""+firstNumber);
EditText txt=(EditText) findViewById(R.id.editText);
txt.setText("");
Number1=firstNumber;
firstNumber=0;
sign=4;
}
}
class Click_Restart implements View.OnClickListener{
public void onClick(View v){
firstNumber=0;
Number=0;
sign=0;
Result=0;
Number1=0;
EditText txt1=(EditText)findViewById(R.id.editText);
txt1.setText("");
EditText txt2=(EditText)findViewById(R.id.editText2);
txt2.setText("");
EditText txt3=(EditText)findViewById(R.id.editText3);
txt3.setText("");
}
}
class Click_radioButton2 implements View.OnClickListener{
public void onClick(View v){
Intent intent=new Intent(MainActivity.this,Main2Activity.class);
startActivity(intent);
}
}
class Click_radioButton3 implements View.OnClickListener{
public void onClick(View v){
Intent intent=new Intent(MainActivity.this,MainActivity.class);
startActivity(intent);
}
}
}
|
package my.yrzy.admin.controller;
import lombok.extern.slf4j.Slf4j;
import my.yrzy.common.common.Paging;
import my.yrzy.common.exception.JsonResponseException;
import my.yrzy.common.exception.ServiceException;
import my.yrzy.common.util.BaseUser;
import my.yrzy.common.util.UserUtil;
import my.yrzy.trade.model.Order;
import my.yrzy.trade.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* Created by yangzefeng on 15/1/12
*/
@Controller @Slf4j
@RequestMapping(value = "/api/admin/order")
public class Orders {
@Autowired
private OrderService orderService;
@RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public Paging<Order> pagingOrder(@RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNo,
@RequestParam(value = "size", required = false, defaultValue = "20") Integer size,
@RequestParam(value = "orderId", required = false) Long orderId) {
BaseUser user = UserUtil.getUser();
if(user == null) {
throw new JsonResponseException(401, "user.not.login");
}
try {
return orderService.adminPaging(pageNo, size, orderId);
}catch (ServiceException se) {
throw new JsonResponseException(se.getMessage());
}catch (Exception e) {
log.error("fail to paging order, cause:{}", e);
throw new JsonResponseException("order.query.fail");
}
}
}
|
package com.example.demo.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
/**
* PageInfo
*
* @author ZhangJP
* @date 2020/7/29
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class PageInfo<T> {
/**
* 总数
*/
private long total;
/**
* 当前页
*/
protected long current;
/**
* 总页数
*/
private long pages;
/**
* 查询数据列表
*/
private List<T> records;
}
|
package com.bofsoft.laio.customerservice.dialog;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import com.bofsoft.laio.common.MyLog;
import com.bofsoft.laio.customerservice.R;
public class WaitDialog extends Dialog implements View.OnClickListener {
MyLog myLog = new MyLog(WaitDialog.class);
Context context;
TextView textTitle;
TextView textContent;
TextView btnOK;
String title;
String content;
private TextView tv;
public WaitDialog(Context context) {
super(context, R.style.WaitDialog);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog_wait);
TextView waitDialogDismiss = (TextView) findViewById(R.id.waitDialogDismiss);
tv = (TextView) findViewById(R.id.waitTv);
waitDialogDismiss.setOnClickListener(this);
}
@Override
public void onClick(View arg0) {
this.dismiss();
myLog.i("waitDialog.dismiss()");
}
public void show(String text) {
this.show();
tv = (TextView) this.getWindow().findViewById(R.id.waitTv);
tv.setText(text);
}
}
|
/**
*
*/
package com.intertec.listusername.service;
import com.intertec.listusername.model.User;
/**
* @author nandopc001
*
*/
public interface UserService {
User addUser(String user);
}
|
package io.zahid.selenium.tutorial.site.toolsqa;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class PracticeFormPage {
/**
*
* https://www.toolsqa.com/automation-practice-form
*
*/
WebDriver driver;
@FindBy(partialLinkText = "Link Test")
WebElement partialLinkTestLink;
@FindBy(linkText = "Link Test")
WebElement linkTestLink;
@FindBy(name = "firstname")
WebElement firstNameInput;
@FindBy(id = "lastname")
WebElement lastNameInput;
@FindBy(id = "buttonwithclass")
WebElement simpleButton;
@FindBy(id = "sex-0")
WebElement maleRadioButton;
@FindBy(id = "sex-1")
WebElement femaleRadioButton;
@FindBy(id = "exp-0")
WebElement exp1RadioButton;
@FindBy(id = "exp-1")
WebElement exp2RadioButton;
@FindBy(id = "exp-2")
WebElement exp3RadioButton;
@FindBy(id = "exp-3")
WebElement exp4RadioButton;
@FindBy(id = "exp-4")
WebElement exp5RadioButton;
@FindBy(id = "exp-5")
WebElement exp6RadioButton;
@FindBy(id = "exp-6")
WebElement exp7RadioButton;
@FindBy(id = "datepicker")
WebElement dateInput;
@FindBy(id = "profession-0")
WebElement manualTesterCheckbox;
@FindBy(id = "profession-1")
WebElement automationTesterCheckbox;
@FindBy(id = "photo")
WebElement profilePictureUploadInput;
@FindBy(linkText = "Selenium Automation Hybrid Framework")
WebElement seleniumAutomationHybridFrameworkDownloadLink;
@FindBy(linkText = "Test File to Download")
WebElement testFileToDownloadDownloadLink;
@FindBy(id = "tool-0")
WebElement qtpCheckbox;
@FindBy(id = "tool-1")
WebElement seleniumIDECheckbox;
@FindBy(id = "tool-2")
WebElement seleniumWebdriverCheckbox;
@FindBy(id = "continents")
WebElement continentsSingleSelect;
@FindBy(id = "continentsmultiple")
WebElement continentsMultipleSelect;
@FindBy(id = "selenium_commands")
WebElement seleniumCommandsMultipleSelect;
@FindBy(id = "submit")
WebElement button;
@FindBy(id = "submit1")
WebElement button2;
@FindBy(id = "submit2")
WebElement button3;
@FindBy(id = "submit3")
WebElement button4;
@FindBy(xpath = "//*[@id=\"NextedText\"]/span")
WebElement text1;
@FindBy(xpath = "//*[@id=\"NextedText\"]/text()")
WebElement text2;
@FindBy(xpath = "//*[@id=\"beverages\"]/li[1]")
WebElement coffeeText;
@FindBy(xpath = "//*[@id=\"beverages\"]/li[2]")
WebElement teaText;
@FindBy(xpath = "//*[@id=\"beverages\"]/li[3]")
WebElement milkText;
@FindBy(xpath = "//*[@id=\"beverages\"]/li[4]")
WebElement skimmedMilkText;
public PracticeFormPage(WebDriver driver) {
this.driver = driver;
PageFactory.initElements(driver, this);
}
public void clickPartialLinkTestLink() {
partialLinkTestLink.click();
}
public void clickLinkTestLink() {
linkTestLink.click();
}
public void inputFirstName(String firstName) {
firstNameInput.sendKeys(firstName);
}
public void inputLastName(String lastName) {
lastNameInput.sendKeys(lastName);
}
public void clickSimpleButton() {
simpleButton.click();
}
public void clickMaleRadioButton() {
maleRadioButton.click();
}
public void clickFemaleRadioButton() {
femaleRadioButton.click();
}
public void clickYearsOfExpereince1() {
exp1RadioButton.click();
}
public void clickYearsOfExpereince2() {
exp2RadioButton.click();
}
public void clickYearsOfExpereince3() {
exp3RadioButton.click();
}
public void clickYearsOfExpereince4() {
exp4RadioButton.click();
}
public void clickYearsOfExpereince5() {
exp5RadioButton.click();
}
public void clickYearsOfExpereince6() {
exp6RadioButton.click();
}
public void clickYearsOfExpereince7() {
exp7RadioButton.click();
}
public void inputDate(String date) {
dateInput.sendKeys(date);
}
public void clickManualTesterCheckbox() {
manualTesterCheckbox.click();
}
public void clickAutomationTesterCheckbox() {
automationTesterCheckbox.click();
}
}
|
package cn.v5cn.v5cms.controller;
import cn.v5cn.v5cms.service.SystemRoleService;
import cn.v5cn.v5cms.entity.SystemRole;
import cn.v5cn.v5cms.util.HttpUtils;
import cn.v5cn.v5cms.util.SystemUtils;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.session.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;
import static cn.v5cn.v5cms.util.MessageSourceHelper.getMessage;
/**
* Created by ZXF-PC1 on 2015/6/26.
*/
@Controller
@RequestMapping("/manager/role")
public class SystemRoleController {
private static final Logger LOGGER = LoggerFactory.getLogger(SystemRoleController.class);
@Autowired
private SystemRoleService systemRoleService;
@RequestMapping(value = "/list/{p}",method = {RequestMethod.GET,RequestMethod.POST})
public String roleList(SystemRole role,@PathVariable Integer p,HttpServletRequest request,ModelMap modelMap){
Session session = SystemUtils.getShiroSession();
if(StringUtils.isNotBlank(role.getName())){
session.setAttribute("roleSearch",role);
modelMap.addAttribute("searchRole",role);
}else{
session.setAttribute("roleSearch",null);
}
Object searchObj = session.getAttribute("roleSearch");
Page<SystemRole> result = systemRoleService.findRoleByRoleNamePageable((searchObj == null ? (new SystemRole()):((SystemRole)searchObj)),p);
modelMap.addAttribute("roles",result);
modelMap.addAttribute("pagination", SystemUtils.pagination(result, HttpUtils.getContextPath(request) + "/manager/role/list"));
return "userauth/role_list";
}
@RequestMapping(value = "/edit",method = RequestMethod.GET)
public String roleEdit(ModelMap model){
model.addAttribute("role",new SystemRole());
return "userauth/role_edit";
}
@ResponseBody
@RequestMapping(value = "/edit",method = RequestMethod.POST)
public ImmutableMap<String,Object> addUpdateRole(String resIds,@Valid SystemRole role,BindingResult bindingResult){
if(bindingResult.hasErrors()){
Map<String, Object> errorMessage = Maps.newHashMap();
errorMessage.put("status", 0);
List<FieldError> fes = bindingResult.getFieldErrors();
for (FieldError fe : fes) {
errorMessage.put("message",fe.getField()+","+fe.getDefaultMessage());
}
return ImmutableMap.<String, Object>builder().putAll(errorMessage).build();
}
//新增操作
if(role.getId() == null){
Long result = systemRoleService.save(role,resIds);
if(result !=null && result != 0L){
LOGGER.info("新增角色成功,{}",role);
return ImmutableMap.<String, Object>of("status","1","message",getMessage("role.addsuccess.message"));
}
LOGGER.warn("新增角色失败,{}",result);
return ImmutableMap.<String, Object>of("status","0","message",getMessage("role.addfailed.message"));
}
//修改操作
try {
systemRoleService.save(role,resIds);
} catch (Exception e) {
e.printStackTrace();
LOGGER.error("修改角色失败,{},失败堆栈错误:{}",role,e.getMessage());
return ImmutableMap.<String, Object>of("status","0","message",getMessage("role.updatefailed.message"));
}
LOGGER.info("修改角色成功,{}",role);
return ImmutableMap.<String, Object>of("status","1","message",getMessage("role.updatesuccess.message"));
}
}
|
package com.andy.wap;
import java.util.NoSuchElementException;
/**
* The Queue class represents an immutable first-in-first-out(FIFO) queue of objects.
* Immutable queue can be implemented by two immutable stacks : enqueueStack and dequeueStack.
* enqueueStack is used to enqueue element and dequeueStack is used to dequeue element.
*
* @date May 26, 2014--9:26:48 AM
* @author Andy
* @param <E>
*/
public class ImmutableQueue<E> {
private ImmutableStack<E> enqueueStack;
private ImmutableStack<E> dequeueStack;
/**
* requires default constructor.
*/
@SuppressWarnings("unchecked")
public ImmutableQueue() {
// modify this constructor if necessary, but do not remove default constructor
this.enqueueStack = ImmutableStack.newStack();
this.dequeueStack = ImmutableStack.newStack();
}
//add other constructors if necessary
private ImmutableQueue(ImmutableStack<E> enqueueStack, ImmutableStack<E> dequeueStack) {
this.enqueueStack = enqueueStack;
this.dequeueStack = dequeueStack;
}
/**
* Returns the queue that adds an item into the tail of this queue without modifying this queue.
* <pre>
* e.g.
* When this queue represents the queue (2,1,2,2,6) and we enqueue the value 4 into this queue,
* this method returns a new queue (2,1,2,2,6,4)
* and this object still represents the queue (2,1,2,2,6).
* </pre>
* If the element e is null, throws IllegalArgumentException.
* @param e
* @return
* @throws IllegalArgumentException
*/
public ImmutableQueue<E> enqueue(E e) {
if (null == e)
throw new IllegalArgumentException();
return new ImmutableQueue<E>(this.enqueueStack.push(e), this.dequeueStack);
}
/**
* Returns the queue that removes the object at the head of this queue without modifying this queue.
* <pre>
* e.g.
* When this queue represents the queue (7,1,3,3,5,1),
* this method returns a new queue (1,3,3,5,1)
* and this object still represents the queue (7,1,3,3,5,1).
* </pre>
* If this queue is empty, throws java.util.NoSuchElementException.
* @return
* @throws java.util.NoSuchElementException
*/
@SuppressWarnings("unchecked")
public ImmutableQueue<E> dequeue(){
if (this.isEmpty())
throw new NoSuchElementException();
if (!this.dequeueStack.isEmpty()) {
return new ImmutableQueue<E>(this.enqueueStack, this.dequeueStack.tail);
} else {
return new ImmutableQueue<E>(ImmutableStack.newStack(),
this.enqueueStack.toDequeuStack().tail);
}
}
/**
* Looks at the object which is the head of this queue without removing it from the queue.
* <pre>
* e.g.
* When this queue represents the queue (7,1,3,3,5,1),
* this method returns 7 and this object still represents the queue (7,1,3,3,5,1)
* </pre>
* If this queue is empty, throws java.util.NoSuchElementException.
* @return
* @throws java.util.NoSuchElementException
*/
@SuppressWarnings("unchecked")
public E peek(){
if (this.isEmpty())
throw new NoSuchElementException();
if (this.dequeueStack.isEmpty()){
this.dequeueStack = this.enqueueStack.toDequeuStack();
this.enqueueStack = ImmutableStack.newStack();
}
return this.dequeueStack.head;
}
/**
* Returns the number of objects in this queue.
* @return
*/
public int size(){
return this.enqueueStack.size + this.dequeueStack.size;
}
public boolean isEmpty() {
return size() == 0;
}
/**
* Internal class ImmutableStack to implement enqueueStack and dequeueStack.
*
* @date May 27, 2014--11:01:11 AM
* @author Andy
* @param <E>
*/
private static class ImmutableStack<E> {
private E head;
private ImmutableStack<E> tail;
private int size;
private ImmutableStack(E head, ImmutableStack<E> tail) {
this.head = head;
this.tail = tail;
this.size = tail.size + 1;
}
/**
* Default constructor.
*/
private ImmutableStack() {
this.head = null;
this.tail = null;
this.size = 0;
}
/**
* Reverse an nonempty enqueueStack to dequeueStack.
*
* @return
*/
public ImmutableStack<E> toDequeuStack() {
ImmutableStack<E> dequeueStack = new ImmutableStack<E>();
ImmutableStack<E> enqueueStack = this;
while (!enqueueStack.isEmpty()) {
dequeueStack = dequeueStack.push(enqueueStack.head);
enqueueStack = enqueueStack.tail;
}
return dequeueStack;
}
public ImmutableStack<E> push(E e) {
return new ImmutableStack<E>(e, this);
}
@SuppressWarnings("rawtypes")
public static ImmutableStack newStack() {
return new ImmutableStack();
}
public boolean isEmpty() {
return this.size == 0;
}
}
}
|
package com.liux.framework.util;
/**
* 2018/2/28
* By Liux
* lx0758@qq.com
*/
public class OtherUtil {
}
|
package uk.co.mtford.jalp.abduction.logic.instance.constraints;
import choco.kernel.model.constraints.Constraint;
import choco.kernel.model.variables.Variable;
import uk.co.mtford.jalp.abduction.logic.instance.IInferableInstance;
import uk.co.mtford.jalp.abduction.logic.instance.IUnifiableInstance;
import uk.co.mtford.jalp.abduction.logic.instance.term.ITermInstance;
import uk.co.mtford.jalp.abduction.logic.instance.term.VariableInstance;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Represents a constraint e.g. X<Y
*/
public interface IConstraintInstance extends IInferableInstance {
/**
* Performs conversion to choco representation of this constraint, or solves the constraint natively.
*
* @param possSubst Substitutions.
* @param chocoConstraints Currently collected choco constraint representations.
* @param chocoVariables Current collection choco variable representations.
* @param constraintMap Maps internal representations onto choco representations.
* @return
*/
boolean reduceToChoco(List<Map<VariableInstance,IUnifiableInstance>> possSubst, List<Constraint> chocoConstraints, HashMap<ITermInstance, Variable> chocoVariables, HashMap<Constraint,IConstraintInstance> constraintMap);
/**
* Performs conversion to negative choco representation of this constraint, or solves the constraint natively.
*
* e.g. X<Y would be X>=Y
*
* @param possSubst Substitutions.
* @param chocoConstraints Currently collected choco constraint representations.
* @param chocoVariables Current collection choco variable representations.
* @param constraintMap Maps internal representations onto choco representations.
* @return
*/
boolean reduceToNegativeChoco(List<Map<VariableInstance,IUnifiableInstance>> possSubst, List<Constraint> chocoConstraints, HashMap<ITermInstance, Variable> chocoVariables, HashMap<Constraint,IConstraintInstance> constraintMap);
}
|
package com.fbse.recommentmobilesystem.XZHL0410;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.fbse.recommentmobilesystem.R;
public class XZHL0410_TopGridAdapter extends BaseAdapter {
private List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
private Context context;
public XZHL0410_TopGridAdapter(List<Map<String, Object>> list,
Context context) {
this.list = list;
this.context = context;
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int arg0) {
return list.get(arg0);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = View.inflate(context, R.layout.xzhl0410_topitem, null);
if (convertView != null) {
LinearLayout setbg = (LinearLayout) convertView
.findViewById(R.id.setbg);
if (position > 3) {
setbg.setBackgroundResource(R.drawable.top_item_background_shape_white);
} else {
setbg.setBackgroundResource(R.drawable.top_item_background_shape);
}
TextView functionlist_text = (TextView) convertView
.findViewById(R.id.top_item);
functionlist_text.setText(list.get(position).get("top_item") + "");
if (position % 2 == 1) {
functionlist_text.setTextColor(android.graphics.Color.RED);
}
}
return convertView;
}
}
|
package classes.core.DAO;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import dominio.endereco.Endereco;
import dominio.endereco.Locacao;
import dominio.evento.Evento;
import dominio.evento.IDominio;
import dominio.evento.Rateio;
public class EventoDAO extends AbsDAO {
@Override
public void salvar(IDominio entidade) throws SQLException {
conectar();
PreparedStatement ps = null;
RateioDAO rateioDAO = new RateioDAO();
EnderecoDAO enderecoDAO = new EnderecoDAO();
// Converte a entidade genérica em evento
Evento evento = (Evento) entidade;
if(evento.getProdutos() != null) {
EstoqueEventoDAO estoqueDAO = new EstoqueEventoDAO();
estoqueDAO.salvar(evento);
} else {
try {
enderecoDAO.salvar(evento.getEndereco());
evento.getEndereco().setId(enderecoDAO.consultar());
rateioDAO.salvar(evento.getRateio());
evento.getRateio().setId(rateioDAO.consultar());
conexao.setAutoCommit(false);
StringBuilder sql = new StringBuilder(); // variável para concatenar as Strings
// inicia a declaração da query
sql.append("INSERT INTO eventos (nome, data, hora, max_pessoas, tipo_evento, situacao, cat_id, end_id, user_id, loc_id, rat_id, pct_lucro)");
sql.append(" VALUES(?,?,?,?,?,?,?,?,?,?,?,?)");
ps = conexao.prepareStatement(sql.toString());
// insere os objetos na query:
ps.setString(1, evento.getNome());
// converte a data
Timestamp time = new Timestamp(evento.getData().getTime());
ps.setTimestamp(2, time);
ps.setString(3, evento.getHora());
ps.setInt(4, evento.getQdtMaximaPessoas());
ps.setString(5, evento.getTipoPagamento());
ps.setString(6, evento.getSituacao());
ps.setInt(7, evento.getCategoria());
ps.setInt(8, evento.getEndereco().getId());
ps.setInt(9, evento.getAdministrador().getId());
ps.setInt(10, evento.getLocacao().getId());
ps.setInt(11, evento.getRateio().getId());
ps.setDouble(12, evento.getEntrada());
ps.executeUpdate();
conexao.commit();
} catch (SQLException e) {
try {
conexao.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
} // fim do try/catch INTERNO
e.printStackTrace();
} /* fim do try/catch */ finally {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
} // final FINALLY
}
} // final SALVAR
@Override
public void alterar(IDominio entidade) throws SQLException {
conectar();
PreparedStatement ps = null;
RateioDAO rateioDAO = new RateioDAO();
EnderecoDAO enderecoDAO = new EnderecoDAO();
// Converte a entidade genérica em evento
Evento evento = (Evento) entidade;
if(evento.getProdutos() != null) {
EstoqueEventoDAO estoqueDAO = new EstoqueEventoDAO();
estoqueDAO.alterar(evento);
} else {
try {
enderecoDAO.alterar(evento.getEndereco());
//evento.getEndereco().setId(enderecoDAO.consultar());
rateioDAO.alterar(evento.getRateio());
conexao.setAutoCommit(false);
StringBuilder sql = new StringBuilder(); // variável para concatenar as Strings
// inicia a declaração da query
sql.append("UPDATE eventos set nome=?, data=?, hora=?, max_pessoas=?, tipo_evento=?, situacao=?, cat_id=?, end_id=?, user_id=?, loc_id=?, pct_lucro=?");
sql.append(" where evt_id=?");
ps = conexao.prepareStatement(sql.toString());
// insere os objetos na query:
ps.setString(1, evento.getNome());
// converte a data
Timestamp time = new Timestamp(evento.getData().getTime());
ps.setTimestamp(2, time);
ps.setString(3, evento.getHora());
ps.setInt(4, evento.getQdtMaximaPessoas());
ps.setString(5, evento.getTipoPagamento());
ps.setString(6, evento.getSituacao());
ps.setInt(7, evento.getCategoria());
ps.setInt(8, evento.getEndereco().getId());
ps.setInt(9, evento.getAdministrador().getId());
ps.setInt(10, evento.getLocacao().getId());
ps.setDouble(11, evento.getEntrada());
ps.setInt(12, evento.getId());
ps.executeUpdate();
conexao.commit();
} catch (SQLException e) {
try {
conexao.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
} // fim do try/catch INTERNO
e.printStackTrace();
} /* fim do try/catch */ finally {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
} // final FINALLY
}
} // final ALTERAR
@Override
public List<IDominio> consultar(IDominio entidade) throws SQLException{
conectar();
PreparedStatement ps = null;
RateioDAO rateioDAO = new RateioDAO();
EnderecoDAO enderecoDAO = new EnderecoDAO();
List<IDominio> eventos = new ArrayList<IDominio>();
// Converte a entidade genérica em evento
Evento evento = (Evento) entidade;
if(evento.getProdutos() != null) {
System.out.println("ENTROU NO CONSULTAR INTERNO :::::::::::::::::");
EstoqueEventoDAO estoqueDAO = new EstoqueEventoDAO();
return estoqueDAO.consultar(evento);
} else {
try {
conexao.setAutoCommit(false);
StringBuilder sql = new StringBuilder(); // variável para concatenar as Strings
// inicia a declaração da query
if(evento.isConvidado() == true) {
sql.append("SELECT * from eventos ev left join enderecos end on end.end_id = ev.end_id left join categorias c");
sql.append(" on c.cat_id = ev.cat_id left join rateios r on r.rat_id = ev.rat_id left join locacoes l on l. loc_id = ev.loc_id where 1=1 AND user_id != ?");
ps = conexao.prepareStatement(sql.toString());
ps.setInt(1, evento.getAdministrador().getId());
} else {
sql.append("SELECT * from eventos ev left join enderecos end on end.end_id = ev.end_id left join categorias c");
sql.append(" on c.cat_id = ev.cat_id left join rateios r on r.rat_id = ev.rat_id left join locacoes l on l. loc_id = ev.loc_id where 1=1 AND user_id=?");
if(evento.getId() != 0) {
sql.append(" AND evt_id=?");
}
if(evento.getNome() != null && evento.getNome() != "") {
sql.append(" AND nome=?");
}
ps = conexao.prepareStatement(sql.toString());
ps.setInt(1, evento.getAdministrador().getId());
if(evento.getId() != 0) {
ps.setInt(2, evento.getId());
}
if(evento.getNome() != null && evento.getNome() != "") {
ps.setString(3, evento.getNome());
}
}
ResultSet resultado = ps.executeQuery();
while(resultado.next()) {
Evento eventoBuscado = new Evento();
Endereco enderecoBuscado = new Endereco();
Rateio rateioBuscado = new Rateio();
Locacao locacaoBuscada = new Locacao();
eventoBuscado.setId(resultado.getInt("evt_id"));
eventoBuscado.setNome(resultado.getString("nome"));
eventoBuscado.setQdtMaximaPessoas(resultado.getInt("max_pessoas"));
eventoBuscado.setTipoPagamento(resultado.getString("tipo_evento"));
eventoBuscado.setData(resultado.getDate("data"));
eventoBuscado.setHora(resultado.getString("hora"));
eventoBuscado.setSituacao(resultado.getString("situacao"));
eventoBuscado.setCategoria(resultado.getInt("c.cat_id"));
eventoBuscado.setCatNome(resultado.getString("cat_nome"));
eventoBuscado.setEntrada(resultado.getDouble("pct_lucro"));
enderecoBuscado.setId(resultado.getInt("end_id"));
enderecoBuscado.setLogradouro(resultado.getString("logradouro"));
enderecoBuscado.setBairro(resultado.getString("bairro"));
enderecoBuscado.setRua(resultado.getString("rua"));
enderecoBuscado.setCEP(resultado.getString("cep"));
enderecoBuscado.setNumero(resultado.getString("numero"));
enderecoBuscado.setCidade(resultado.getString("cidade"));
enderecoBuscado.setEstado(resultado.getString("estado"));
rateioBuscado.setId(resultado.getInt("rat_id"));
rateioBuscado.setInicioRateio(resultado.getDate("dt_inicio"));
rateioBuscado.setFimRateio(resultado.getDate("dt_final"));
rateioBuscado.setValorPagar(resultado.getDouble("valor_pagar"));
locacaoBuscada.setId(resultado.getInt("l.loc_id"));
locacaoBuscada.setNome(resultado.getString("l.nome"));
eventoBuscado.setEndereco(enderecoBuscado);
eventoBuscado.setRateio(rateioBuscado);
eventoBuscado.setLocacao(locacaoBuscada);
eventos.add(eventoBuscado);
}
conexao.commit();
} catch (SQLException e) {
try {
conexao.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
} // fim do try/catch INTERNO
e.printStackTrace();
} /* fim do try/catch */ finally {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
} // final FINALLY
}
return eventos;
} // final CONSULTAR
@Override
public void excluir(IDominio entidade) throws SQLException {
conectar();
PreparedStatement ps = null;
RateioDAO rateioDAO = new RateioDAO();
EnderecoDAO enderecoDAO = new EnderecoDAO();
// Converte a entidade genérica em evento
Evento evento = (Evento) entidade;
try {
rateioDAO.excluir(evento.getRateio());
conexao.setAutoCommit(false);
StringBuilder sql = new StringBuilder(); // variável para concatenar as Strings
// inicia a declaração da query
sql.append("DELETE from eventos where evt_id=?;");
ps = conexao.prepareStatement(sql.toString());
// insere os objetos na query:
ps.setInt(1, evento.getId());
ps.executeUpdate();
conexao.commit();
} catch (SQLException e) {
try {
conexao.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
} // fim do try/catch INTERNO
e.printStackTrace();
} /* fim do try/catch */ finally {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
} // final FINALLY
} // final EXCLUIR
} // final da classe
|
package com.demo.state.blog;
/**
* @author: Maniac Wen
* @create: 2020/6/2
* @update: 8:12
* @version: V1.0
* @detail:
**/
public class UnLoginState extends UserState{
public void favorite() {
System.out.println("跳转到登陆界面");
this.appContext.setState(this.appContext.STATE_LOGIN);
this.appContext.getCurrentState().favorite();
}
public void comment(String comment) {
System.out.println("跳转到登陆界面");
this.appContext.setState(this.appContext.STATE_LOGIN);
this.appContext.getCurrentState().comment(comment);
}
}
|
package homework.task_brackets;
/**
* Created by Admin on 15.02.2015.
*/
public class Test {
public static void main(String[] args) {
String str = " Тестовая с(()т()ро(ка )с (нес))к((()))олькими пробелами ";
int counter = 0;
char symbol;
for (int i = 0; i < str.length(); i++) {
symbol = str.charAt(i);
if (symbol == '(') {
counter++;
}
if (symbol == ')') {
counter--;
}
}
if (counter == 0) {
System.out.println("Скобки расставлены правильно");
} else System.out.println("Скобки расставлены неправильно");
}
}
|
package com.example.demo.jpaTest.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.jpaTest.service.DepartmentService;
import com.example.demo.jpaTest.vo.DepartmentVo;
@RestController
@RequestMapping("/departmentTest")
public class DepartmentController {
// 기본형
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
DepartmentService deptService;
@PostMapping("/add")
public ResponseEntity<DepartmentVo> save(DepartmentVo dept) {
return new ResponseEntity<DepartmentVo>(deptService.save(dept), HttpStatus.OK);
}
}
|
package py.edu.unican.facitec.entidades;
public class Habitacion extends General{
//private int codHabitacion;
private String descripHabitacion;
private int montoDia;
private String observacion;
private int habActivo;
public Habitacion() {
super();
//this.codHabitacion = 0;
this.descripHabitacion = "";
this.montoDia = 0;
this.observacion = "";
this.habActivo = 1;
}
public Habitacion(String descripHabitacion, int montoDia,
String observacion, int habActivo) {
super();
this.descripHabitacion = descripHabitacion;
this.montoDia = montoDia;
this.observacion = observacion;
this.habActivo = habActivo;
}
public String getDescripHabitacion() {
return descripHabitacion;
}
public void setDescripHabitacion(String descripHabitacion) {
this.descripHabitacion = descripHabitacion;
}
public int getMontoDia() {
return montoDia;
}
public void setMontoDia(int montoDia) {
this.montoDia = montoDia;
}
public String getObservacion() {
return observacion;
}
public void setObservacion(String observacion) {
this.observacion = observacion;
}
public int getHabActivo() {
return habActivo;
}
public void setHabActivo(int habActivo) {
this.habActivo = habActivo;
}
}
|
package propertyparser;
import java.util.HashMap;
public class Property {
String type;
HashMap<String, String> attributes;
public Property(String type){
this.type = type;
attributes = new HashMap<String, String>();
}
public Property(String type, String field1, String field2){
this.type = type;
attributes = new HashMap<String, String>();
attributes.put(field1, field2);
}
public void addAttributeToHashMap(String key, String value){
addAttribute(key, value);
}
private void addAttribute(String key, String value){
attributes.put(key, value);
}
public String getType(){
return getTypeString();
}
private String getTypeString(){
return type;
}
public String getAttributeFromHashMap(String key){
return getAttribute(key);
}
private String getAttribute(String key){
return attributes.get(key);
}
}
|
package com.pluralsight.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.pluralsight.model.Activity;
import com.pluralsight.model.Exercise;
import com.pluralsight.repository.ExerciseRepository;
@Service("excerciseService")
public class ExerciseServiceImpl implements ExerciseService {
@Autowired
private ExerciseRepository exerciseRepository;
public List<Activity> findAllActivities() {
List<Activity> activities = new ArrayList<Activity>();
Activity run = new Activity();
run.setDescription("Run");
activities.add(run);
Activity swim = new Activity();
swim.setDescription("Swim");
activities.add(swim);
Activity walk = new Activity();
walk.setDescription("Walk");
activities.add(walk);
return activities;
}
@Transactional
public Exercise Save(Exercise exercise) {
exerciseRepository.save(exercise);
return exercise;
}
}
|
package Controllers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class mycontroller {
//if this class has only one method then this is single action controller class
//if if this class has multiple methods then this is multiple action controller class
@RequestMapping("/hello")
public ModelAndView show(){
ModelAndView mobj = new ModelAndView("welcome"); //here welcome is the view
mobj.addObject("name","ankit gupta"); // ankit gupta is the data stored in name variable
return mobj; //this object(view and data) is send to the front controller(spring-servlet.xml) where viewresolver apply the prefix and sufix properties on the view(welcome)
//then front controller send the data to the particular view(welcome.jsp)
}
@RequestMapping("/data")
public ModelAndView showdata(){
ModelAndView obj = new ModelAndView("mydata");
obj.addObject("info","hello this is your data");
return obj;
}
}
|
package cn.happy.spring1007_03;
/**
* Created by LY on 2017/10/7.
*/
public class SomeService implements ISomeService {
public void insert() {
System.out.println("insert");
}
public String update() {
System.out.println("update");
return null;
}
public void delete() {
System.out.println("delete");
}
public void select() {
System.out.println("select");
}
}
|
/*
* (C) Mississippi State University 2009
*
* The WebTOP employs two licenses for its source code, based on the intended use. The core license for WebTOP applications is
* a Creative Commons GNU General Public License as described in http://*creativecommons.org/licenses/GPL/2.0/. WebTOP libraries
* and wapplets are licensed under the Creative Commons GNU Lesser General Public License as described in
* http://creativecommons.org/licenses/*LGPL/2.1/. Additionally, WebTOP uses the same licenses as the licenses used by Xj3D in
* all of its implementations of Xj3D. Those terms are available at http://www.xj3d.org/licenses/license.html.
*/
//Vector3.java
//Defines the class Vector3, for representing three-dimensional Cartesian vectors.
//Davis Herring
//Created August 3 2002
//Updated March 11 2004
//Version 1.11
package org.sdl.math;
public class Vector3 extends MVector
{
public double z;
public Vector3(final double X,final double Y,final double Z) {x=X;y=Y;z=Z;}
public Vector3(final Vector2 v) {x=v.x;y=v.y;}
public Vector3(final Vector3 v) {x=v.x;y=v.y;z=v.z;}
public double mag() {return Math.pow(x*x+y*y+z*z,.5);}
public double cylR() {return Math.pow(x*x+y*y,.5);}
public double phi() {return Math.atan2(z,Math.pow(x*x+y*y,.5));}
public double lat() {return Math.PI/2-phi();}
public void add(final Vector3 v) {x+=v.x;y+=v.y;z+=v.z;}
public void subtract(final Vector3 v) {x-=v.x;y-=v.x;y-=v.z;}
public void scale(final double s) {x*=s;y*=s;z*=s;}
public void setCylR(final double r) {final double s=r/cylR();x*=s;y*=s;}
public void setTheta(final double t) {final double r=cylR();x=r*Math.cos(t);y=r*Math.sin(t);}
public void setPhi(final double p) {final double phi=phi(),s=Math.sin(p)/Math.sin(phi);x*=s;y*=s;z*=Math.cos(p)/Math.cos(phi);}
public void setLat(final double l) {setPhi(Math.PI/2-l);}
public void rotate(final Vector3 a,final double t) {
if(a.x==0 && a.y==0 && a.z==0) throw new IllegalArgumentException("Cannot rotate about the 0 vector.");
//We resolve ourselves into components parallel and perpendicular to the axis.
//The parallel component will be unaffected.
Vector3 par=proj(this,a),per=subtract(this,par);
//If we have no such perpendicular component, we are along the axis: rotation does nothing.
if(per.x==0 && per.y==0 && per.z==0) return;
//Then take the vector perpendicular to both the
//axis and our component perpendicular to the axis:
Vector3 c=crossP(a,per);
c.setMag(per.mag());
//By the right-hand rule, this vector (if we place tail-to-tip a, then per, then c)
//points counter-clockwise as seen from beyond the end of a. We can then use it and
//per as x-y components of a new "two-dimensional" vector in the plane perpendicular
//to the axis. We set their magnitudes equal and then apply the rotation.
per.scale(Math.cos(t));
c.scale(Math.sin(t));
//With the vectors scaled, their sum is the new perpendicular component.
//We then re-add the parallel component, and the vector is rotated.
x=per.x+c.x+par.x;
y=per.y+c.y+par.y;
z=per.z+c.z+par.z;
}
public double[] toArray(final double[] a) {if(a==null) return new double[] {x,y,z}; a[0]=x;a[1]=y;a[2]=z; return a;}
public float[] toFArray(final float[] a) {if(a==null) return new float[] {(float)x,(float)y,(float)z}; a[0]=(float)x;a[1]=(float)y;a[2]=(float)z; return a;}
public String asString(boolean ijk) {
if(ijk) {
StringBuffer sb=new StringBuffer(24);
if(x!=0) {
sb.append(x);
sb.append('i');
}
if(y!=0) {
if(y>0 && sb.length()>0) sb.append('+');
sb.append(y);
sb.append('j');
}
if(z!=0) {
if(z>0 && sb.length()>0) sb.append('+');
sb.append(z);
sb.append('k');
}
return sb.toString();
}
return "<"+x+','+y+','+z+'>';
}
public boolean equals(Object o) {
if(o instanceof Vector3) {
Vector3 v=(Vector3)o;
return x==v.x&&y==v.y&&z==v.z;
} else return false;
}
public String toString() {return getClass().getName()+'['+x+','+y+','+z+']';}
//Static methods do not modify arguments
public static Vector3 add(final Vector3 v1,final Vector3 v2) {return new Vector3(v1.x+v2.x,v1.y+v2.y,v1.z+v2.z);}
public static Vector3 subtract(final Vector3 v1,final Vector3 v2) {return new Vector3(v1.x-v2.x,v1.y-v2.y,v1.z-v2.z);}
public static Vector3 multiply(final Vector3 v,final double s) {return new Vector3(v.x*s,v.y*s,v.z*s);}
public static Vector3 proj(final Vector3 v,final Vector3 along) {final double s=comp(v,along)/along.mag();return new Vector3(along.x*s,along.y*s,along.z*s);}
public static Vector3 crossP(final Vector3 v1,final Vector3 v2) {return new Vector3(v1.y*v2.z-v1.z*v2.y,v1.z*v2.x-v1.x*v2.z,v1.x*v2.y-v1.y*v2.x);}
public static Vector3 unitV(final Vector3 v) {final double m=v.mag();return new Vector3(v.x/m,v.y/m,v.z/m);}
public static Vector3 fromCylindrical(final double r,final double t,final double z) {return new Vector3(r*Math.cos(t),r*Math.sin(t),z);}
public static Vector3 fromSpherical(final double r,final double t,final double p) {final double s=Math.sin(p);return new Vector3(r*s*Math.cos(t),r*s*Math.sin(t),r*Math.cos(p));}
public static double comp(final Vector3 v,final Vector3 along) {final double xa=along.x,ya=along.y,za=along.z;return (v.x*xa+v.y*ya+v.z*za)/Math.pow(xa*xa+ya*ya+za*za,.5);}
public static double dotP(final Vector3 v1,final Vector3 v2) {return v1.x*v2.x+v1.y*v2.y+v1.z*v2.z;}
public static double doubleBetween(final Vector3 v1,final Vector3 v2) {final double x1=v1.x,x2=v2.x,y1=v1.y,y2=v2.y,z1=v1.z,z2=v2.z;return Math.acos((x1*x2+y1*y2+z1*z2)/Math.pow((x1*x1+y1*y1+z1*z1)*(x2*x2+y2*y2+z2*z2),.5));}
public static Vector3 i() {return new Vector3(1,0,0);}
public static Vector3 j() {return new Vector3(0,1,0);}
public static Vector3 k() {return new Vector3(0,0,1);}
public static Vector3 zero() {return new Vector3(0,0,0);}
}
|
package aspect;
public class Advice1 {
public void tt(){
System.out.println("advice!");
}
}
|
package edu.asu.commons.net;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeSet;
/**
* $Id$
*
* Very basic pooled implementation for worker threads. The WorkerPool is a composite of
* the Worker.
*
* FIXME: replace with Java 1.5 thread pools, i.e., ThreadPoolExecutor
*
* @author <a href='mailto:alllee@cs.indiana.edu'>Allen Lee</a>
* @version $Revision$
*/
public class WorkerPool<T> implements Worker<T> {
private final static int DEFAULT_SIZE = 8;
private WorkerFactory<T> factory;
// Set of Workers ordered such that the workers with the least number of
// jobs are in the front of the Set.
private final TreeSet<Worker<T>> workers = new TreeSet<Worker<T>>();
private final Map<T, Worker<T>> objectToWorkerMap =
new HashMap<T, Worker<T>>();
private final boolean growable;
public WorkerPool(WorkerFactory<T> factory) {
this(DEFAULT_SIZE, factory);
}
public WorkerPool(int initialSize, WorkerFactory<T> factory) {
this(initialSize, factory, false);
}
// FIXME: should really have GrowableWorkerPool and StaticWorkerPool,
// Should support the thread model where there is one worker thread per
// job (in plain old java Socket programming, for instance).
public WorkerPool(int initialSize, WorkerFactory<T> factory, boolean growable) {
this.growable = growable;
for (int i = 0; i < initialSize; i++) {
workers.add(factory.create());
}
}
public synchronized void remove(T job) {
Worker<T> worker = objectToWorkerMap.remove(job);
if (worker == null) {
return;
}
worker.remove(job);
}
// FIXME: mayhap this should be non-public. Also, figure out what to do
// here.
public synchronized void shutdown() {
objectToWorkerMap.clear();
for (Iterator<Worker<T>> iterator = workers.iterator(); iterator.hasNext();) {
Worker<T> worker = iterator.next();
// assumes that each worker has the ability to kill itself?
worker.shutdown();
iterator.remove();
}
}
public synchronized Identifier process(T object) {
Worker<T> worker = workers.first();
// this should always grab the first worker out.
if (growable) {
if (worker.numberOfJobs() > 0) {
worker = factory.create();
workers.add(worker);
}
}
objectToWorkerMap.put(object, worker);
return worker.process(object);
}
public void report() {
for (Worker<T> worker : workers) {
worker.report();
}
}
public int compareTo(Worker<T> worker) {
return numberOfJobs() - worker.numberOfJobs();
}
public int numberOfJobs() {
return objectToWorkerMap.size();
}
public void run() {
for (Worker<T> worker : workers) {
new Thread(worker).start();
}
}
}
|
package actions;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import static org.testng.Assert.assertTrue;
public class WebUiActions {
WebDriver driver;
public WebUiActions(WebDriver driver)
{
this.driver=driver;
}
public boolean validateElement(ExpectedCondition<WebElement> Exp)
{
try
{
new WebDriverWait(driver,10).until(Exp);
return true;
}
catch (Exception e)
{
return false;
}
}
public void clickOnBtn(By element,By expectedElement)
{
if(validateElement(ExpectedConditions.elementToBeClickable(element)))
{
driver.findElement(element).click(); //javascript
}
assertTrue(validateElement(ExpectedConditions.presenceOfElementLocated(expectedElement)));
}
}
|
package alien4cloud.paas.wf;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class GetAttributeActivity extends AbstractActivity {
private String attributeName;
@Override
public String toString() {
return getNodeId() + ".getAttribute[" + attributeName + "]";
}
@Override
public String getRepresentation() {
return getNodeId() + "_get_" + attributeName;
}
}
|
package com.kdgz.uwifi.backoffice.model;
import java.util.List;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import com.kdgz.uwifi.backoffice.constant.Constants;
@SuppressWarnings("serial")
public class Acinfo extends Model<Acinfo> {
public static final Acinfo dao = new Acinfo();
/**
* 获取列表
*
* @param pageNumber
* @param pageSize
* @return
*/
public Page<Acinfo> pageinfoList(int pageNumber, int pageSize,
String busname, String construtname, String businessid) {
StringBuffer sql = new StringBuffer();
sql.append("from acinfo a, businessinfo b, construtinfo c, acbrand d, actypeinfo e ");
sql.append("where a.businessid = b.id and a.construtid = c.id and a.acbrandid = d.id and a.actypeid = e.id ");
if (StrKit.notBlank(busname)) {
sql.append(" and b.busname like '%" + busname + "%' ");
}
if (StrKit.notBlank(construtname)) {
sql.append(" and c.construtname like '%" + construtname + "%'");
}
if (StrKit.notBlank(businessid)) {
sql.append(" and b.id in (" + businessid + ")");
}
sql.append(" order by a.id desc");
Page<Acinfo> acinfo = paginate(pageNumber, pageSize,
"select a.id, a.acid, a.businessid, a.acos, a.addtime, d.acbrandname, e.typename,"
+ " a.eqptssid, c.construtname, b.busname",
sql.toString());
return acinfo;
}
/**
* 获取导出路由列表
*/
public List<Acinfo> acinfoListExport(String businessid) {
StringBuffer sql = new StringBuffer();
sql.append("select a.id, a.acid, a.businessid, a.acos, a.addtime, d.acbrandname, e.typename,"
+ " a.eqptssid, b.busname, f.userid");
sql.append(" from acinfo a, businessinfo b, acbrand d, actypeinfo e, userbiz f ");
sql.append(" where a.businessid = b.id and a.acbrandid = d.id and a.actypeid = e.id and b.id = f.businessid ");
if (StrKit.notBlank(businessid)) {
sql.append(" and b.id in (" + businessid + ")");
}
List<Acinfo> list = dao.find(sql.toString());
return list;
}
/**
* 获取我的店铺路由器列表
*
* @param pageNumber
* @param pageSize
* @return
*/
public Page<Acinfo> pageAcInfoList(int pageNumber, int pageSize,
String busname, String acid, String businessid, String areaId,
String provinceId, String cityId, String countiesId) {
StringBuffer sql = new StringBuffer();
sql.append("from acinfo a, businessinfo b, acbrand d, actypeinfo e, userbiz f ");
sql.append("where a.businessid = b.id and a.acbrandid = d.id and a.actypeid = e.id and b.id = f.businessid ");
if (StrKit.notBlank(busname)) {
sql.append(" and b.busname like '%" + busname + "%' ");
}
if (StrKit.notBlank(acid)) {
sql.append(" and a.acid like '%" + acid + "%'");
}
if (StrKit.notBlank(businessid)) {
sql.append(" and b.id in (" + businessid + ")");
} else {
sql.append(" and b.id = 0");
}
if (StrKit.notBlank(areaId)) {
sql.append(" and b.area = "+areaId);
}
if (StrKit.notBlank(provinceId)) {
sql.append(" and b.province = "+provinceId);
}
if (StrKit.notBlank(cityId)) {
sql.append(" and b.city like '%" + provinceId + "%' ");
}
if (StrKit.notBlank(countiesId)) {
sql.append(" and b.counties like '%" + cityId + "%' ");
}
sql.append(" order by a.id desc");
Page<Acinfo> acinfo = paginate(pageNumber, pageSize,
"select a.id, a.acid, a.businessid, a.acos, a.addtime, d.acbrandname, e.typename,"
+ " a.eqptssid, b.busname, f.userid", sql.toString());
//added by yan
if(acinfo.getTotalPage()>0 && pageNumber>acinfo.getTotalPage()){
acinfo = paginate(1, pageSize,
"select a.id, a.acid, a.businessid, a.acos, a.addtime, d.acbrandname, e.typename,"
+ " a.eqptssid, b.busname, f.userid", sql.toString());
}
return acinfo;
}
public Page<Acinfo> pageAcInfoListWithArea(int pageNumber, int pageSize,
String busname, String acid, String businessid, String areaId,
String provinceId, String cityId, String countiesId, Integer userRole, String flage) {
StringBuffer sql = new StringBuffer();
sql.append("from acinfo a, businessinfo b, acbrand d, actypeinfo e ");
sql.append("where a.businessid = b.id and a.acbrandid = d.id and a.actypeid = e.id ");
if (StrKit.notBlank(busname)) {
sql.append(" and b.busname like '%" + busname + "%' ");
}
if (StrKit.notBlank(acid)) {
sql.append(" and a.acid like '%" + acid + "%'");
}
if (StrKit.notBlank(businessid)) {
sql.append(" and b.id in (" + businessid + ")");
} else {
sql.append(" and b.id = 0");
}
if("sessionFlage".equals(flage)){
if(areaId.length() > 0){
sql.append(" and b.area = '"+areaId+"'");
}
if(provinceId.length() > 0){
sql.append(" and b.province = '"+provinceId+"'");
}
if(cityId.length() > 0){
sql.append(" and b.city = '"+cityId+"'");
}
if(countiesId.length() > 0){
sql.append(" and b.counties = '"+countiesId+"'");
}
}else{
if(Constants.ROLE_AREA.equals(userRole)){//大区用户:可查询大区下所有店铺
if(areaId.length() > 0){
sql.append(" and b.area = '"+areaId+"'");
}
}else if(Constants.ROLE_PROVINCE.equals(userRole)){//省级用户:可查询该生下所有市,区/县店铺
if(provinceId.length() > 0){
sql.append(" and b.province = '"+provinceId+"'");
}
}else if(Constants.ROLE_CITY.equals(userRole)){//市级用户:可查询该市下所有区/县店铺
if(cityId.length() > 0){
sql.append(" and b.city = '"+cityId+"'");
}
}else if(Constants.ROLE_COUNTIES.equals(userRole)){//区/县级用户
if(countiesId.length() > 0){
sql.append(" and b.counties = '"+countiesId+"'");
}
}
}
sql.append(" order by a.id desc");
Page<Acinfo> acinfo = paginate(pageNumber, pageSize,
"select a.id, a.acid, a.businessid, a.acos,a.addtime, d.acbrandname, e.typename,"
+ " a.eqptssid, b.busname", sql.toString());
//added by yan
if(acinfo.getTotalPage()>0 && pageNumber>acinfo.getTotalPage()){
acinfo = paginate(1, pageSize,
"select a.id, a.acid, a.businessid, a.acos,a.addtime, d.acbrandname, e.typename,"
+ " a.eqptssid, b.busname", sql.toString());
}
return acinfo;
}
/**
* 获取Ac信息表,此方法只用到获取ACId
*
* @return
*/
public List<Acinfo> selectAcidList(String businessid) {
StringBuffer sql = new StringBuffer();
sql.append("select a.id, a.acid from acinfo a ");
if (StrKit.notBlank(businessid)) {
sql.append(" where 1=1 and a.businessid in (" + businessid + ")");
}else{
sql.append(" where 1=2 ");
}
sql.append(" order by a.id desc");
List<Acinfo> list = dao.find(sql.toString());
return list;
}
/**
* 查找ac信息通过ACId
*
* @param acid
* @return
*/
public Acinfo selectAcinfoByAcId(String acid) {
Acinfo acinfo = dao.findFirst("select * from acinfo where acid = '"
+ acid + "' ");
return acinfo;
}
/**
* 判断acid唯一性
*/
public Acinfo selectAcinfoByIdAndAcId(int id, String acid) {
Acinfo acinfo = dao.findFirst("select * from acinfo where id <> '" + id
+ "' and acid = '" + acid + "' ");
return acinfo;
}
/**
* 获取店铺的路由器数量
*
* @param userId
* @return
*/
public long countShopDeviceNum(int busId) {
long count = Db
.queryLong(
"SELECT count(1) AS count FROM acinfo WHERE acinfo.businessid = ?",
new int[] { busId });
return count;
}
/**
* 获取一个路由器acid
* @param businessId
* @return
* @author jason
*/
public Acinfo getAcIdByBusid(Integer businessId) {
Acinfo acinfo = dao.findFirst("select * from acinfo where businessid = "+ businessId + " limit 1 ");
return acinfo;
}
}
|
package lando.systems.ld37.utils;
import com.badlogic.gdx.graphics.Color;
/**
* Created by dsgraham on 12/10/16.
*/
public class Config {
public static int gameWidth = 640;
public static int gameHeight = 480;
public static Color bgColor = new Color(0,0,0,1);
}
|
package pkglayer;
import java.lang.ModuleLayer;
// leaf node in the layer hierarchy tree
public class LayerRef extends AbstractLayerRef {
public LayerRef(final LayerGroup parent, final String name, final String level) {
super(parent, name, level);
}
public LayerRef(final LayerGroup parent, final String name, final String level, final ModuleLayer layer) {
super(parent, name, level, layer);
}
@Override
public String toString() {
return name + " on " + level;
}
}
|
package com.bankerguy.bankerguy;
import java.util.List;
/**
* Created by nevin on 11/12/2017.
*/
public class BankInfo {
private List<Bank> banks; //private List<Integer> banks;
}
|
package com.ats.communication_admin.fcm;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.widget.Toast;
import com.ats.communication_admin.R;
import com.ats.communication_admin.activity.ComplaintDetailActivity;
import com.ats.communication_admin.activity.FeedbackDetailActivity;
import com.ats.communication_admin.activity.HomeActivity;
import com.ats.communication_admin.activity.InnerTabActivity;
import com.ats.communication_admin.activity.SuggestionDetailActivity;
import com.ats.communication_admin.activity.TabActivity;
import com.ats.communication_admin.bean.ComplaintData;
import com.ats.communication_admin.bean.ComplaintDetail;
import com.ats.communication_admin.bean.FeedbackData;
import com.ats.communication_admin.bean.FeedbackDetail;
import com.ats.communication_admin.bean.MessageData;
import com.ats.communication_admin.bean.NoticeData;
import com.ats.communication_admin.bean.NotificationData;
import com.ats.communication_admin.bean.SchedulerList;
import com.ats.communication_admin.bean.SuggestionData;
import com.ats.communication_admin.bean.SuggestionDetail;
import com.ats.communication_admin.bean.User;
import com.ats.communication_admin.constants.Constants;
import com.ats.communication_admin.db.DatabaseHandler;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import com.google.gson.Gson;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
if (remoteMessage.getData().size() > 0 || !remoteMessage.getNotification().equals(null)) {
try {
JSONObject json = new JSONObject(remoteMessage.getData());
// JSONObject json1 = new JSONObject(remoteMessage.getNotification().toString());
Log.e("JSON DATA", "-----------------------------" + json);
// Log.e("JSON NOTIFICATION", "-----------------------------" + json1);
sendPushNotification(json);
} catch (Exception e) {
Log.e(TAG, "-----------------------------Exception: " + e.getMessage());
e.printStackTrace();
}
super.onMessageReceived(remoteMessage);
// NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
// .setSmallIcon(R.mipmap.ic_launcher).setDefaults(Notification.DEFAULT_ALL)
// .setContentTitle(remoteMessage.getData().get("title"))
// .setContentText(remoteMessage.getData().get("body"));
// NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// manager.notify(0, builder.build());
// builder.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE);
} else {
Log.e("FIREBASE", "----------------------------------");
}
}
@Override
public void handleIntent(Intent intent) {
super.handleIntent(intent);
}
private void sendPushNotification(JSONObject json) {
Log.e(TAG, "--------------------------------JSON String" + json.toString());
try {
String tempTitle = json.getString("title");
String[] tempArray = tempTitle.split("#");
String title = "";
String frName = "";
Log.e("LENGTH : -----------","--------------"+tempArray.length);
if (tempArray.length > 1) {
title = tempArray[0];
frName = tempArray[1];
} else {
title = tempTitle;
}
// String title = json.getString("title");
String message = json.getString("body");
String imageUrl = "";
String tag = json.getString("tag");
MyNotificationManager mNotificationManager = new MyNotificationManager(getApplicationContext());
DatabaseHandler db = new DatabaseHandler(this);
if (tag.equalsIgnoreCase("nf")) {
Gson gson = new Gson();
NotificationData notificationData = gson.fromJson(message, NotificationData.class);
notificationData.setUserName(frName);
Log.e("NotificationData:", "----------------------" + notificationData);
if (mNotificationManager.isAppIsInBackground(getApplicationContext())) {
Log.e("APP BACKGROUND", "--------------------------------------------------");
db.addNotifications(notificationData);
Intent resultIntent = new Intent(getApplicationContext(), TabActivity.class);
resultIntent.putExtra("tabId", 2);
mNotificationManager.showSmallNotification(title, notificationData.getSubject(), resultIntent);
} else {
Log.e("APP RUNNING", "--------------------------------------------------");
Intent pushNotification = new Intent();
pushNotification.setAction("NOTIFICATION_ADMIN");
pushNotification.putExtra("message", message);
LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);
MyNotificationManager notificationUtils = new MyNotificationManager(getApplicationContext());
notificationUtils.playNotificationSound();
db.addNotifications(notificationData);
}
}
if (tag.equalsIgnoreCase("notice")) {
Gson gson = new Gson();
com.ats.communication_admin.bean.Message messageData = gson.fromJson(message, com.ats.communication_admin.bean.Message.class);
Log.e("MessageData : ", "----------------------" + messageData);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat sdf2 = new SimpleDateFormat("dd-MM-yyyy");
try {
Date parseDate = sdf.parse(messageData.getMsgFrdt());
messageData.setMsgFrdt(sdf2.format(parseDate));
Date parseDateTo = sdf.parse(messageData.getMsgTodt());
messageData.setMsgTodt(sdf2.format(parseDateTo));
} catch (ParseException e) {
e.printStackTrace();
}
if (mNotificationManager.isAppIsInBackground(getApplicationContext())) {
Log.e("APP BACKGROUND", "--------------------------------------------------");
com.ats.communication_admin.bean.Message dbMesage = db.getMessage(messageData.getMsgId());
if (dbMesage.getMsgId() == 0) {
db.addMessage(messageData);
} else {
db.updateMessageById(messageData);
}
Intent resultIntent = new Intent(getApplicationContext(), TabActivity.class);
resultIntent.putExtra("tabId", 1);
mNotificationManager.showSmallNotification(title, messageData.getMsgHeader(), resultIntent);
} else {
Log.e("APP RUNNING", "--------------------------------------------------");
Intent pushNotification = new Intent();
pushNotification.setAction("MESSAGE_ADMIN");
pushNotification.putExtra("message", message);
LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);
MyNotificationManager notificationUtils = new MyNotificationManager(getApplicationContext());
notificationUtils.playNotificationSound();
com.ats.communication_admin.bean.Message dbMesage = db.getMessage(messageData.getMsgId());
if (dbMesage.getMsgId() == 0) {
db.addMessage(messageData);
} else {
db.updateMessageById(messageData);
}
}
}
if (tag.equalsIgnoreCase("news")) {
Gson gson = new Gson();
SchedulerList noticeData = gson.fromJson(message, SchedulerList.class);
Log.e("noticeData : ", "----------------------" + noticeData);
if (mNotificationManager.isAppIsInBackground(getApplicationContext())) {
Log.e("APP BACKGROUND", "--------------------------------------------------");
SchedulerList dbNews = db.getNotice(noticeData.getSchId());
if (dbNews.getSchId() == 0) {
db.addNotices(noticeData);
} else {
db.updateNoticeById(noticeData);
}
Intent resultIntent = new Intent(getApplicationContext(), TabActivity.class);
resultIntent.putExtra("tabId", 0);
mNotificationManager.showSmallNotification(title, noticeData.getSchMessage(), resultIntent);
} else {
Log.e("APP RUNNING", "--------------------------------------------------");
Intent pushNotification = new Intent();
pushNotification.setAction("NOTICE_ADMIN");
pushNotification.putExtra("message", message);
LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);
MyNotificationManager notificationUtils = new MyNotificationManager(getApplicationContext());
notificationUtils.playNotificationSound();
SchedulerList dbNews = db.getNotice(noticeData.getSchId());
if (dbNews.getSchId() == 0) {
db.addNotices(noticeData);
} else {
db.updateNoticeById(noticeData);
}
}
}
if (tag.equalsIgnoreCase("sd")) {
Gson gson = new Gson();
SuggestionDetail suggestionDetail = gson.fromJson(message, SuggestionDetail.class);
suggestionDetail.setFrName(frName);
Log.e("SUGGESTION DETAIL : ", "----------------------" + suggestionDetail);
if (mNotificationManager.isAppIsInBackground(getApplicationContext())) {
Log.e("APP BACKGROUND", "--------------------------------------------------");
db.addSuggestionDetails(suggestionDetail);
Intent resultIntent = new Intent(getApplicationContext(), SuggestionDetailActivity.class);
resultIntent.putExtra("suggestionId", suggestionDetail.getSuggestionId());
resultIntent.putExtra("refresh", 1);
mNotificationManager.showSmallNotification(title, suggestionDetail.getMessage(), resultIntent);
} else {
Log.e("APP RUNNING", "--------------------------------------------------");
Intent pushNotification = new Intent();
pushNotification.setAction("SUGGESTION_DETAIL_ADMIN");
pushNotification.putExtra("frName", frName);
pushNotification.putExtra("message", message);
pushNotification.putExtra("suggestionId", suggestionDetail.getSuggestionId());
pushNotification.putExtra("refresh", 1);
LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);
MyNotificationManager notificationUtils = new MyNotificationManager(getApplicationContext());
notificationUtils.playNotificationSound();
db.addSuggestionDetails(suggestionDetail);
}
} else if (tag.equalsIgnoreCase("cd")) {
Gson gson = new Gson();
ComplaintDetail complaintDetail = gson.fromJson(message, ComplaintDetail.class);
complaintDetail.setFrName(frName);
Log.e("COMPLAINT DETAIL : ", "----------------------" + complaintDetail);
if (mNotificationManager.isAppIsInBackground(getApplicationContext())) {
Log.e("APP BACKGROUND", "--------------------------------------------------");
db.addComplaintDetails(complaintDetail);
Intent resultIntent = new Intent(getApplicationContext(), ComplaintDetailActivity.class);
resultIntent.putExtra("complaintId", complaintDetail.getComplaintId());
resultIntent.putExtra("refresh", 1);
mNotificationManager.showSmallNotification(title, complaintDetail.getMessage(), resultIntent);
} else {
Log.e("APP RUNNING", "--------------------------------------------------");
Intent pushNotification = new Intent();
pushNotification.setAction("COMPLAINT_DETAIL_ADMIN");
pushNotification.putExtra("frName", frName);
pushNotification.putExtra("message", message);
pushNotification.putExtra("complaintId", complaintDetail.getComplaintId());
pushNotification.putExtra("refresh", 1);
LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);
MyNotificationManager notificationUtils = new MyNotificationManager(getApplicationContext());
notificationUtils.playNotificationSound();
db.addComplaintDetails(complaintDetail);
}
} else if (tag.equalsIgnoreCase("fd")) {
Gson gson = new Gson();
FeedbackDetail feedbackDetail = gson.fromJson(message, FeedbackDetail.class);
feedbackDetail.setFrName(frName);
Log.e("FEEDBACK DETAIL : ", "----------------------" + feedbackDetail);
if (mNotificationManager.isAppIsInBackground(getApplicationContext())) {
Log.e("APP BACKGROUND", "--------------------------------------------------");
db.addFeedbackDetails(feedbackDetail);
Intent resultIntent = new Intent(getApplicationContext(), FeedbackDetailActivity.class);
resultIntent.putExtra("feedbackId", feedbackDetail.getFeedbackId());
resultIntent.putExtra("refresh", 1);
mNotificationManager.showSmallNotification(title, feedbackDetail.getMessage(), resultIntent);
} else {
Log.e("APP RUNNING", "--------------------------------------------------");
Intent pushNotification = new Intent();
pushNotification.setAction("FEEDBACK_DETAIL_ADMIN");
pushNotification.putExtra("frName", frName);
pushNotification.putExtra("message", message);
pushNotification.putExtra("feedbackId", feedbackDetail.getFeedbackId());
pushNotification.putExtra("refresh", 1);
LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);
MyNotificationManager notificationUtils = new MyNotificationManager(getApplicationContext());
notificationUtils.playNotificationSound();
db.addFeedbackDetails(feedbackDetail);
}
} else if (tag.equalsIgnoreCase("s")) {
Gson gson = new Gson();
SuggestionData suggestion = gson.fromJson(message, SuggestionData.class);
suggestion.setFrName(frName);
String dateStr = suggestion.getDate();
try {
long dateLong = Long.parseLong(dateStr);
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
suggestion.setDate(sdf.format(dateLong));
} catch (Exception e) {
}
Log.e("SUGGESTION : ", "----------------------" + suggestion);
if (mNotificationManager.isAppIsInBackground(getApplicationContext())) {
Log.e("APP BACKGROUND", "--------------------------------------------------");
db.addSuggestion(suggestion);
Intent resultIntent = new Intent(getApplicationContext(), InnerTabActivity.class);
resultIntent.putExtra("tabId", 0);
mNotificationManager.showSmallNotification(title, suggestion.getTitle(), resultIntent);
} else {
Log.e("APP RUNNING", "--------------------------------------------------");
Intent pushNotification = new Intent();
pushNotification.setAction("SUGGESTION_ADMIN");
pushNotification.putExtra("frName", frName);
pushNotification.putExtra("message", message);
LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);
MyNotificationManager notificationUtils = new MyNotificationManager(getApplicationContext());
notificationUtils.playNotificationSound();
db.addSuggestion(suggestion);
}
} else if (tag.equalsIgnoreCase("c")) {
Gson gson = new Gson();
ComplaintData complaint = gson.fromJson(message, ComplaintData.class);
complaint.setFrName(frName);
String dateStr = complaint.getDate();
try {
long dateLong = Long.parseLong(dateStr);
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
complaint.setDate(sdf.format(dateLong));
} catch (Exception e) {
}
Log.e("COMPLAINT : ", "----------------------" + complaint);
if (mNotificationManager.isAppIsInBackground(getApplicationContext())) {
Log.e("APP BACKGROUND", "--------------------------------------------------");
db.addComplaint(complaint);
Intent resultIntent = new Intent(getApplicationContext(), InnerTabActivity.class);
resultIntent.putExtra("tabId", 1);
mNotificationManager.showSmallNotification(title, complaint.getTitle(), resultIntent);
} else {
Log.e("APP RUNNING", "--------------------------------------------------");
Intent pushNotification = new Intent();
pushNotification.setAction("COMPLAINT_ADMIN");
pushNotification.putExtra("frName", frName);
pushNotification.putExtra("message", message);
LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);
MyNotificationManager notificationUtils = new MyNotificationManager(getApplicationContext());
notificationUtils.playNotificationSound();
db.addComplaint(complaint);
}
} else if (tag.equalsIgnoreCase("f")) {
Gson gson = new Gson();
FeedbackData feedbackData = gson.fromJson(message, FeedbackData.class);
feedbackData.setUserName(frName);
Log.e("FEEDBACK : ", "----------------------" + feedbackData);
if (mNotificationManager.isAppIsInBackground(getApplicationContext())) {
Log.e("APP BACKGROUND", "--------------------------------------------------");
db.addFeedBack(feedbackData);
Intent resultIntent = new Intent(getApplicationContext(), InnerTabActivity.class);
resultIntent.putExtra("tabId", 2);
mNotificationManager.showSmallNotification(title, feedbackData.getTitle(), resultIntent);
} else {
Log.e("APP RUNNING", "--------------------------------------------------");
Intent pushNotification = new Intent();
pushNotification.setAction("FEEDBACK_ADMIN");
pushNotification.putExtra("frName", frName);
pushNotification.putExtra("message", message);
LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);
MyNotificationManager notificationUtils = new MyNotificationManager(getApplicationContext());
notificationUtils.playNotificationSound();
db.addFeedBack(feedbackData);
}
}
Intent pushNotificationIntent = new Intent();
pushNotificationIntent.setAction("REFRESH_DATA");
LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotificationIntent);
} catch (JSONException e) {
Log.e(TAG, "Json Exception: -----------" + e.getMessage());
e.printStackTrace();
} catch (Exception e) {
Log.e(TAG, "Exception: ------------" + e.getMessage());
e.printStackTrace();
}
}
}
|
package com.oa.office.form;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name="goods")
public class Goods {
@Id
@GeneratedValue
@Column(name="goodsId")
private int goodsId;
@Column(name="goodsName")
private String goodsName;
@Column(name="goodsPrice")
private float goodsPrice;
@ManyToOne
@JoinColumn(name="goodsTypeId")
private GoodsType goodType;
public int getGoodsId() {
return goodsId;
}
public void setGoodsId(int goodsId) {
this.goodsId = goodsId;
}
public String getGoodsName() {
return goodsName;
}
public void setGoodsName(String goodsName) {
this.goodsName = goodsName;
}
public float getGoodsPrice() {
return goodsPrice;
}
public void setGoodsPrice(float goodsPrice) {
this.goodsPrice = goodsPrice;
}
public GoodsType getGoodType() {
return goodType;
}
public void setGoodType(GoodsType goodType) {
this.goodType = goodType;
}
}
|
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.List;
class Solution {
public static Map<Integer, Guard> parseInput(String input) {
/**
* parse the events to get, for each guard, all the naps they took
* @input a list of String that look like "YYYY-MM-DD HH:MM something happened"
* @return a map of guard ID to guard object, filled with naps
*/
String[] events = input.split("\n");
Arrays.sort(events);
Map<Integer, Guard> guards = new HashMap<Integer, Guard>();
Guard currentGuard = null;
for (String line: events) {
// Get time informations
int minute = Integer.parseInt(line.substring(15, 17));
// Find out if its a starts shift / falls asleep / wakes up situation
String situation = line.substring(19);
if (situation.substring(0, 5).equals("Guard")) {
// If it's a starts shift situation, get the guard's ID
// and add it to the list of guards if they're not there
int id = Integer.parseInt(situation.split("[# ]")[2]);
currentGuard = guards.get(id);
if (currentGuard == null) {
currentGuard = new Guard(id);
guards.put(id, currentGuard);
}
}
else {
currentGuard.addEvent(minute);
}
}
return guards;
}
private static String solve(String input) {
/**
* We want to find out from logs when the guards will most probably be asleep
* To do this, we need to find out which guard sleeps the most and when he sleeps
* @input a list of String that look like "YYYY-MM-DD HH:MM something happened"
* @return the id of the guard chosen time the minute when they will be asleep
*/
Map<Integer, Guard> guards = parseInput(input);
// find out which guard has slept the most
Guard guardMostAsleep = null;
int minutesSlept = 0;
for (int guardID: guards.keySet()) {
Guard guard = guards.get(guardID);
int timeAsleep = guard.getTotalNapDuration();
if (timeAsleep > minutesSlept) {
guardMostAsleep = guard;
minutesSlept = timeAsleep;
}
}
// find out when this guard was the most asleep
int bestMinute = guardMostAsleep.getMinuteMostAsleep();
// return ID of guard most asleep * minute when most asleep
return Integer.toString(guardMostAsleep.id * bestMinute);
};
public static void main(String[] args) {
String input = args[0];
long startTime = System.currentTimeMillis();
String result = solve(input);
System.out.println("_duration: " + (System.currentTimeMillis() - startTime) + "\n" + result);
}
}
class Guard {
int id;
List<Integer> naps = new ArrayList<Integer>();
public Guard(int id) {
this.id = id;
}
public void addEvent(int mn) {
naps.add(mn);
}
public int getTotalNapDuration() {
int totalNapDuration = 0;
for (int i = 0; i < naps.size() - 1; i += 2) {
totalNapDuration += naps.get(i+1) - naps.get(i);
}
return totalNapDuration;
}
public int getMinuteMostAsleep() {
int[] minutes = new int[60];
int start, end;
for (int i = 0; i < naps.size(); i += 2) {
start = naps.get(i);
end = naps.get(i+1);
for (int mn = start; mn < end; mn++) {
minutes[mn] += 1;
}
}
int minuteMostAsleep = 0, timeAsleepThisMinute = 0;
for (int i = 0; i < minutes.length; i++) {
if (minutes[i] > timeAsleepThisMinute) {
minuteMostAsleep = i;
timeAsleepThisMinute = minutes[i];
}
}
return minuteMostAsleep;
}
}
|
package com.blockgame.crash.service;
import java.util.List;
import com.blockgame.crash.model.RecordVo;
public interface BoardService {
public void saveScore(Long score);
public List<RecordVo> getAllRecord();
}
|
/* Copyright 2015 Esri
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.esri.arcgis.android.samples.featuredusergroup;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.esri.core.portal.Portal;
import com.esri.core.portal.PortalGroup;
import com.esri.core.portal.PortalItem;
import com.esri.core.portal.PortalItemType;
import com.esri.core.portal.PortalQueryParams;
import com.esri.core.portal.PortalQueryResultSet;
import java.util.ArrayList;
/**
* This fragment is launched when the user chooses a group from the list of featured groups. The
* Portal and the chosen PortalGroup are passed in using the {@link #setParams(Portal, PortalGroup)}
* method.
* <p>
* It displays a list of the webmap items in the chosen group and launches MapActivity when the user
* picks an item.
*/
public class ItemsFragment extends Fragment {
private static final String TAG = "ItemsFragment";
PortalItemListAdapter mAdapter;
ArrayList<PortalItemData> mItems;
static Portal mPortal;
PortalGroup mPortalGroup;
ProgressDialog mProgressDialog;
/**
* Mandatory empty constructor for the fragment manager to instantiate the fragment (e.g. upon
* device configuration changes).
*/
public ItemsFragment() {
}
/**
* Passes the Portal and the chosen PortalGroup into this fragment.
*
* @param portal
* @param portalGroup
*/
public void setParams(Portal portal, PortalGroup portalGroup) {
mPortal = portal;
mPortalGroup = portalGroup;
}
/**
* Returns the Portal object for the portal we are using. Used by MapActivity to get access to the
* Portal object. Ideally this object would be passed in the Intent used to start MapActivity, but
* it�s not currently possible to serialize a Portal object for passing in an Intent.
*/
public static Portal getPortal() {
return mPortal;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Calling setRetainInstance() causes the Fragment instance to be retained when its Activity is
// destroyed and recreated. This allows some ArcGIS objects (Portal, PortalGroup and PortalItem)
// to be retained so data will not need to be fetched from the network again.
setRetainInstance(true);
// Setup list view and list adapter
if (mItems == null || mAdapter == null) {
mItems = new ArrayList<PortalItemData>();
mAdapter = new PortalItemListAdapter(getActivity(), mItems);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Creates the view from the list_layout layout resource. The layout/list_layout.xml file
// contains a ListView for use in portrait orientation, but layout-land/list_layout.xml contains
// a GridView for use in landscape orientation
View view = inflater.inflate(R.layout.list_layout, container, false);
// Setup title
TextView textView = (TextView) view.findViewById(R.id.listTitleTextView);
textView.setText(R.string.itemListTitle);
// Setup list view - maybe a ListView or a GridView
AbsListView list = (AbsListView) view.findViewById(android.R.id.list);
list.setAdapter(mAdapter);
list.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
// Start new activity to handle the portal item the user has selected
Intent intent = new Intent(getActivity(), MapActivity.class);
intent.putExtra(MapActivity.KEY_PORTAL_ITEM_ID, mItems.get(position).portalItem.getItemId());
startActivity(intent);
}
});
// Setup progress dialog
mProgressDialog = new ProgressDialog(getActivity()) {
@Override
public void onBackPressed() {
// Back key pressed - dismiss the dialog and kill this fragment by popping back stack
dismiss();
getFragmentManager().popBackStack();
}
};
return view;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if (mItems == null || mItems.size() == 0) {
// Execute an async task to fetch and display the items
new PortalItemsAsyncTask().execute();
}
}
/**
* This class provides an AsyncTask that fetches info about portal items from the server on a
* background thread and displays it in a list on the UI thread.
*/
private class PortalItemsAsyncTask extends AsyncTask<Void, Void, Void> {
private Exception mException;
public PortalItemsAsyncTask() {
}
@Override
protected void onPreExecute() {
// Display progress dialog on UI thread
mProgressDialog.setOnDismissListener(new OnDismissListener() {
@Override
public void onDismiss(DialogInterface arg0) {
// Cancel the task if it's not finished yet
PortalItemsAsyncTask.this.cancel(true);
}
});
mProgressDialog.setMessage(getString(R.string.fetchingItems));
mProgressDialog.show();
}
@Override
protected Void doInBackground(Void... params) {
mException = null;
try {
// Do a query for all web maps in the given group
PortalQueryParams queryParams = new PortalQueryParams();
queryParams.setQuery(PortalItemType.WEBMAP, mPortalGroup.getGroupId(), null);
PortalQueryResultSet<PortalItem> results = mPortal.findItems(queryParams);
if (isCancelled()) {
return null;
}
// Loop through query results
for (PortalItem item : results.getResults()) {
Log.d(TAG, "[item title] " + item.getTitle());
// Fetch item thumbnail (if any) from server
byte[] data = item.fetchThumbnail();
if (isCancelled()) {
return null;
}
if (data != null) {
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
PortalItemData portalItemData = new PortalItemData(item, bitmap);
mItems.add(portalItemData);
}
}
} catch (Exception e) {
mException = e;
}
return null;
}
@Override
protected void onPostExecute(Void result) {
// Display results on UI thread
mProgressDialog.dismiss();
if (mException != null) {
Log.w(TAG, mException.toString());
Toast.makeText(getActivity(), getString(R.string.fetchDataFailed), Toast.LENGTH_LONG)
.show();
getFragmentManager().popBackStack(); // kill this fragment
return;
}
mAdapter.notifyDataSetChanged();
}
}
/**
* This class provides the adapter for the list of portal items.
*/
private class PortalItemListAdapter extends ArrayAdapter<PortalItemData> {
public PortalItemListAdapter(Context context, ArrayList<PortalItemData> items) {
super(context, 0, items);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
// Inflate view unless we've been given an existing view to reuse
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.list_item, null);
}
// Setup item thumbnail
PortalItemData item = getItem(position);
ImageView image = (ImageView) view.findViewById(R.id.itemThumbnailImageView);
image.setImageBitmap(item.itemThumbnail);
// Setup item title
TextView text = (TextView) view.findViewById(R.id.itemTitleTextView);
text.setText(item.portalItem.getTitle());
return view;
}
}
/**
* This class holds data for a portal item.
*/
private class PortalItemData {
PortalItem portalItem;
Bitmap itemThumbnail;
public PortalItemData(PortalItem item, Bitmap bt) {
this.portalItem = item;
this.itemThumbnail = bt;
}
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package jopos;
import Conexao.Conexao;
import exceptions.PessoaException;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author Matheus Maia
*/
public class pessoa {
private int id;
private String nome;
private String Sobrenome;
private String endereco;
private String cpf;
private Date dataNasc;
private String email;
private String telefone;
public void validarCPF(String cpf) throws PessoaException {
int d1, d2;
int digito1, digito2, resto;
int digitoCPF;
String nDigResult;
d1 = d2 = 0;
digito1 = digito2 = resto = 0;
for (int nCount = 1; nCount < cpf.length() - 1; nCount++) {
digitoCPF = Integer.valueOf(cpf.substring(nCount - 1, nCount)).intValue();
d1 = d1 + (11 - nCount) * digitoCPF;
d2 = d2 + (12 - nCount) * digitoCPF;
};
resto = (d1 % 11);
if (resto < 2) {
digito1 = 0;
} else {
digito1 = 11 - resto;
}
d2 += 2 * digito1;
resto = (d2 % 11);
if (resto < 2) {
digito2 = 0;
} else {
digito2 = 11 - resto;
}
String nDigVerific = cpf.substring(cpf.length() - 2, cpf.length());
nDigResult = String.valueOf(digito1) + String.valueOf(digito2);
if (nDigVerific.equals(nDigResult) == false) {
throw new PessoaException("CPF INVALIDO!");
};
}
public void adicionar(pessoa p) throws ClassNotFoundException, SQLException {
Conexao connm = new Conexao();
try (Connection conn = connm.obterConexao();
PreparedStatement stmt = conn.prepareStatement(
"INSERT INTO Pessoa (nome, sobrenome, entedereco, cpf, dataNasc, email, telefone)"
+ "VALUES (?,?,?,?,?,?,?) ")) {
stmt.setString(1, p.getNome());
stmt.setString(2, p.getSobrenome());
stmt.setString(3, p.getEndereco());
stmt.setString(4, p.getCpf());
stmt.setDate(5, p.getDataNasc());
stmt.setString(6, p.getEmail());
stmt.setString(7, p.getTelefone());
int status = stmt.executeUpdate();
conn.close();
} catch (SQLException ex) {
System.err.println(ex.getMessage());
} catch (ClassNotFoundException ex) {
System.err.println(ex.getMessage());
}
}
public void excluir() throws ClassNotFoundException, SQLException {
Conexao connm = new Conexao();
try (Connection conn = connm.obterConexao();
PreparedStatement stmt = conn.prepareStatement(
"DELETE FROM PESSOA WHERE id = ? ")) {
stmt.setString(1, "id");
stmt.executeUpdate();
conn.close();
} catch (SQLException ex) {
System.err.println(ex.getMessage());
} catch (ClassNotFoundException ex) {
System.err.println(ex.getMessage());
}
}
public void atualizar(pessoa p) throws ClassNotFoundException, SQLException {
Conexao connm = new Conexao();
try {
Connection conn = connm.obterConexao();
PreparedStatement stmt = conn.prepareStatement("UPDATE PESSOA SET "
+ "nome = ?,sobrenomeo =?,entedereco=?, cpf=?, dataNasc=?, email=?, telefone=?"
+ "FROM PRODUTO WHERE ID = ?");
stmt.setString(1, p.getNome());
stmt.setString(2, p.getSobrenome());
stmt.setString(3, p.getEndereco());
stmt.setString(4, p.getCpf());
stmt.setDate(5, p.getDataNasc());
stmt.setString(6, p.getEmail());
stmt.setString(7, p.getTelefone());
stmt.setLong(8, p.getId());
stmt.executeUpdate();
conn.close();
} catch (SQLException ex) {
System.err.println(ex.getMessage());
} catch (ClassNotFoundException ex) {
System.err.println(ex.getMessage());
}
}
public pessoa obter(int id) throws SQLException, Exception {
Conexao connm = new Conexao();
String sql = "SELECT * FROM PESSOA WHERE (id=?)";
PreparedStatement preparedStatement = null;
ResultSet result = null;
Connection conn = connm.obterConexao();
try {
preparedStatement = conn.prepareStatement(sql);
preparedStatement.setInt(1, id);
preparedStatement.setBoolean(2, true);
result = preparedStatement.executeQuery();
if (result.next()) {
pessoa p = new pessoa();
p.setId(result.getInt("id"));
p.setNome(result.getString("nome"));
p.setSobrenome(result.getString("sobrenome"));
p.setEndereco(result.getString("entedereco"));
p.setCpf(result.getString("cpf"));
p.setDataNasc(result.getDate("dataNasc"));
p.setEmail(result.getString("email"));
p.setTelefone(result.getString("telefone"));
return p;
}
} finally {
if (result != null && !result.isClosed()) {
result.close();
}
if (preparedStatement != null && !preparedStatement.isClosed()) {
preparedStatement.close();
}
if (conn != null && !conn.isClosed()) {
conn.close();
}
}
return null;
}
public List<pessoa> procurar(String valor) throws SQLException, Exception {
String sql = "SELECT * FROM PESSOA WHERE ((UPPER(nome) LIKE UPPER(?) ";
List<pessoa> listaPessoas = null;
Conexao connm = new Conexao();
PreparedStatement preparedStatement = null;
ResultSet result = null;
Connection conn = connm.obterConexao();
try {
preparedStatement = conn.prepareStatement(sql);
preparedStatement.setString(1, "%" + valor + "%");
result = preparedStatement.executeQuery();
while (result.next()) {
if (listaPessoas == null) {
listaPessoas= new ArrayList<pessoa>();
}
pessoa p = new pessoa();
p.setId(result.getInt("id"));
p.setNome(result.getString("nome"));
p.setSobrenome(result.getString("sobrenome"));
p.setEndereco(result.getString("entedereco"));
p.setCpf(result.getString("cpf"));
p.setDataNasc(result.getDate("dataNasc"));
p.setEmail(result.getString("email"));
p.setTelefone(result.getString("telefone"));
listaPessoas.add(p);
}
} finally {
if (result != null && !result.isClosed()) {
result.close();
}
if (preparedStatement != null && !preparedStatement.isClosed()) {
preparedStatement.close();
}
if (conn != null && !conn.isClosed()) {
conn.close();
}
}
return listaPessoas;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getSobrenome() {
return Sobrenome;
}
public void setSobrenome(String Sobrenome) {
this.Sobrenome = Sobrenome;
}
public String getEndereco() {
return endereco;
}
public void setEndereco(String endereco) {
this.endereco = endereco;
}
public String getCpf() {
return cpf;
}
public void setCpf(String cpg) {
this.cpf = cpf;
}
public Date getDataNasc() {
return dataNasc;
}
public void setDataNasc(Date dataNasc) {
this.dataNasc = dataNasc;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getTelefone() {
return telefone;
}
public void setTelefone(String telefone) {
this.telefone = telefone;
}
}
|
package webElementMethods;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class ElementVerificationMethods {
public static void main(String[] args) throws Exception {
// Verification of the elements in browser
// isEnabled()
// isDisplayed()
// isSelected()
System.setProperty("webdriver.chrome.driver", "E:\\AutomationPractice\\Core Java\\selenium\\src\\test\\resources\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://automationpractice.com/index.php?controller=authentication&back=my-account#account-creation");
WebElement btn = driver.findElement(By.id("SubmitLogin"));
driver.findElement(By.id("email")).sendKeys("admin@def.com");
driver.findElement(By.id("passwd")).sendKeys("admin");
btn.click();
try {
if(driver.findElement(By.cssSelector("div.alert.alert-danger")).isDisplayed()) {
System.out.println(driver.findElement(By.cssSelector("div.alert.alert-danger p")).getText());
}
}catch (Exception e) {
// throw new Exception("Button is disabled");
System.out.println(e.getMessage());
}
// if(driver.findElement(By.cssSelector("div.alert.alert-danger")).isDisplayed()) {
// System.out.println(driver.findElement(By.cssSelector("div.alert.alert-danger p")).getText());
// }
// else {
// throw new Exception("Button is disabled");
// }
// driver.close();
// if(btn.isEnabled()) {
// driver.findElement(By.id("email")).sendKeys("admin@def.com");
// driver.findElement(By.id("passwd")).sendKeys("admin");
// btn.click();
// } else {
// throw new Exception("Button is disabled");
// }
//
// if(driver.findElement(By.cssSelector("div.alert.alert-danger")).isDisplayed()) {
// System.out.println(driver.findElement(By.cssSelector("div.alert.alert-danger p")).getText());
// }
// Ternary operator
// btn.isEnabled()?btn.click():throw new Exception("Button is disabled");
// int a = 20;
// a <10 ? System.out.println(" a is smaller") : System.out.println("a is larger");
}
}
|
package com.example.studyResultfulAPI.controller;
import com.example.studyResultfulAPI.Result;
import com.example.studyResultfulAPI.ResultCode;
import com.example.studyResultfulAPI.pojo.Order;
import com.example.studyResultfulAPI.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
/**
* @PackageName: com.example.studyResultfulAPI.controller
* @ClassName: OrderController
* @Description: TODO
* @author: qiuweijie
* @date: 2019/12/10 11:36
*/
@RestController
@RequestMapping("/orders")
public class OrderController {
@Autowired
OrderService orderService;
//@GetMapping("{id}")
//public Result getOrder(@PathVariable("id") Integer id){
// Order order = (Order) orderService.getOrderById(id);
// return new Result(ResultCode.SUCCESS, order);
//}
@GetMapping("{id}")
public Result getOrder(@PathVariable("id") Integer id){
if(id == null){
return Result.failure(ResultCode.PARAM_IS_INVALID);
}
Order order = orderService.getOrderById(id);
return Result.success(order);
}
}
|
package com.gxtc.huchuan.widget;
import android.content.Context;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.TextAppearanceSpan;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.gxtc.commlibrary.recyclerview.RecyclerView;
import com.gxtc.commlibrary.utils.ToastUtil;
import com.gxtc.huchuan.MyApplication;
import com.gxtc.huchuan.R;
import com.gxtc.huchuan.utils.ClickUtil;
import com.gxtc.huchuan.utils.StringUtil;
import rx.Subscription;
/**
* Created by sjr on 2017/5/12.
*/
public class CircleMainHeadView extends LinearLayout {
private com.gxtc.commlibrary.recyclerview.RecyclerView mRecyclerView;
private MarqueeView mMarqueeView;
private LinearLayout llNotice;
private View line;
private Context mContext;
private TextView commission;
private OnItemClickListener listener;
private int circleId;
private boolean isPreviews;
private String notice;//圈子公告
public View dotBest;
public View dotChatInfo;
public View dotClass;
public View dotFile;
public CircleMainHeadView(Context context, RecyclerView mRecyclerView, int circleId, String notice, boolean isPreviews) {
super(context);
this.mRecyclerView = mRecyclerView;
this.mContext = context;
this.circleId = circleId;
this.notice = notice;
this.isPreviews = isPreviews;
initView();
}
public void ShowCommission(double com){
if(com > 0) {
String text1 = "本圈邀请好友有奖励," + "邀请一位获得" ;
String text2 = StringUtil.formatMoney(2, com) + "元";
SpannableString ss2 = new SpannableString(text1 + text2 + "佣金");
TextAppearanceSpan dealSpan2 = new TextAppearanceSpan(mContext, R.style.circle_invite_text_color);
ss2.setSpan(dealSpan2, text1.length(), text1.length()+text2.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
commission.setText(ss2);
}
}
private void initView() {
View view = LayoutInflater.from(getContext()).inflate(
R.layout.item_circle_main_head, mRecyclerView, false);
mMarqueeView = (MarqueeView) view.findViewById(R.id.marquee_view);
llNotice = (LinearLayout) view.findViewById(R.id.ll_notice);
dotBest = view.findViewById(R.id.dragView_msg_best);
dotChatInfo = view.findViewById(R.id.dragView_msg_chatinfo);
dotClass = view.findViewById(R.id.dragView_msg_class);
dotFile = view.findViewById(R.id.dragView_msg_file);
line = view.findViewById(R.id.view_notice);
commission=view.findViewById(R.id.tv_havecommission);
//发表
view.findViewById(R.id.ll_circle_main_head_fabiao).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (ClickUtil.isFastClick()) return;
if(isPreviews){
ToastUtil.showShort(mContext,"加入圈子可以发表动态!");
}else{
listener.onFaBiao();
}
}
});
//文章
view.findViewById(R.id.ll_circle_main_head_article).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (ClickUtil.isFastClick()) return;
if(isPreviews){
ToastUtil.showShort(mContext,"加入圈子可以查看更多内容哦!");
}else{
listener.onArticle();
}
}
});
//课堂
view.findViewById(R.id.ll_circle_main_head_classroom).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (ClickUtil.isFastClick()) return;
if(isPreviews){
ToastUtil.showShort(mContext,"加入圈子可以查看更多内容哦!");
}else{
listener.onClassRoom();
}
}
});
//文件
view.findViewById(R.id.ll_circle_main_head_file).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (ClickUtil.isFastClick()) return;
if(isPreviews){
ToastUtil.showShort(mContext,"加入圈子可以查看更多内容哦!");
}else{
listener.onFile();
}
}
});
//邀请
view.findViewById(R.id.btn_yaoqing).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (ClickUtil.isFastClick()) return;
if(!isPreviews){
listener.onYaoQing();
}
}
});
initData();
this.addView(view);
}
private void initData() {
if (!TextUtils.isEmpty(notice)) {
llNotice.setVisibility(View.VISIBLE);
line.setVisibility(View.VISIBLE);
TextView textView = new TextView(MyApplication.getInstance());
textView.setTextColor(getResources().getColor(R.color.text_color_333));
textView.setText(notice);
textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.textSize_s));
mMarqueeView.addViewInQueue(textView);
mMarqueeView.setScrollSpeed(8);
mMarqueeView.setScrollDirection(MarqueeView.RIGHT_TO_LEFT);
mMarqueeView.setViewMargin(15);
mMarqueeView.startScroll();
//公告
llNotice.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (ClickUtil.isFastClick()) return;
listener.onNotice();
}
});
} else {
llNotice.setVisibility(View.GONE);
line.setVisibility(View.GONE);
}
}
public void removeRunable(){
mMarqueeView.removeCallbacks(mMarqueeView); //把Runable干掉,不然造成内存泄漏
mMarqueeView = null;
}
public void setOnItemCLickLisetner(OnItemClickListener itemListener) {
this.listener = itemListener;
}
public interface OnItemClickListener {
void onFaBiao();
void onArticle();
void onClassRoom();
void onFile();
void onNotice();
void onYaoQing();
}
public void setNotice(String notice) {
this.notice = notice;
initData();
}
}
|
package com.vika.addressBook;
public class Address {
int houseNumber;
String streetName;
String cityName;
String state;
int zipCode;
public int getHouseNumber() {
return houseNumber;
}
public void setHouseNumber(int houseNumber) {
this.houseNumber = houseNumber;
}
public String getStreetName() {
return streetName;
}
public void setStreetName(String streetName) {
this.streetName = streetName;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public int getZipCode() {
return zipCode;
}
public void setZipCode(int zipCode) {
this.zipCode = zipCode;
}
}
|
package com.esum.comp.ftasoap.message.util;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import org.apache.commons.io.IOUtils;
public class ByteWrapper {
private ByteArrayInputStream mInputStream = null;
private int mSize = -1;
public ByteWrapper(byte[] data) {
mInputStream = new ByteArrayInputStream(data);
mSize = mInputStream.available();
}
/**
* 파라미터로 지정한 길이만큼 스트링으로 리턴한다.<br>
* String 클래스의 substring() 메소드와 같다.
*
* @param beginIndex 시작 인덱스
* @param endIndex 끝 인덱스
* @return String
*/
public String subString(int beginIndex, int endIndex) throws UnsupportedEncodingException {
int size = endIndex - beginIndex;
byte[] buffer = new byte[size];
mInputStream.reset();
mInputStream.skip(beginIndex);
mInputStream.read(buffer, 0, size);
try {
return new String(buffer, 0, size, "euc-kr");
} catch (UnsupportedEncodingException e) {
throw e;
}
}
/**
* 파라미터로 지정한 길이만큼 byte[]으로 리턴한다.<br>
* String 클래스의 subString() 메소드와 비슷하다.
*
* @param beginIndex 시작 인덱스
* @param endIndex 끝 인덱스
* @return byte[]
*/
public byte[] subByte(int beginIndex, int endIndex) {
int size = endIndex - beginIndex;
byte[] buffer = new byte[size];
mInputStream.reset();
mInputStream.skip(beginIndex);
mInputStream.read(buffer, 0, size);
ByteArrayOutputStream out = null;
try {
out = new ByteArrayOutputStream();
out.write(buffer, 0, size);
return out.toByteArray();
} finally {
IOUtils.closeQuietly(out);
}
}
/**
* 파라미터로 받은 인덱스부터 byte[]의 마지막까지 읽은 후 스트링으로 리턴한다.<br>
* String 클래스의 substring() 메소드와 같다.
*
* @param beginIndex 시작 인덱스
* @return String
*/
public String subString(int beginIndex) throws UnsupportedEncodingException {
int size = mSize - beginIndex;
byte[] buffer = new byte[size];
mInputStream.reset();
mInputStream.skip(beginIndex);
mInputStream.read(buffer, 0, size);
try {
return new String(buffer, 0, size, "euc-kr");
} catch (UnsupportedEncodingException e) {
throw e;
}
}
/**
* 읽은 byte[] 타입의 데이터를 모두 String으로 반환한다.<br>
* toString()과 같은 기능이다.
*
* @author hg.han
* @version 2006.04.20
* @return String
* @throws UnsupportedEncodingException
*/
public String getString() throws UnsupportedEncodingException{
int size = mSize;
byte[] buffer = new byte[size];
mInputStream.reset();
mInputStream.read(buffer, 0, size);
try {
return new String(buffer, 0, size, "euc-kr");
} catch (UnsupportedEncodingException e) {
throw e;
}
}
}
|
package com.example.android.nusevents;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DialogFragment;
import android.app.Fragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.example.android.nusevents.model.EventInfo;
import com.firebase.client.Firebase;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
//import static com.example.android.nusevents.MainActivity.displaymessage;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import static android.R.attr.data;
import static android.R.attr.elegantTextHeight;
import static android.R.attr.y;
import static android.os.Build.VERSION_CODES.M;
import static com.example.android.nusevents.MainActivity.RC_SIGN_IN;
public class Details extends FragmentActivity {
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
android.Manifest.permission.READ_EXTERNAL_STORAGE,
android.Manifest.permission.WRITE_EXTERNAL_STORAGE
};
private CheckBox goodieCheck,snacksCheck;
private FirebaseDatabase mFireBaseDataBase;
private DatabaseReference mEventInfo;
private Button mSendButton;
EditText nameField, organizeField, eventField, timeField, locField, contactfield,linkAddress;
String name, organize, event, time, location, id, contact,date,count;
boolean goodie,snacks;
String link="";
boolean free;
private static final int RC_PHOTO_PICKER = 2;
Uri downloadUrl;
String pic_uri="";
public static Button timeButton;
public static Button dateButton;
private ImageButton mPhotoPickerButton;
public static int year, month, day, hour, min;
public static int yearF, monthF, dayF, hourF, minF;
public static Button timeButtonFinish;
public static Button dateButtonFinish;
private Spinner sp1;
private FirebaseStorage mFirebaseStorage;
private StorageReference mChatPhotosStorageReference;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
sp1 = (Spinner) findViewById(R.id.spinner);
linkAddress=(EditText)findViewById(R.id.bookTicket);
goodieCheck=(CheckBox)findViewById(R.id.goodieBox);
snacksCheck=(CheckBox)findViewById(R.id.snacksBox);
goodieCheck.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(goodieCheck.isChecked()){
goodie=true;
}
else
{
goodie=false;
}
}
});
snacksCheck.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(snacksCheck.isChecked()){
snacks=true;
}
else
{
snacks=false;
}
}
});
final List<String> list = new ArrayList<String>();
list.add("Free");
list.add("Paid");
ArrayAdapter<String> adp1 = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, list);
adp1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp1.setAdapter(adp1);
sp1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long id) {
// TODO Auto-generated method stub
if(list.get(position).equals("Free")){
free=true;
link="";
linkAddress.setVisibility(View.GONE);
}
else
{
free=false;
linkAddress.setVisibility(View.VISIBLE);
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
verifyStoragePermissions(this);
mFirebaseStorage = FirebaseStorage.getInstance();
mChatPhotosStorageReference = mFirebaseStorage.getReference().child("events_poster");
mFireBaseDataBase = FirebaseDatabase.getInstance();
mEventInfo = mFireBaseDataBase.getReference().child("Events");
mSendButton = (Button) findViewById(R.id.sendButton);
dateButton = (Button) findViewById(R.id.datepicker);
timeButton = (Button) findViewById(R.id.timepicker);
dateButtonFinish = (Button) findViewById(R.id.datepickerfinish);
timeButtonFinish = (Button) findViewById(R.id.timepickerfinish);
mPhotoPickerButton = (ImageButton) findViewById(R.id.photoPickerButton);
// ImagePickerButton shows an image picker to upload a image for a message
mPhotoPickerButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
//intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), RC_PHOTO_PICKER);
}
});
mSendButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
nameField = (EditText) findViewById(R.id.event_name);
name = nameField.getText().toString();
organizeField = (EditText) findViewById(R.id.organize);
organize = organizeField.getText().toString();
eventField = (EditText) findViewById(R.id.about_event);
event = eventField.getText().toString();
//timeField = (EditText)findViewById(R.id.time_event);
//time = timeField.getText().toString();
locField = (EditText) findViewById(R.id.location);
location = locField.getText().toString();
link=linkAddress.getText().toString();
//id = mEventInfo.push().getKey();
contactfield = (EditText) findViewById(R.id.contact_details);
contact = contactfield.getText().toString();
count="0";
String dateString = day + "/" + month + "/" + year + " " + hour + ":" + min;
date=day + "/" + month + "/" + year;
if(day/10==0)
{
date="0"+day + "/" + month + "/" + year;
}
if (month/10==0)
{
date=day + "/0" + month + "/" + year;
}
if(day/10==0&&month/10==0){
date="0"+day + "/0" + month + "/" + year;
}
long eventDateLong = 0;
try {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm");
Date eventDate = sdf.parse(dateString);
eventDateLong = eventDate.getTime();
} catch (ParseException e) {
}
String dateStringF = dayF + "/" + monthF + "/" + yearF + " " + hourF + ":" + minF;
long eventDateLongF = 0;
try {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm");
Date eventDate = sdf.parse(dateStringF);
eventDateLongF = eventDate.getTime();
} catch (ParseException e) {
}
FirebaseAuth mAuth = FirebaseAuth.getInstance();
FirebaseUser currUser = mAuth.getCurrentUser();
DatabaseReference mypostref = mEventInfo.push();
id = mypostref.getKey();
String currUid = currUser.getUid();
EventInfo object = new EventInfo(name, eventDateLong, location, event, organize, currUid, id, contact, eventDateLongF,date,pic_uri,count,free,link,goodie,snacks);
if (eventDateLong < System.currentTimeMillis() || eventDateLong > eventDateLongF||eventDateLong==0||eventDateLongF==0) {
popUp();
} else {
mypostref.setValue(object);
//mEventInfo.setValue(object);
nameField.setText("");
organizeField.setText("");
eventField.setText("");
linkAddress.setText("");
//timeField.setText("");
locField.setText("");
contactfield.setText("");
dateButton.setText("Enter Start Date");
timeButton.setText("Enter Start Time");
dateButtonFinish.setText("Enter Finish Date");
timeButtonFinish.setText("Enter Finish Time");
goodieCheck.setChecked(false);
snacksCheck.setChecked(false);
displaymessage();
}
}
});
}
public void displaymessage() {
AlertDialog.Builder myAlert1 = new AlertDialog.Builder(this);
myAlert1.setMessage("Your event has been added .Thank You!")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
finish();
}
})
.create();
myAlert1.show();
}
public void popUp(){AlertDialog.Builder myAlert1 = new AlertDialog.Builder(this);
myAlert1.setMessage("Please check if Date and Time of start and end Time are logically correct")
.
setPositiveButton("OK",new DialogInterface.OnClickListener() {
@Override
public void onClick (DialogInterface dialog,int which){
dialog.dismiss();
}
})
.
create();
myAlert1.show();
}
public void showDatePickerDialog(View v) {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getFragmentManager(),"DatePicker");
}
public static void showDate(int y,int m,int d)
{
year=y;
month=m+1;
day=d;
dateButton.setText(d+"-"+month+"-"+y);
}
public void showTimePickerDialog(View v) {
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getFragmentManager(), "timePicker");
}
public static void showTime(int h,int m)
{
hour=h;
min=m;
if(m/10==0) {
timeButton.setText(h + ":0" + m);
}
else{
timeButton.setText(h + ":" + m);
}
}
public void showDateFinishPickerDialog(View v) {
DialogFragment newFragment = new DateFinishPickerFragment();
newFragment.show(getFragmentManager(),"DatePicker");
}
public static void showFinishDate(int y,int m,int d)
{
yearF=y;
monthF=m+1;
dayF=d;
dateButtonFinish.setText(d+"-"+monthF+"-"+y);
}
public void showTimeFinishPickerDialog(View v) {
DialogFragment newFragment = new TimeFinishPickerFragment();
newFragment.show(getFragmentManager(), "timePicker");
}
public static void showFinishTime(int h,int m)
{
hourF=h;
minF=m;
if(minF/10==0) {
timeButtonFinish.setText(h + ":0" + m);
}
else{
timeButtonFinish.setText(h + ":" + m);
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_PHOTO_PICKER) {
if(data==null){
Toast.makeText(this,"Image not uploaded. Try again! ",Toast.LENGTH_SHORT).show();
}
else {
Uri selectedImageUri = data.getData();
// Get a reference to store file at chat_photos/<FILENAME>
StorageReference photoRef = mChatPhotosStorageReference.child(selectedImageUri.getLastPathSegment());
// Upload file to Firebase Storage
photoRef.putFile(selectedImageUri)
.addOnSuccessListener(this, new OnSuccessListener<UploadTask.TaskSnapshot>() {
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// When the image has successfully uploaded, we get its download URL
downloadUrl = taskSnapshot.getDownloadUrl();
pic_uri = downloadUrl.toString();
// Set the download URL to the message box, so that the user can send it to the database
}
});
}
}
}
public static void verifyStoragePermissions(Activity activity) {
// Check if we have write permission
int permission = ActivityCompat.checkSelfPermission(activity, android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
// We don't have permission so prompt the user
ActivityCompat.requestPermissions(
activity,
PERMISSIONS_STORAGE,
REQUEST_EXTERNAL_STORAGE
);
}
}
}
|
package hu.mitro.persistence.entity;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
@Entity
@Table(name = "contracts")
@NamedQueries(value = { //
@NamedQuery(name = "checkExistingContract", query = "SELECT COUNT(c) FROM Contract c "
+ "WHERE c.contractId=:contractid"),
@NamedQuery(name = "getAllOfContracts", query = "SELECT c FROM Contract c LEFT JOIN FETCH c.client cl "
+ "LEFT JOIN FETCH c.car cr ORDER BY c.date DESC"),
@NamedQuery(name = "getContractByContractId", query = "SELECT c FROM Contract c LEFT JOIN FETCH c.client cl "
+ "LEFT JOIN FETCH c.car cr WHERE c.contractId=:contractid"),
@NamedQuery(name = "getContractById", query = "SELECT c FROM Contract c LEFT JOIN FETCH c.client cl "
+ "LEFT JOIN FETCH c.car cr WHERE c.id=:id"),
@NamedQuery(name = "getContractOfClient", query = "SELECT c FROM Contract c LEFT JOIN FETCH c.client cl "
+ "LEFT JOIN FETCH c.car cr WHERE c.client.email=:email"),
@NamedQuery(name = "getContractByCar", query = "SELECT c FROM Contract c LEFT JOIN FETCH c.client cl "
+ "LEFT JOIN FETCH c.car cr WHERE c.car.licencePlateNumber=:licenceplateNumber"),
@NamedQuery(name = "getContractByDate", query = "SELECT c FROM Contract c LEFT JOIN FETCH c.client cl "
+ "LEFT JOIN FETCH c.car cr WHERE c.date=:date"),
@NamedQuery(name = "getContractByActive", query = "SELECT c FROM Contract c LEFT JOIN FETCH c.client cl "
+ "LEFT JOIN FETCH c.car cr WHERE c.active=true")
//
})
public class Contract implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@SequenceGenerator(name = "generatorContract", sequenceName = "contracts_contract_id_seq", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "generatorContract")
@Column(name = "contract_id", nullable = false)
private Long id;
@Column(name = "contract_contractid", nullable = false)
private String contractId;
@Column(name = "contract_date", nullable = false)
private Date date;
@Column(name = "contract_duration", nullable = false)
private int duration;
@Column(name = "contract_installment", nullable = false)
private double installment;
@Column(name = "contract_interestrate", nullable = false)
private double interestrate;
@Column(name = "contract_downpayment", nullable = false)
private double downpayment;
@Column(name = "contract_contractamount", nullable = false)
private double contractamount;
@Column(name = "contract_active", nullable = false)
private boolean active;
@ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL, optional = false)
@JoinColumn(name = "contract_client_id", referencedColumnName = "client_id", nullable = false)
private Client client;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "contract_car_id")
private Car car;
public Contract() {
}
public Contract(String contractId, Date date, int duration, double installment,
double interestrate, double downpayment, double contractamount,
boolean active, Client client, Car car) {
this.contractId = contractId;
this.date = date;
this.duration = duration;
this.installment = installment;
this.interestrate = interestrate;
this.downpayment = downpayment;
this.contractamount = contractamount;
this.active = active;
this.client = client;
this.car = car;
}
public Contract(String contractId, Date date, int duration, double installment,
double interestrate, double downpayment, double contractamount,
boolean active) {
this(contractId, date, duration, installment, interestrate, downpayment,
contractamount, active, null, null);
}
public Long getId() {
return id;
}
public String getContractId() {
return contractId;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public void setContractId(String contractId) {
this.contractId = contractId;
}
public int getDuration() {
return duration;
}
public void setDuration(int duration) {
this.duration = duration;
}
public double getInstallment() {
return installment;
}
public void setInstallment(double installment) {
this.installment = installment;
}
public double getInterestrate() {
return interestrate;
}
public void setInterestrate(double interestrate) {
this.interestrate = interestrate;
}
public double getDownpayment() {
return downpayment;
}
public void setDownpayment(double downpayment) {
this.downpayment = downpayment;
}
public double getContractamount() {
return contractamount;
}
public void setContractamount(double contractamount) {
this.contractamount = contractamount;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public Client getClient() {
return client;
}
public void setClient(Client client) {
this.client = client;
}
public Car getCar() {
return car;
}
public void setCar(Car car) {
this.car = car;
}
@Override
public String toString() {
return "Contract [id=" + id + ", contractId=" + contractId + ", date=" + date
+ ", duration=" + duration + ", installment=" + installment
+ ", interestrate=" + interestrate + ", downpayment=" + downpayment
+ ", contractamount=" + contractamount + ", active=" + active
+ ", client=" + client + ", car=" + car + "]";
}
}
|
/*
* Copyright (c) 2013-2014, Neuro4j.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.neuro4j.studio.debug.ui.views;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.debug.internal.ui.DebugUIPlugin;
import org.eclipse.debug.internal.ui.IDebugHelpContextIds;
import org.eclipse.debug.internal.ui.actions.ActionMessages;
import org.eclipse.debug.internal.ui.viewers.FindElementDialog;
import org.eclipse.debug.internal.ui.viewers.model.ILabelUpdateListener;
import org.eclipse.debug.internal.ui.viewers.model.TimeTriggeredProgressMonitorDialog;
import org.eclipse.debug.internal.ui.viewers.model.provisional.IChildrenUpdate;
import org.eclipse.debug.internal.ui.viewers.model.provisional.ILabelUpdate;
import org.eclipse.debug.internal.ui.viewers.model.provisional.IModelDelta;
import org.eclipse.debug.internal.ui.viewers.model.provisional.IModelDeltaVisitor;
import org.eclipse.debug.internal.ui.viewers.model.provisional.IViewerUpdate;
import org.eclipse.debug.internal.ui.viewers.model.provisional.IViewerUpdateListener;
import org.eclipse.debug.internal.ui.viewers.model.provisional.ModelDelta;
import org.eclipse.debug.internal.ui.viewers.model.provisional.VirtualItem;
import org.eclipse.debug.internal.ui.viewers.model.provisional.VirtualTreeModelViewer;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.TreePath;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.ui.IWorkbenchCommandConstants;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.texteditor.IUpdate;
import com.ibm.icu.text.MessageFormat;
/**
* Action which prompts user with a filtered list selection dialog to find an element in tree.
*
* @since 3.3
*/
public class VirtualFindAction extends Action implements IUpdate {
private TreeModelViewer fClientViewer;
private class VirtualViewerListener implements IViewerUpdateListener, ILabelUpdateListener {
private boolean fViewerUpdatesComplete = false;
private boolean fLabelUpdatesComplete = false;
private IProgressMonitor fProgressMonitor;
private int fRemainingUpdatesCount = 0;
public void labelUpdateStarted(ILabelUpdate update) {
}
public void labelUpdateComplete(ILabelUpdate update) {
incrementProgress(1);
}
public void labelUpdatesBegin() {
fLabelUpdatesComplete = false;
}
public void labelUpdatesComplete() {
fLabelUpdatesComplete = true;
completeProgress();
}
public void updateStarted(IViewerUpdate update) {
}
public void updateComplete(IViewerUpdate update) {
if (update instanceof IChildrenUpdate) {
incrementProgress(((IChildrenUpdate) update).getLength());
}
}
public void viewerUpdatesBegin() {
fViewerUpdatesComplete = false;
}
public void viewerUpdatesComplete() {
fViewerUpdatesComplete = true;
completeProgress();
}
private void completeProgress() {
IProgressMonitor pm;
synchronized (this) {
pm = fProgressMonitor;
}
if (pm != null && fLabelUpdatesComplete && fViewerUpdatesComplete) {
pm.done();
}
}
private void incrementProgress(int count) {
IProgressMonitor pm;
synchronized (this) {
pm = fProgressMonitor;
fRemainingUpdatesCount -= count;
}
if (pm != null && fLabelUpdatesComplete && fViewerUpdatesComplete) {
pm.worked(count);
}
}
}
private static class FindLabelProvider extends LabelProvider {
private VirtualTreeModelViewer fVirtualViewer;
private Map fTextCache = new HashMap();
public FindLabelProvider(VirtualTreeModelViewer viewer, List items) {
fVirtualViewer = viewer;
for (int i = 0; i < items.size(); i++) {
VirtualItem item = (VirtualItem) items.get(i);
fTextCache.put(item, fVirtualViewer.getText(item, 0));
}
}
public Image getImage(Object element) {
return fVirtualViewer.getImage((VirtualItem) element, 0);
}
public String getText(Object element) {
return (String) fTextCache.get(element);
}
}
public VirtualFindAction(TreeModelViewer viewer) {
fClientViewer = viewer;
setText(ActionMessages.FindAction_0);
setId(DebugUIPlugin.getUniqueIdentifier() + ".FindElementAction"); //$NON-NLS-1$
PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IDebugHelpContextIds.FIND_ELEMENT_ACTION);
setActionDefinitionId(IWorkbenchCommandConstants.EDIT_FIND_AND_REPLACE);
fClientViewer = viewer;
}
private VirtualTreeModelViewer initVirtualViewer(TreeModelViewer clientViewer, VirtualViewerListener listener) {
Object input = clientViewer.getInput();
ModelDelta stateDelta = new ModelDelta(input, IModelDelta.NO_CHANGE);
clientViewer.saveElementState(TreePath.EMPTY, stateDelta, IModelDelta.EXPAND);
listener.fRemainingUpdatesCount = calcUpdatesCount(stateDelta);
VirtualTreeModelViewer fVirtualViewer = new VirtualTreeModelViewer(
clientViewer.getDisplay(),
SWT.NONE,
clientViewer.getPresentationContext());
fVirtualViewer.setFilters(clientViewer.getFilters());
fVirtualViewer.addViewerUpdateListener(listener);
fVirtualViewer.addLabelUpdateListener(listener);
String[] columns = clientViewer.getPresentationContext().getColumns();
fVirtualViewer.setInput(input);
if (fVirtualViewer.canToggleColumns()) {
fVirtualViewer.setShowColumns(clientViewer.isShowColumns());
fVirtualViewer.setVisibleColumns(columns);
}
fVirtualViewer.updateViewer(stateDelta);
return fVirtualViewer;
}
public void run() {
final VirtualViewerListener listener = new VirtualViewerListener();
VirtualTreeModelViewer virtualViewer = initVirtualViewer(fClientViewer, listener);
ProgressMonitorDialog dialog = new TimeTriggeredProgressMonitorDialog(fClientViewer.getControl().getShell(), 500);
final IProgressMonitor monitor = dialog.getProgressMonitor();
dialog.setCancelable(true);
try {
dialog.run(
true, true,
new IRunnableWithProgress() {
public void run(final IProgressMonitor m) throws InvocationTargetException, InterruptedException {
synchronized (listener) {
listener.fProgressMonitor = m;
listener.fProgressMonitor.beginTask(DebugUIPlugin.removeAccelerators(getText()), listener.fRemainingUpdatesCount);
}
while ((!listener.fLabelUpdatesComplete || !listener.fViewerUpdatesComplete) && !listener.fProgressMonitor.isCanceled()) {
Thread.sleep(1);
}
synchronized (listener) {
listener.fProgressMonitor = null;
}
}
});
} catch (InvocationTargetException e) {
DebugUIPlugin.log(e);
return;
} catch (InterruptedException e) {
return;
}
VirtualItem root = virtualViewer.getTree();
if (!monitor.isCanceled()) {
List list = new ArrayList();
collectAllChildren(root, list);
FindLabelProvider labelProvider = new FindLabelProvider(virtualViewer, list);
VirtualItem result = performFind(list, labelProvider);
if (result != null) {
setSelectionToClient(virtualViewer, labelProvider, result);
}
}
virtualViewer.removeLabelUpdateListener(listener);
virtualViewer.removeViewerUpdateListener(listener);
virtualViewer.dispose();
}
private int calcUpdatesCount(IModelDelta stateDelta) {
final int[] count = new int[] { 0 };
stateDelta.accept(new IModelDeltaVisitor() {
public boolean visit(IModelDelta delta, int depth) {
if ((delta.getFlags() & IModelDelta.EXPAND) != 0) {
count[0] += delta.getChildCount();
return true;
}
return false;
}
});
// Double it to account for separate element and label update ticks.
return count[0] * 2;
}
private void collectAllChildren(VirtualItem element, List collect) {
VirtualItem[] children = element.getItems();
if (children != null) {
for (int i = 0; i < children.length; i++) {
if (!children[i].needsLabelUpdate()) {
collect.add(children[i]);
collectAllChildren(children[i], collect);
}
}
}
}
protected VirtualItem performFind(List items, FindLabelProvider labelProvider) {
FindElementDialog dialog = new FindElementDialog(
fClientViewer.getControl().getShell(),
labelProvider,
items.toArray());
dialog.setTitle(ActionMessages.FindDialog_3);
dialog.setMessage(ActionMessages.FindDialog_1);
if (dialog.open() == Window.OK) {
Object[] elements = dialog.getResult();
if (elements.length == 1) {
return (VirtualItem) elements[0];
}
}
return null;
}
protected void setSelectionToClient(VirtualTreeModelViewer virtualViewer, ILabelProvider labelProvider, VirtualItem findItem) {
virtualViewer.getTree().setSelection(new VirtualItem[] { findItem });
ModelDelta stateDelta = new ModelDelta(virtualViewer.getInput(), IModelDelta.NO_CHANGE);
virtualViewer.saveElementState(TreePath.EMPTY, stateDelta, IModelDelta.SELECT);
// Set the force flag to all select delta in order to override model's selection policy.
stateDelta.accept(new IModelDeltaVisitor() {
public boolean visit(IModelDelta delta, int depth) {
if ((delta.getFlags() & IModelDelta.SELECT) != 0) {
((ModelDelta) delta).setFlags(delta.getFlags() | IModelDelta.FORCE);
}
return true;
}
});
fClientViewer.updateViewer(stateDelta);
ISelection selection = fClientViewer.getSelection();
if (!selection.isEmpty() &&
selection instanceof IStructuredSelection &&
((IStructuredSelection) selection).getFirstElement().equals(findItem.getData())) {
} else {
DebugUIPlugin.errorDialog(
fClientViewer.getControl().getShell(),
ActionMessages.VirtualFindAction_0,
MessageFormat.format(ActionMessages.VirtualFindAction_1, new String[] { labelProvider.getText(findItem) }),
new Status(IStatus.ERROR, DebugUIPlugin.getUniqueIdentifier(), ActionMessages.VirtualFindAction_1));
}
}
public void update() {
setEnabled(fClientViewer.getInput() != null && fClientViewer.getChildCount(TreePath.EMPTY) > 0);
}
}
|
package com.example.chordnote.ui.period.question;
import android.util.Log;
import com.example.chordnote.data.DataManager;
import com.example.chordnote.data.network.model.QuestionsResponse;
import com.example.chordnote.ui.base.BasePresenter;
import javax.inject.Inject;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
public class QuestionPresenterImpl<V extends QuestionView> extends BasePresenter<V> implements QuestionPresenter<V> {
private static final String TAG = "QuestionPresenterImpl";
@Inject
public QuestionPresenterImpl(DataManager manager){
super(manager);
}
@Override
public void setQuestionList(int idPeriod) {
getDataManager().doGetQuestionsApiCall(idPeriod)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<QuestionsResponse>() {
@Override
public void onCompleted() {
Log.d(TAG, "onCompleted: ");
}
@Override
public void onError(Throwable e) {
Log.d(TAG, "onError: ");
}
@Override
public void onNext(QuestionsResponse questionsResponse) {
Log.d(TAG, "onNext: ");
if (questionsResponse.getCode() == 1000){
getMvpView().setQuestionList(questionsResponse.getQuestionList());
}else{
getMvpView().showToastText("获取问题失败");
}
}
});
}
}
|
/*
* LcmsSeqConditionType.java 1.00 2011-09-05
*
* Copyright (c) 2011 ???? Co. All Rights Reserved.
*
* This software is the confidential and proprietary information
* of um2m. You shall not disclose such Confidential Information
* and shall use it only in accordance with the terms of the license agreement
* you entered into with um2m.
*/
package egovframework.adm.lcms.cts.domain;
/**
* <pre>
* system :
* menu :
* source : LcmsSeqConditionType.java
* description :
* </pre>
* @version
* <pre>
* 1.0 2011-09-05 created by ?
* 1.1
* </pre>
*/
public class LcmsSeqConditionType {
private long ctIdxNum = 0;
private long seqIdNum = 0;
private long ruleConditionId = 0;
private String conditionRuleType = "";
private String ruleAction = "";
private String conditionCombination = "";
private String userId = "";
private String updateDt = "";
private long seqIdxNum = 0;
private long beforeCtIdxNum = 0;
public long getCtIdxNum() {
return ctIdxNum;
}
public long getSeqIdNum() {
return seqIdNum;
}
public long getRuleConditionId() {
return ruleConditionId;
}
public String getConditionRuleType() {
return conditionRuleType;
}
public String getRuleAction() {
return ruleAction;
}
public String getConditionCombination() {
return conditionCombination;
}
public String getUserId() {
return userId;
}
public String getUpdateDt() {
return updateDt;
}
public long getSeqIdxNum() {
return seqIdxNum;
}
public long getBeforeCtIdxNum() {
return beforeCtIdxNum;
}
public void setCtIdxNum( long ctIdxNum) {
this.ctIdxNum = ctIdxNum;
}
public void setSeqIdNum( long seqIdNum) {
this.seqIdNum = seqIdNum;
}
public void setRuleConditionId( long ruleConditionId) {
this.ruleConditionId = ruleConditionId;
}
public void setConditionRuleType( String conditionRuleType) {
this.conditionRuleType = conditionRuleType;
}
public void setRuleAction( String ruleAction) {
this.ruleAction = ruleAction;
}
public void setConditionCombination( String conditionCombination) {
this.conditionCombination = conditionCombination;
}
public void setUserId( String userId) {
this.userId = userId;
}
public void setUpdateDt( String updateDt) {
this.updateDt = updateDt;
}
public void setSeqIdxNum( long seqIdxNum) {
this.seqIdxNum = seqIdxNum;
}
public void setBeforeCtIdxNum( long beforeCtIdxNum) {
this.beforeCtIdxNum = beforeCtIdxNum;
}
}
|
package com.adv.pojo;
public class MaterialsTables {
private Integer id;
private String materials;
private Long unitPrice;
private String supplier;
private String suppPhone;
private String remark;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getMaterials() {
return materials;
}
public void setMaterials(String materials) {
this.materials = materials == null ? null : materials.trim();
}
public Long getUnitPrice() {
return unitPrice;
}
public void setUnitPrice(Long unitPrice) {
this.unitPrice = unitPrice;
}
public String getSupplier() {
return supplier;
}
public void setSupplier(String supplier) {
this.supplier = supplier == null ? null : supplier.trim();
}
public String getSuppPhone() {
return suppPhone;
}
public void setSuppPhone(String suppPhone) {
this.suppPhone = suppPhone == null ? null : suppPhone.trim();
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark == null ? null : remark.trim();
}
}
|
package testo.pl.giphyapitest.connection;
import android.graphics.drawable.Drawable;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import java.lang.reflect.Type;
/**
* Created by Lukasz Marczak on 2015-08-08.
*/
public class CatDeserializer implements JsonDeserializer<Drawable> {
@Override
public Drawable deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
return null;
}
}
|
package hu.mitro.ejb.domain;
import java.io.Serializable;
public class CarStub implements Serializable, Comparable<CarStub> {
private static final long serialVersionUID = 1L;
private String licencePlateNumber;
private CarTypeStub type;
private String model;
private String color;
private int vintage;
private double price;
private double leaseRate;
private boolean isLeasable;
private String ownerName;
private String ownerEmail;
private String contractNumber;
public CarStub() {
}
public CarStub(String licencePlateNumber, CarTypeStub type, String model, String color,
int vintage, double price, double leaseRate, boolean isLeasable, String ownerName,
String ownerEmail, String contractNumber) {
this.licencePlateNumber = licencePlateNumber;
this.type = type;
this.model = model;
this.color = color;
this.vintage = vintage;
this.price = price;
this.leaseRate = leaseRate;
this.isLeasable = isLeasable;
this.ownerName = ownerName;
this.ownerEmail = ownerEmail;
this.contractNumber = contractNumber;
}
public String getLicencePlateNumber() {
return licencePlateNumber;
}
public void setLicencePlateNumber(String licencePlateNumber) {
this.licencePlateNumber = licencePlateNumber;
}
public CarTypeStub getType() {
return type;
}
public void setType(CarTypeStub type) {
this.type = type;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getVintage() {
return vintage;
}
public void setVintage(int vintage) {
this.vintage = vintage;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public double getLeaseRate() {
return leaseRate;
}
public void setLeaseRate(double leaseRate) {
this.leaseRate = leaseRate;
}
public boolean isLeasable() {
return isLeasable;
}
public void setLeasable(boolean isLeasable) {
this.isLeasable = isLeasable;
}
public String getOwnerName() {
return ownerName;
}
public void setOwnerName(String ownerName) {
this.ownerName = ownerName;
}
public String getOwnerEmail() {
return ownerEmail;
}
public void setOwnerEmail(String ownerEmail) {
this.ownerEmail = ownerEmail;
}
public String getContractNumber() {
return contractNumber;
}
public void setContractNumber(String contractNumber) {
this.contractNumber = contractNumber;
}
@Override
public String toString() {
return "CarStub [licencePlateNumber=" + licencePlateNumber + ", type=" + type + ", model="
+ model + ", color=" + color + ", vintage=" + vintage + ", price=" + price
+ ", leaseRate=" + leaseRate + ", isLeasable=" + isLeasable + ", ownerName="
+ ownerName + ", ownerEmail=" + ownerEmail + ", contractNumber=" + contractNumber
+ "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((color == null) ? 0 : color.hashCode());
result = prime * result + (isLeasable ? 1231 : 1237);
long temp;
temp = Double.doubleToLongBits(leaseRate);
result = prime * result + (int) (temp ^ (temp >>> 32));
result = prime * result
+ ((licencePlateNumber == null) ? 0 : licencePlateNumber.hashCode());
result = prime * result + ((model == null) ? 0 : model.hashCode());
temp = Double.doubleToLongBits(price);
result = prime * result + (int) (temp ^ (temp >>> 32));
result = prime * result + ((type == null) ? 0 : type.hashCode());
result = prime * result + vintage;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
CarStub other = (CarStub) obj;
if (color == null) {
if (other.color != null) {
return false;
}
} else if (!color.equals(other.color)) {
return false;
}
if (isLeasable != other.isLeasable) {
return false;
}
if (Double.doubleToLongBits(leaseRate) != Double.doubleToLongBits(other.leaseRate)) {
return false;
}
if (licencePlateNumber == null) {
if (other.licencePlateNumber != null) {
return false;
}
} else if (!licencePlateNumber.equals(other.licencePlateNumber)) {
return false;
}
if (model == null) {
if (other.model != null) {
return false;
}
} else if (!model.equals(other.model)) {
return false;
}
if (Double.doubleToLongBits(price) != Double.doubleToLongBits(other.price)) {
return false;
}
if (type != other.type) {
return false;
}
if (vintage != other.vintage) {
return false;
}
return true;
}
@Override
public int compareTo(CarStub o) {
return getLicencePlateNumber().compareTo(o.getLicencePlateNumber());
}
}
|
package SimpleFactory01.exercise;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
public class XMLUtil {
private final static String PATH = "src\\SimpleFactory01\\exercise\\config.xml";
private final static String TAG_NAME = "shapeType";
public static String getShapeName() {
try {
//创建文档对象
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(new File(PATH));
//获取包图表类型的文本节点
NodeList n1 = document.getElementsByTagName(TAG_NAME);
Node classNode = n1.item(0).getFirstChild();
String shapeType = classNode.getNodeValue().trim();
return shapeType;
}catch (Exception e){
e.printStackTrace();
return null;
}
}
}
|
package kr.co.people_gram.app;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
public class MemberJoinStep5_Activity extends AppCompatActivity {
private ImageView sex_man, sex_woman;
private String sexType = "";
private LinearLayout nextLL;
private MemberData md;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_member_join_step5_);
Log.d("people_gram", "성별 실행");
md = new MemberData();
nextLL = (LinearLayout) findViewById(R.id.nextLL);
nextLL.setVisibility(View.INVISIBLE);
sex_man = (ImageView) findViewById(R.id.sex_man);
sex_woman = (ImageView) findViewById(R.id.sex_woman);
sex_man.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sex_man.setImageResource(R.drawable.sexman_on);
sex_woman.setImageResource(R.drawable.sexwoman_off);
sexType = "M";
md.set_sex("M");
nextLL.setVisibility(View.VISIBLE);
}
});
sex_woman.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sex_man.setImageResource(R.drawable.sexman_off);
sex_woman.setImageResource(R.drawable.sexwoman_on);
sexType = "F";
md.set_sex("F");
nextLL.setVisibility(View.VISIBLE);
}
});
nextLL.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(sexType.equals("")) {
Toast.makeText(MemberJoinStep5_Activity.this, "성별을 선택해주세요", Toast.LENGTH_LONG).show();
} else {
Intent intent = new Intent(MemberJoinStep5_Activity.this, MemberJoinStep6_Activity.class);
startActivity(intent);
overridePendingTransition(R.anim.speed_start_end, R.anim.speed_start_exit);
next_finish();
}
}
});
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
finish();
break;
default:
break;
}
return super.onKeyDown(keyCode, event);
}
public void next_finish()
{
super.finish();
}
public void finish()
{
super.finish();
overridePendingTransition(R.anim.slide_close_down_info, R.anim.slide_clode_up_info);
}
public void closeMember(View v)
{
finish();
}
}
|
package com.sinodynamic.hkgta.service.crm.backoffice.admin;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.sinodynamic.hkgta.dao.crm.HelperPassTypeDao;
import com.sinodynamic.hkgta.entity.crm.HelperPassType;
import com.sinodynamic.hkgta.service.ServiceBase;
import com.sinodynamic.hkgta.util.CommUtil;
import com.sinodynamic.hkgta.util.DateConvertUtil;
@Service
public class HelperPassTypeServiceImpl extends ServiceBase<HelperPassType>
implements HelperPassTypeService {
@Autowired
private HelperPassTypeDao helperPassTypeDao;
@Override
@Transactional
public void checkIfHelperPassTypeExpired() {
Date curDate = new Date();
Date yesDate = CommUtil.addDays(curDate, -1);
String paramDate = DateConvertUtil.getYMDFormatDate(yesDate);
List<HelperPassType> passTypes = helperPassTypeDao.getExpiryPassTypeByCurdate(paramDate);
if (passTypes != null && passTypes.size() > 0) {
for (HelperPassType passType : passTypes) {
passType.setStatus("EXP");
passType.setUpdateBy("ADMIN");
passType.setUpdateDate(curDate);
helperPassTypeDao.updatePassType(passType);
}
}
}
}
|
package ar.gob.ambiente.servicios.especiesforestales.managedBeans;
import ar.gob.ambiente.servicios.especiesforestales.entidades.AdminEntidad;
import ar.gob.ambiente.servicios.especiesforestales.entidades.Especie;
import ar.gob.ambiente.servicios.especiesforestales.entidades.Familia;
import ar.gob.ambiente.servicios.especiesforestales.entidades.Genero;
import ar.gob.ambiente.servicios.especiesforestales.entidades.Usuario;
import ar.gob.ambiente.servicios.especiesforestales.facades.EspecieFacade;
import ar.gob.ambiente.servicios.especiesforestales.facades.FamiliaFacade;
import ar.gob.ambiente.servicios.especiesforestales.facades.GeneroFacade;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import sacvefor.Especie_svf;
import sacvefor.Especie_svfFacade;
import sacvefor.Familia_svf;
import sacvefor.Familia_svfFacade;
import sacvefor.Genero_svf;
import sacvefor.Genero_svfFacade;
/**
* Temporal para importar las especies del SACVeFor
* @deprecated Ya utilizada para realizar la migración
* @author rincostante
*/
public class MbImport implements Serializable{
private Familia_svf familiaSvf;
private Genero_svf generoSvf;
private Especie_svf especieSvf;
private MbLogin login;
private Usuario usLogeado;
@EJB
private Familia_svfFacade familiaSvfFacade;
@EJB
private Genero_svfFacade generoSvfFacade;
@EJB
private Especie_svfFacade especieSvfFacade;
@EJB
private FamiliaFacade familiaFacade;
@EJB
private GeneroFacade generoFacade;
@EJB
private EspecieFacade especieFacade;
public MbImport() {
}
/**
* Método que se ejecuta luego de instanciada la clase e inicializa los datos del usuario
*/
@PostConstruct
public void init(){
ExternalContext ctx = FacesContext.getCurrentInstance().getExternalContext();
login = (MbLogin)ctx.getSessionMap().get("mbLogin");
if(login != null) usLogeado = login.getUsLogeado();
}
public void leerFammilias() throws IOException{
File f = new File("D:\\rincostante\\Mis documentos\\SACVeFor\\Desarrollo\\trazabilidad\\planificación\\diseño\\ESPECIES\\import\\familia.xlsx");
int fila = 0;
if(f.exists()){
try(FileInputStream fileInputStream = new FileInputStream(f)) {
// Instancio un libro de excel
XSSFWorkbook workBook = new XSSFWorkbook(fileInputStream);
// Obtengo la primera hoja del libro
XSSFSheet hssfSheet = workBook.getSheetAt(0);
// Levanto las filas de la hoja y las guardo en un iterator
Iterator rowIterator = hssfSheet.rowIterator();
// recorro las filas
while(rowIterator.hasNext()){
familiaSvf = new Familia_svf();
int i = 0;
// obtengo los datos de cada fila y por cada una instancio e inserto un tmpEst
XSSFRow hssfRow = (XSSFRow) rowIterator.next();
// instancio otro iterator para guardar las celdas de la fila
Iterator cellIterator = hssfRow.cellIterator();
while(cellIterator.hasNext()){
XSSFCell xssfCell = (XSSFCell) cellIterator.next();
String valor = xssfCell.toString();
switch(i){
case 0:
if(valor.indexOf(".") > 0){
familiaSvf.setId_svf(Integer.valueOf(valor.substring(0, valor.indexOf("."))));
}else{
familiaSvf.setId_svf(Integer.valueOf(valor));
}
break;
default:
familiaSvf.setNombre(valor);
break;
}
i += 1;
}
System.out.println(familiaSvf.getId_svf() + " | "
+ "" + familiaSvf.getNombre());
familiaSvfFacade.create(familiaSvf);
System.out.println("-----------------guardó " + fila + "--------------");
fila += 1;
}
}catch(Exception ex){
System.out.println(ex.getMessage());
}
}else{
System.out.println("No se encontró el archvivo familia.xlsx");
}
}
public void insertarFamilias() {
try{
// leo las familias importadas del SACVefor, no insertadas aún
List<Familia_svf> lstFamSvf = familiaSvfFacade.getNoInsertadas();
// recorro el listado y por cada una valido
for(Familia_svf famSvf : lstFamSvf){
// vrifico si existe la familia con el nombre de la leída
Familia fam = familiaFacade.getXNombre(famSvf.getNombre());
if(fam != null){
// si existe le pongo el flag esSacvefor en true y actualizo
fam.setEsSacvefor(true);
familiaFacade.edit(fam);
// actualizo el id_insertado en la Familia_svf
famSvf.setId_insertado(fam.getId());
familiaSvfFacade.edit(famSvf);
System.out.println("Se actualizó la familia " + famSvf.getNombre() + " en las dos tablas.");
}else{
// si no existe lo inserto
fam = new Familia();
Date date = new Date(System.currentTimeMillis());
AdminEntidad admEnt = new AdminEntidad();
admEnt.setFechaAlta(date);
admEnt.setHabilitado(true);
admEnt.setUsAlta(usLogeado);
fam.setAdminentidad(admEnt);
fam.setEsSacvefor(true);
fam.setNombre(famSvf.getNombre());
familiaFacade.create(fam);
// actualizo el id_insertado en la Familia_svf
famSvf.setId_insertado(fam.getId());
familiaSvfFacade.edit(famSvf);
System.out.println("Se insertó la familia " + famSvf.getNombre() + " y se actualizaron las dos tablas.");
}
}
}catch(Exception ex){
System.out.println("Hubo un error insertando Familias " + ex.getMessage());
}
}
public void leerGeneros(){
File f = new File("D:\\rincostante\\Mis documentos\\SACVeFor\\Desarrollo\\trazabilidad\\planificación\\diseño\\ESPECIES\\import\\genero.xlsx");
int fila = 0;
if(f.exists()){
try(FileInputStream fileInputStream = new FileInputStream(f)) {
// Instancio un libro de excel
XSSFWorkbook workBook = new XSSFWorkbook(fileInputStream);
// Obtengo la primera hoja del libro
XSSFSheet hssfSheet = workBook.getSheetAt(0);
// Levanto las filas de la hoja y las guardo en un iterator
Iterator rowIterator = hssfSheet.rowIterator();
// recorro las filas
while(rowIterator.hasNext()){
generoSvf = new Genero_svf();
int i = 0;
// obtengo los datos de cada fila y por cada una instancio e inserto un tmpEst
XSSFRow hssfRow = (XSSFRow) rowIterator.next();
// instancio otro iterator para guardar las celdas de la fila
Iterator cellIterator = hssfRow.cellIterator();
while(cellIterator.hasNext()){
XSSFCell xssfCell = (XSSFCell) cellIterator.next();
String valor = xssfCell.toString();
switch(i){
case 0:
if(valor.indexOf(".") > 0){
generoSvf.setId_svf(Integer.valueOf(valor.substring(0, valor.indexOf("."))));
}else{
generoSvf.setId_svf(Integer.valueOf(valor));
}
break;
case 1:
generoSvf.setNombre(valor);
break;
default:
if(valor.indexOf(".") > 0){
generoSvf.setId_familia_svf(Integer.valueOf(valor.substring(0, valor.indexOf("."))));
}else{
generoSvf.setId_familia_svf(Integer.valueOf(valor));
}
break;
}
i += 1;
}
System.out.println(generoSvf.getId_svf() + " | "
+ "" + generoSvf.getNombre());
// seteo la familia_svf
Familia_svf famSvf = familiaSvfFacade.getById_svf(generoSvf.getId_familia_svf());
generoSvf.setFamilia_svf(famSvf);
generoSvfFacade.create(generoSvf);
System.out.println("-----------------guardó " + fila + "--------------");
fila += 1;
}
}catch(Exception ex){
System.out.println(ex.getMessage());
}
}else{
System.out.println("No se encontró el archvivo genero.xlsx");
}
}
public void insertarGeneros(){
try{
// leo los géneros importados del SACVefor, no insertados aún
List<Genero_svf> lstGenSvf = generoSvfFacade.getNoInsertados();
// recorro el listado y por cada una valido
for(Genero_svf genSvf : lstGenSvf){
// vrifico si existe el Género con el nombre del leído
Genero gen = generoFacade.getXNombre(genSvf.getNombre());
if(gen != null){
// si existe le pongo el flag esSacvefor en true y actualizo
gen.setEsSacvefor(true);
generoFacade.edit(gen);
// actualizo el id_insertado en el Genero_svf
genSvf.setId_insertado(gen.getId());
generoSvfFacade.edit(genSvf);
System.out.println("Se actualizó el género " + genSvf.getNombre() + " en las dos tablas.");
}else{
// si no existe lo inserto
gen = new Genero();
Date date = new Date(System.currentTimeMillis());
AdminEntidad admEnt = new AdminEntidad();
admEnt.setFechaAlta(date);
admEnt.setHabilitado(true);
admEnt.setUsAlta(usLogeado);
// seteo el admin
gen.setAdminentidad(admEnt);
gen.setEsSacvefor(true);
gen.setNombre(genSvf.getNombre());
// busco la familia desde el id_insertado de la vinculada al género
Familia fam = familiaFacade.find(genSvf.getFamilia_svf().getId_insertado());
if(fam != null){
gen.setFamilia(fam);
generoFacade.create(gen);
}
// actualizo el id_insertado en la Familia_svf
if(gen.getId() != null){
genSvf.setId_insertado(gen.getId());
generoSvfFacade.edit(genSvf);
System.out.println("Se insertó el género " + genSvf.getNombre() + " y se actualizaron las dos tablas.");
}
}
}
}catch(Exception ex){
System.out.println("Hubo un error insertando Géneros " + ex.getMessage());
}
}
public void leerEspecies(){
File f = new File("D:\\rincostante\\Mis documentos\\SACVeFor\\Desarrollo\\trazabilidad\\planificación\\diseño\\ESPECIES\\import\\especie.xlsx");
int fila = 0;
if(f.exists()){
try(FileInputStream fileInputStream = new FileInputStream(f)) {
// Instancio un libro de excel
XSSFWorkbook workBook = new XSSFWorkbook(fileInputStream);
// Obtengo la primera hoja del libro
XSSFSheet hssfSheet = workBook.getSheetAt(0);
// Levanto las filas de la hoja y las guardo en un iterator
Iterator rowIterator = hssfSheet.rowIterator();
// recorro las filas
while(rowIterator.hasNext()){
especieSvf = new Especie_svf();
int i = 0;
// obtengo los datos de cada fila y por cada una instancio e inserto un tmpEst
XSSFRow hssfRow = (XSSFRow) rowIterator.next();
// instancio otro iterator para guardar las celdas de la fila
Iterator cellIterator = hssfRow.cellIterator();
while(cellIterator.hasNext()){
XSSFCell xssfCell = (XSSFCell) cellIterator.next();
String valor = xssfCell.toString();
switch(i){
case 0:
if(valor.indexOf(".") > 0){
especieSvf.setId_svf(Integer.valueOf(valor.substring(0, valor.indexOf("."))));
}else{
especieSvf.setId_svf(Integer.valueOf(valor));
}
break;
case 1:
especieSvf.setNombre_vulgar(valor);
break;
case 2:
especieSvf.setObs(valor);
break;
case 3:
especieSvf.setNombre(valor);
break;
default:
if(valor.indexOf(".") > 0){
especieSvf.setId_genero_svf(Integer.valueOf(valor.substring(0, valor.indexOf("."))));
}else{
especieSvf.setId_genero_svf(Integer.valueOf(valor));
}
break;
}
i += 1;
}
// seteo la familia_svf
Genero_svf genSvf = generoSvfFacade.getById_svf(especieSvf.getId_genero_svf());
especieSvf.setGenero_svf(genSvf);
System.out.println(especieSvf.getId_svf() + " | "
+ "" + especieSvf.getNombre());
especieSvfFacade.create(especieSvf);
System.out.println("-----------------guardó " + fila + "--------------");
fila += 1;
}
}catch(Exception ex){
System.out.println(ex.getMessage());
}
}else{
System.out.println("No se encontró el archvivo especie.xlsx");
}
}
public void insertarEspecies(){
try{
// leo las especies importados del SACVefor, no insertadas aún
List<Especie_svf> lstEspSvf = especieSvfFacade.getNoInsertadas();
// recorro el listado y por cada una valido
for(Especie_svf espSvf : lstEspSvf){
// vrifico si existe la especie con el nombre de la leída
Especie esp = especieFacade.getXNombre(espSvf.getNombre());
if(esp != null){
// si existe le pongo el flag esSacvefor en true y actualizo
esp.setEsSacvefor(true);
especieFacade.edit(esp);
// actualizo el id_insertado en el Genero_svf
espSvf.setId_insertado(esp.getId());
especieSvfFacade.edit(espSvf);
System.out.println("Se actualizó la especie " + espSvf.getNombre() + " en las dos tablas.");
}else{
// si no existe la inserto
esp = new Especie();
Date date = new Date(System.currentTimeMillis());
AdminEntidad admEnt = new AdminEntidad();
admEnt.setFechaAlta(date);
admEnt.setHabilitado(true);
admEnt.setUsAlta(usLogeado);
// seteo el admin
esp.setAdminentidad(admEnt);
esp.setEsSacvefor(true);
esp.setNombre(espSvf.getNombre());
// busco el género desde el id_insertado del vinculado a la especie
Genero gen = generoFacade.find(espSvf.getGenero_svf().getId_insertado());
if(gen != null){
esp.setGenero(gen);
especieFacade.create(esp);
}
// actualizo el id_insertado en el Genero_svf
if(esp.getId() != null){
espSvf.setId_insertado(esp.getId());
especieSvfFacade.edit(espSvf);
System.out.println("Se insertó la especie " + espSvf.getNombre() + " y se actualizaron las dos tablas.");
}
}
}
}catch(Exception ex){
System.out.println("Hubo un error insertando Especies " + ex.getMessage());
}
}
}
|
/*********************************************
* Android Nanodegree Program
* Project 0 - My App Portfolio
*
* Zach Rogers
* 7 June 2015
**********************************************/
package zachr.app.myappportfolio;
import android.app.Activity;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity
{
//UI Elements
private TextView welcomeText = null;
private Button project1Btn = null;
private Button project2Btn = null;
private Button project3Btn = null;
private Button project4Btn = null;
private Button project5Btn = null;
private Button project6Btn = null;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Setup UI Elements
welcomeText = (TextView) findViewById(R.id.welcome);
project1Btn = (Button) findViewById(R.id.button);
project2Btn = (Button) findViewById(R.id.button2);
project3Btn = (Button) findViewById(R.id.button3);
project4Btn = (Button) findViewById(R.id.button4);
project5Btn = (Button) findViewById(R.id.button5);
project6Btn = (Button) findViewById(R.id.button6);
//Set the typeface font for our welcome message textview
Typeface typeface = Typeface.createFromAsset(getAssets(), "Roboto-Regular.ttf");
welcomeText.setTypeface(typeface);
//Setup onClickListeners for project buttons
project1Btn.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
Toast.makeText(getApplicationContext(), "This will launch my Spotify Streamer app!", Toast.LENGTH_SHORT).show();
}
});
project2Btn.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
Toast.makeText(getApplicationContext(), "This will launch my Football Scores app!", Toast.LENGTH_SHORT).show();
}
});
project3Btn.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
Toast.makeText(getApplicationContext(), "This will launch my Library App!", Toast.LENGTH_SHORT).show();
}
});
project4Btn.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
Toast.makeText(getApplicationContext(), "This will launch my Build It Bigger app!", Toast.LENGTH_SHORT).show();
}
});
project5Btn.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
Toast.makeText(getApplicationContext(), "This will launch my XYZ Reader app!", Toast.LENGTH_SHORT).show();
}
});
project6Btn.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
Toast.makeText(getApplicationContext(), "This will launch my Capstone Project app!", Toast.LENGTH_SHORT).show();
}
});
}
@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.action_settings)
{
return true;
}
return super.onOptionsItemSelected(item);
}
}
|
package com.pce.BookMeTutor.Model.Dto.Requests;
public class AddressRequest {
private String line_1;
private String line_2;
private String city;
private String pincode;
public String getLine_1() {
return line_1;
}
public void setLine_1(String line_1) {
this.line_1 = line_1;
}
public String getLine_2() {
return line_2;
}
public void setLine_2(String line_2) {
this.line_2 = line_2;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getPincode() {
return pincode;
}
public void setPincode(String pincode) {
this.pincode = pincode;
}
public AddressRequest(String line_1, String line_2, String city,
String pincode) {
super();
this.line_1 = line_1;
this.line_2 = line_2;
this.city = city;
this.pincode = pincode;
}
public AddressRequest() {
// TODO Auto-generated constructor stub
}
}
|
import java.util.*;
public class Fabonaci
{
public static void main(String args[])
{
Scanner sc =new Scanner(System.in);
System.out.print("Enter the last term ");
int n= sc.nextInt();
int a=0;
int b=1;
int series =0;
for(int i=0;i<n;i++){
System.out.print(a+" ");
series =(a+b);
a=b;
b=series;
}
}
}
|
package com.karya.bean;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.NotEmpty;
public class ItemStatusBean {
private int itemstId;
@NotNull
@NotEmpty(message="please select item")
private String itemCode;
@NotNull
@NotEmpty(message="please select status")
private String status;
@NotNull
@NotEmpty(message="please select itemGroup")
private String itemGroup;
public int getItemstId() {
return itemstId;
}
public void setItemstId(int itemstId) {
this.itemstId = itemstId;
}
public String getItemCode() {
return itemCode;
}
public void setItemCode(String itemCode) {
this.itemCode = itemCode;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getItemGroup() {
return itemGroup;
}
public void setItemGroup(String itemGroup) {
this.itemGroup = itemGroup;
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.csci360.alarmclock;
/**
*
* @author baldy
*/
public class AlarmView {
public void printAlarmDetails(String time, Boolean playsAlert){
System.out.println("Alarm will play @ " + time);
System.out.println("The alarm will sound: " + playsAlert);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.