text
stringlengths
10
2.72M
package 第三次Java作业; public class work5_21 { public static void main(String[] args) { } }
package com.delrima.webgene.client.event; import com.delrima.webgene.client.common.Command; import com.delrima.webgene.client.event.handler.RetrieveMemberLookupResultEventHandler; import com.delrima.webgene.client.result.MemberLookupResult; import com.google.gwt.event.shared.GwtEvent; /** * <code><B>MemberChangeEvent</code></b> * <p> * Event associated with server messages data being present in the JSON variable "serverMessages" * </p> * * @author bhavesh.thakker@ihg.com * @since Jul 22, 2009 * */ public class RetrieveMemberLookupResultEvent extends GwtEvent<RetrieveMemberLookupResultEventHandler> { /** * Event type for server message events. Represents the meta-data associated with this event. */ private static final GwtEvent.Type<RetrieveMemberLookupResultEventHandler> TYPE = new GwtEvent.Type<RetrieveMemberLookupResultEventHandler>(); /** * Gets the event type associated with server messages events. * * @return the handler type */ public static GwtEvent.Type<RetrieveMemberLookupResultEventHandler> getType() { return TYPE; } /** * If true, server-side processing is ignored. Indicates this event is being triggered for client-side processing only */ private final String query; /** * Execute this command after the results are retrieved */ private final Command<MemberLookupResult> command; public RetrieveMemberLookupResultEvent(String query, Command<MemberLookupResult> command) { super(); this.query = query; this.command = command; } /** * @see com.google.gwt.event.shared.GwtEvent#dispatch(com.google.gwt.event.shared.EventHandler) */ @Override protected void dispatch(RetrieveMemberLookupResultEventHandler handler) { handler.onMemberLookupResultRetrieveRequest(this); } /** * @see com.google.gwt.event.shared.GwtEvent#getAssociatedType() */ @Override public com.google.gwt.event.shared.GwtEvent.Type<RetrieveMemberLookupResultEventHandler> getAssociatedType() { return TYPE; } /** * @return the query */ public String getQuery() { return query; } public Command<MemberLookupResult> getCommand() { return command; } }
public class NoRightTurnDiv2 { public int[] findPath(int[] x, int[] y) { int startX = Integer.MAX_VALUE; int startY = Integer.MAX_VALUE; int point = -1; for(int i = 0; i < x.length; ++i) { if(x[i] < startX) { startX = x[i]; startY = y[i]; point = i; } else if(x[i] == startX) { if(y[i] < startY) { startY = y[i]; point = i; } } } int[] result = new int[x.length]; boolean[] used = new boolean[x.length]; result[0] = point; used[point] = true; for(int i = 1; i < result.length; ++i) { int prevX = x[point]; int prevY = y[point]; point = -1; for(int j = 0; j < x.length && point == -1; ++j) { if(!used[j]) { boolean possible = true; for(int k = 0; k < x.length; ++k) { if(!used[k] && j != k) { if(area(prevX, prevY, x[j], y[j], x[k], y[k]) < 0) { possible = false; } } } if(possible) { point = j; } } } used[point] = true; result[i] = point; } return result; } public long area(long x1, long y1, long x2, long y2, long x3, long y3) { return (x2 - x1) * (y3 - y1) - (x3 - x1) * (y2 - y1); } }
package acueducto.domain; import java.util.*; import java.io.Serializable; /** * * @author Karla Salas M. | Leonardo Sanchez J. */ public class Lectura implements Serializable { private int id; private String fecha; private String medicion; private String responsable; private int idMedidor; /** * Constructor de la clase Lectura. */ public Lectura() { } /** * Constructor de la clase Lectura. * @param id * @param fecha * @param medicion * @param responsable * @param idMedidor */ public Lectura(int id, String fecha, String medicion, String responsable, int idMedidor) { this.id = id; this.fecha = fecha; this.medicion = medicion; this.responsable = responsable; this.idMedidor = idMedidor; } /** * Metodo accesor a id. * @return id */ public int getId() { return id; } /** * Metodo modificador de id * @param id */ public void setId(int id) { this.id = id; } /** * Metodo accesor a fecha. * @return fecha */ public String getFecha() { return fecha; } /** * M�todo modificador de fecha * @param fecha */ public void setFecha(String fecha) { this.fecha = fecha; } /** * M�todo accesor a medicion. * @return medicion */ public String getMedicion() { return medicion; } /** * M�todo modificador de medicion * @param medicion */ public void setMedicion(String medicion) { this.medicion = medicion; } /** * M�todo accesor a responsable. * @return responsable */ public String getResponsable() { return responsable; } /** * M�todo modificador de responsable * @param responsable */ public void setResponsable(String responsable) { this.responsable = responsable; } /** * M�todo accesor a idMedidor. * @return idMedidor */ public int getIdMedidor() { return idMedidor; } /** * M�todo modificador de idMedidor * @param idMedidor */ public void setIdMedidor(int idMedidor) { this.idMedidor = idMedidor; } }
package com.apap.igd.model; import java.util.ArrayList; import java.util.List; public class JadwalJagaContainerModel { List<JadwalJagaDokterModel> jadwalContainer; public JadwalJagaContainerModel() { super(); this.jadwalContainer = new ArrayList<JadwalJagaDokterModel>(); } public List<JadwalJagaDokterModel> getJadwalContainer() { return jadwalContainer; } public void setJadwalContainer(List<JadwalJagaDokterModel> jadwalContainer) { this.jadwalContainer = jadwalContainer; } public void addJadwal(JadwalJagaDokterModel jadwal) { this.jadwalContainer.add(jadwal); } public void removeJadwal(JadwalJagaDokterModel jadwal) { this.jadwalContainer.remove(jadwal); } }
package Day3.swing; import Day3.Computers; import java.util.ArrayList; import java.util.List; /** * Created by student on 06-May-16. */ public class Supplier { private String name; private final List<Computers> products = new ArrayList<>(); public Supplier(String name){this.name = name ;} public List<Computers> getProducts(){ return products;} public String getName(){return name;} @Override public String toString(){return "Supplier { Name : " + name + "Product : " + products;} }
package com.github.galimru.telegram.objects; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import java.io.Serializable; @JsonInclude(JsonInclude.Include.NON_NULL) public class MaskPosition implements Serializable { private static final long serialVersionUID = 8759623172272812930L; private static final String POINT_FIELD = "point"; private static final String X_SHIFT_FIELD = "x_shift"; private static final String Y_SHIFT_FIELD = "y_shift"; private static final String SCALE_FIELD = "scale"; @JsonProperty(value = POINT_FIELD) private String point; @JsonProperty(value = X_SHIFT_FIELD) private Float xShift; @JsonProperty(value = Y_SHIFT_FIELD) private Float yShift; @JsonProperty(value = SCALE_FIELD) private Float scale; public String getPoint() { return point; } public MaskPosition setPoint(String point) { this.point = point; return this; } public Float getxShift() { return xShift; } public MaskPosition setxShift(Float xShift) { this.xShift = xShift; return this; } public Float getyShift() { return yShift; } public MaskPosition setyShift(Float yShift) { this.yShift = yShift; return this; } public Float getScale() { return scale; } public MaskPosition setScale(Float scale) { this.scale = scale; return this; } @Override public String toString() { return "MaskPosition{" + "point='" + point + '\'' + ", xShift=" + xShift + ", yShift=" + yShift + ", scale=" + scale + '}'; } }
package dataservice; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; public class DataDaoImpl implements DataDao{ @Override public String retrieveName(int id) { Connection conn = null; Statement stmt = null; ResultSet rs = null; String name = null; try{ ConnectionFactory cf = new ConnectionFactory(); conn = cf.getConnection(); stmt = conn.createStatement(); //Retrieve an existing account rs = stmt.executeQuery("SELECT * FROM employee WHERE id= " + id); while (rs.next()){ name = rs.getString(2) + " " + rs.getString(3); } }catch(Exception e){ e.printStackTrace(); }finally{ try{ rs.close(); conn.close(); stmt.close(); }catch(Exception e){ e.printStackTrace(); } } return name; } }
package helpers; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; public class PostToGetRequestWrapper extends HttpServletRequestWrapper { public PostToGetRequestWrapper(HttpServletRequest request) { super(request); } public String getMethod(){ return "GET"; } }
package com.ymall.controller.admin; import com.ymall.annotation.AdminReqired; import com.ymall.common.Const; import com.ymall.common.ServerResponse; import com.ymall.common.exception.IllegalException; import com.ymall.pojo.Product; import com.ymall.service.ProductService; import com.ymall.vo.PageModel; import com.ymall.vo.ProductDetailVo; import com.ymall.vo.ProductListVo; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; /** * Created by zc on 2017/6/14. */ @RestController @RequestMapping("/admin/product") @Api(value="ProductMangerController",tags="商品管理") public class ProductMangerController { @Autowired private ProductService productService; //添加商品 @AdminReqired @RequestMapping(value = "product", method = RequestMethod.POST) @ApiOperation(value="addProduct",notes="添加商品") public ServerResponse addProduct( @ApiParam(name="product",value="product:{id:商品ID,categoryId:分类ID,name:名称.......}") @Valid Product product) throws IllegalException { return productService. saveOrUpdateProduct(product); } //修改商品信息 @AdminReqired @RequestMapping(value = "product/{productId}", method = RequestMethod.PUT) @ApiOperation(value="updateProduct",notes="修改商品") public ServerResponse updateProduct(@PathVariable Integer productId,@Valid Product product) throws IllegalException { product.setId(productId); return productService.saveOrUpdateProduct(product); } //删除商品信息 @AdminReqired @RequestMapping(value = "product/{productId}", method = RequestMethod.DELETE) @ApiOperation(value="deleteProduct",notes="删除商品") public ServerResponse deleteProduct(@PathVariable Integer productId) throws IllegalException { return productService.setSaleStatus(productId, Const.ProductStatusEnum.DELETE_SALE.getCode()); } //修改商品状态 @AdminReqired @RequestMapping(value = "sale_status/{productId}", method = RequestMethod.PUT) @ApiOperation(value="setSaleStatus",notes="修改商品状态") public ServerResponse setSaleStatus(@PathVariable Integer productId, @RequestParam Integer status) throws IllegalException { return productService.setSaleStatus(productId,status); } //获取所有商品详情 @AdminReqired @RequestMapping(value = "product_detail/{productId}",method = RequestMethod.GET) @ApiOperation(value="getProductDetail",notes="获取商品详情") public ServerResponse<ProductDetailVo> getProductDetail(@PathVariable Integer productId) throws IllegalException { return productService.getProductDetail(productId,null); } @AdminReqired @RequestMapping(value = "product_list",method = RequestMethod.GET) //获取所有商品列表(带分类与搜索) @ApiOperation(value="getProductList",notes="获取商品列表") public ServerResponse<PageModel<ProductListVo>> getProductList( @RequestParam(required = false) String keyword, @RequestParam(required = false) Integer productId, @RequestParam(required = false) Integer categoryId, @RequestParam(defaultValue = "id_asc") String orderBy, @Valid PageModel pageModel) throws IllegalException { int pageNum=pageModel.getPageNum(); int limit=pageModel.getLimit(); return productService.getProductList( null, keyword, productId, categoryId, orderBy, pageNum, limit); } }
/** * 湖北安式软件有限公司 * Hubei Anssy Software Co., Ltd. * FILENAME : ServiceInfoDao.java * PACKAGE : com.anssy.venturebar.service.dao * CREATE DATE : 2016-8-10 * AUTHOR : make it * MODIFIED BY : * DESCRIPTION : */ package com.anssy.venturebar.service.dao; import com.anssy.venturebar.service.entity.ServiceInfoEntity; import com.anssy.venturebar.service.vo.FieldVo; import com.anssy.venturebar.service.vo.GPSVo; import com.anssy.venturebar.service.vo.PvVo; import com.anssy.webcore.vo.CollectVo; import com.anssy.webcore.vo.MyVo; import com.anssy.webcore.vo.ReferralsVo; import org.springframework.stereotype.Repository; import java.util.List; /** * @author make it * @version SVN #V1# #2016-8-10# * 服务_服务信息 */ @Repository("serviceInfoDao") public interface ServiceInfoDao { /** * 添加服务信息 */ int insertServiceInfo(ServiceInfoEntity info); /** * 修改服务信息 */ int updateServiceInfo(ServiceInfoEntity info); /** * 获取主键 */ Long findId(); /** * 通过服务ID查询服务信息 */ ServiceInfoEntity findServiceInfoById(Long id); /** * 修改浏览量 */ int updatePV(Long id); /** * 点赞 */ int updatePraise(Long id); /** * 修改权重 */ int updateWeight(Long id, Long weight); /** * 删除服务信息 */ int deleteServiceInfo(Long id); /** * 按GPS进行附近搜索 */ List<ServiceInfoEntity> findListByGPS(GPSVo vo); /** * 按服务类型搜索 */ List<ServiceInfoEntity> findListByType(FieldVo vo); /** * 智能搜索 */ List<ServiceInfoEntity> findListByPv(PvVo vo); /** * 推荐服务 */ List<ServiceInfoEntity> referrals(ReferralsVo vo); /** * 我发布的信息 */ List<ServiceInfoEntity> findMyPublish(MyVo vo); /** * 查看我的收藏 */ List<ServiceInfoEntity> findCollect(CollectVo vo); }
import java.io.DataInputStream; import java.io.PrintStream; import java.io.IOException; import java.net.Socket; import java.util.ArrayList; import java.util.HashMap; import java.net.ServerSocket; public class Serwer { private static ServerSocket serverSocket = null; private static Socket clientSocket = null; private static final int maxClientsCount = 20;//MAKSYMALNA ILOSC ZDAJACYCH private static final clientThread[] threads = new clientThread[maxClientsCount]; public static void main(String args[]) { int portNumber = 2222; if (args.length < 1) { System.out.println("Wielowatkowosc egzamin prawo jazdy. Numer portu wynosi =" + portNumber); } else { portNumber = Integer.valueOf(args[0]).intValue(); } try { serverSocket = new ServerSocket(portNumber);//proba otwarcia socket serwera dla potu 2222 } catch (IOException e) { System.out.println(e); } //tworzymy klienckiego socketa dla kazdego zdajacego i przypisujemy nowy watek while (true) { try { clientSocket = serverSocket.accept(); int i = 0; for (i = 0; i < maxClientsCount; i++) { if (threads[i] == null) { (threads[i] = new clientThread(clientSocket, threads)).start(); break; } } if (i == maxClientsCount) { PrintStream os = new PrintStream(clientSocket.getOutputStream()); os.println("Limit zdajacych"); os.close(); clientSocket.close(); } } catch (IOException e) { System.out.println(e); } } } } //Klient otwiera strumienie wejscia/wyjscia, konkretny klient jest pytany o imie, //jest w stanie informowac innych klientow o dolaczeniu nowego klienta, serwer //zbiera dane i moze rozeslac odebrane dane do wszystkich innych. Gdy klient //sie wylogowuje to watek ten moze wszystkich informowac o tym fakcie class clientThread extends Thread { static ArrayList<String> ZDAJACY = new ArrayList<String>(); //Nazwy zdajacych static HashMap<String, Integer> PUNKTY = new HashMap<String, Integer>(); //Przypisanie punktow po kazdym pytaniu dla konkretnego zdajacego static HashMap<String, Integer> ILEPYTAN = new HashMap<String, Integer>(); //Ile pytan minelo static HashMap<String, ArrayList<Integer>> BEZPOWTORZEN = new HashMap<String, ArrayList<Integer>>(); //Ile pytan minelo private DataInputStream is = null; private PrintStream os = null; private Socket clientSocket = null; private final clientThread[] threads; private int maxClientsCount; public clientThread(Socket clientSocket, clientThread[] threads) //konstruktor { this.clientSocket = clientSocket; this.threads = threads; maxClientsCount = threads.length; } public void run() { int maxClientsCount = this.maxClientsCount; clientThread[] threads = this.threads; //File f = new File(); Database db = new Database(); Users u = new Users(); Integer zmienna1, zmienna2; try { //tworzenie strumienia wejscia/wyjscia dla danego klienta is = new DataInputStream(clientSocket.getInputStream()); os = new PrintStream(clientSocket.getOutputStream()); //os.println("Podaj imie i nazwisko."); String name = is.readLine().trim(); //os.println(u.UserInit(name, ZDAJACY,PUNKTY, ILEPYTAN, BEZPOWTORZEN)); u.UserInit(name, ZDAJACY,PUNKTY, ILEPYTAN, BEZPOWTORZEN); os.println(db.GetDataFromDB(name, BEZPOWTORZEN)); BEZPOWTORZEN.get(name).add(db.GetId()); for(int j = 0; j < ZDAJACY.size(); j++) { System.out.println(ZDAJACY.get(j)); zmienna1 = PUNKTY.get(ZDAJACY.get(j)); System.out.print(zmienna1); System.out.println(" " + j + ZDAJACY.get(j)); } for (int i = 0; i < maxClientsCount; i++) { if (threads[i] != null && threads[i] != this) { System.out.println("Zdajacy " + name + " zalogowal sie"); } } while (true) { String line = is.readLine(); System.out.println(line + "\n" + name); System.out.println("Odpowiedz z baz danych: " + db.GetAns()); if(line.equals(db.GetAns())) { zmienna1 = PUNKTY.get(name); zmienna2 = ILEPYTAN.get(name); PUNKTY.replace(name, zmienna1+1); ILEPYTAN.replace(name, zmienna2+1); } else { zmienna1 = ILEPYTAN.get(name); ILEPYTAN.replace(name, zmienna1+1); } if(line.startsWith("/SKONCZ") || ILEPYTAN.get(name) == 5) { u.IfPassed(name, PUNKTY, ILEPYTAN); String sepName = ""; String surname = ""; int flag = 0, counter = 0; for(int i = 0; i < name.length(); i++) { if(name.charAt(i) == ' ') { flag++; } if(flag == 0) { sepName += name.charAt(i); } else { surname += name.charAt(i); } } surname = surname.trim() + " "; sepName = sepName.trim() + " "; System.out.println("Imie: " + sepName + " i nazwisko: " + surname); if(u.RetWynik() > 60) { os.println("Gratulacje! Zdales egzamin z wynikiem " + u.RetWynik() +"%"); db.WriteToDB(sepName, surname, u.RetWynik(), true); } else { os.println("Niestety uzyskales " + u.RetWynik() + "% a tym samym nie zaliczyles egzaminu"); db.WriteToDB(sepName, surname, u.RetWynik(), false); } break; } os.println(db.GetDataFromDB(name, BEZPOWTORZEN)); // os.println(db.GetAns()); System.out.println("*********************"); for(int j = 0; j < ZDAJACY.size(); j++) { zmienna1 = PUNKTY.get(ZDAJACY.get(j)); System.out.print(zmienna1 + " " + ILEPYTAN.get(ZDAJACY.get(j))); System.out.println(" " + ZDAJACY.get(j)); } System.out.print("**********************"); for (int i = 0; i < maxClientsCount; i++) { if (threads[i] != null) { //threads[i].os.println("<" + name + ": " + line); zmienna1 = PUNKTY.get(ZDAJACY.get(i)); //threads[i].os.println(zmienna1); } } } for (int i = 0; i < maxClientsCount; i++) { if (threads[i] != null && threads[i] != this) { threads[i].os.println("***Uzytkownik " + name + " zakonczyl test ***"); } } //os.println("*** Koniec " + name + " ***"); //Ustawienie null dla obecnego watku tak by nowy klient mogl byc //zaakceptowany przez serwer for (int i = 0; i < maxClientsCount; i++) { if (threads[i] == this) { threads[i] = null; } } //Zamkniecie strumienia wejscia/wyjscia oraz socketu is.close(); os.close(); clientSocket.close(); } catch (IOException e) { } } }
package com.example.mycalorietracker; import android.util.Log; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.io.PrintWriter; import java.net.HttpURLConnection; import java.net.URL; import java.util.Scanner; public class RestClient { private static final String BASE_URL = "http://118.139.93.9:8080/CalorieTracker/webresources/"; public static String checkusercredentials(String username,String passwordhash) { final String methodPath = "restcalorietracker.credential/checkCredentials/" + username +"/"+passwordhash; //initialise URL url = null; HttpURLConnection conn = null; String textResult = ""; //Making HTTP request try { url = new URL(BASE_URL + methodPath); //open the connection conn = (HttpURLConnection) url.openConnection(); //set the timeout conn.setReadTimeout(10000); conn.setConnectTimeout(15000); //set the connection method to GET conn.setRequestMethod("GET"); //add http headers to set your response type to json conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Accept", "application/json"); //Read the response Scanner inStream = new Scanner(conn.getInputStream()); while (inStream.hasNextLine()) { textResult += inStream.nextLine(); } } catch (Exception e) { e.printStackTrace(); } finally { conn.disconnect(); } return textResult; } public static String checkUsername(String username) { final String methodPath = "restcalorietracker.credential/findByUsername/" + username ; //initialise URL url = null; HttpURLConnection conn = null; String textResult = ""; //Making HTTP request try { url = new URL(BASE_URL + methodPath); //open the connection conn = (HttpURLConnection) url.openConnection(); //set the timeout conn.setReadTimeout(10000); conn.setConnectTimeout(15000); //set the connection method to GET conn.setRequestMethod("GET"); //add http headers to set your response type to json conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Accept", "application/json"); //Read the response Scanner inStream = new Scanner(conn.getInputStream()); while (inStream.hasNextLine()) { textResult += inStream.nextLine(); } } catch (Exception e) { e.printStackTrace(); } finally { conn.disconnect(); } return textResult; } public static String countRows() { final String methodPath = "restcalorietracker.credential/count"; //initialise URL url = null; HttpURLConnection conn = null; String textResult = ""; //Making HTTP request try { url = new URL(BASE_URL + methodPath); //open the connection conn = (HttpURLConnection) url.openConnection(); //set the timeout conn.setReadTimeout(10000); conn.setConnectTimeout(15000); //set the connection method to GET conn.setRequestMethod("GET"); //add http headers to set your response type to json conn.setRequestProperty("Content-Type", "text/plain"); conn.setRequestProperty("Accept", "text/plain"); //Read the response Scanner inStream = new Scanner(conn.getInputStream()); while (inStream.hasNextLine()) { textResult += inStream.nextLine(); } } catch (Exception e) { e.printStackTrace(); } finally { conn.disconnect(); } return textResult; } //to post to Credential public static void createCredential(Credential credential){ //initialise URL url = null; HttpURLConnection conn = null; final String methodPath="restcalorietracker.credential/"; try { Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX").create(); String stringReportJson = gson.toJson(credential); url = new URL(BASE_URL + methodPath); //open the connection conn = (HttpURLConnection) url.openConnection(); //set the timeout conn.setReadTimeout(10000); conn.setConnectTimeout(15000); //set the connection method to POST conn.setRequestMethod("POST"); //set the output to true conn.setDoOutput(true); //set length of the data you want to send conn.setFixedLengthStreamingMode(stringReportJson.getBytes().length); //add HTTP headers conn.setRequestProperty("Content-Type", "application/json"); //Send the POST out PrintWriter out= new PrintWriter(conn.getOutputStream()); out.print(stringReportJson); out.close(); Scanner scanner = new Scanner(conn.getInputStream()); while (scanner.hasNext()) { } Log.i("error",new Integer(conn.getResponseCode()).toString()); } catch (Exception e) { e.printStackTrace(); } finally { conn.disconnect(); } } public static void createUser(Users users){ //initialise URL url = null; HttpURLConnection conn = null; final String methodPath="restcalorietracker.users/"; try { Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX").create(); String stringReportJson = gson.toJson(users); url = new URL(BASE_URL + methodPath); //open the connection conn = (HttpURLConnection) url.openConnection(); //set the timeout conn.setReadTimeout(10000); conn.setConnectTimeout(15000); //set the connection method to POST conn.setRequestMethod("POST"); //set the output to true conn.setDoOutput(true); //set length of the data you want to send conn.setFixedLengthStreamingMode(stringReportJson.getBytes().length); //add HTTP headers conn.setRequestProperty("Content-Type", "application/json"); //Send the POST out PrintWriter out= new PrintWriter(conn.getOutputStream()); out.print(stringReportJson); out.close(); Scanner scanner = new Scanner(conn.getInputStream()); while (scanner.hasNext()) { } Log.i("error",new Integer(conn.getResponseCode()).toString()); } catch (Exception e) { e.printStackTrace(); } finally { conn.disconnect(); } } public static String getFoodByCategory(String category) { final String methodPath = "restcalorietracker.food/findByCategory/" + category ; //initialise URL url = null; HttpURLConnection conn = null; String textResult = ""; //Making HTTP request try { url = new URL(BASE_URL + methodPath); //open the connection conn = (HttpURLConnection) url.openConnection(); //set the timeout conn.setReadTimeout(10000); conn.setConnectTimeout(15000); //set the connection method to GET conn.setRequestMethod("GET"); //add http headers to set your response type to json conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Accept", "application/json"); //Read the response Scanner inStream = new Scanner(conn.getInputStream()); while (inStream.hasNextLine()) { textResult += inStream.nextLine(); } } catch (Exception e) { e.printStackTrace(); } finally { conn.disconnect(); } return textResult; } public static String countConsumptionRows() { final String methodPath = "restcalorietracker.consumption/count"; //initialise URL url = null; HttpURLConnection conn = null; String textResult = ""; //Making HTTP request try { url = new URL(BASE_URL + methodPath); //open the connection conn = (HttpURLConnection) url.openConnection(); //set the timeout conn.setReadTimeout(10000); conn.setConnectTimeout(15000); //set the connection method to GET conn.setRequestMethod("GET"); //add http headers to set your response type to json conn.setRequestProperty("Content-Type", "text/plain"); conn.setRequestProperty("Accept", "text/plain"); //Read the response Scanner inStream = new Scanner(conn.getInputStream()); while (inStream.hasNextLine()) { textResult += inStream.nextLine(); } } catch (Exception e) { e.printStackTrace(); } finally { conn.disconnect(); } return textResult; } public static String countFoodRows() { final String methodPath = "restcalorietracker.food/count"; //initialise URL url = null; HttpURLConnection conn = null; String textResult = ""; //Making HTTP request try { url = new URL(BASE_URL + methodPath); //open the connection conn = (HttpURLConnection) url.openConnection(); //set the timeout conn.setReadTimeout(10000); conn.setConnectTimeout(15000); //set the connection method to GET conn.setRequestMethod("GET"); //add http headers to set your response type to json conn.setRequestProperty("Content-Type", "text/plain"); conn.setRequestProperty("Accept", "text/plain"); //Read the response Scanner inStream = new Scanner(conn.getInputStream()); while (inStream.hasNextLine()) { textResult += inStream.nextLine(); } } catch (Exception e) { e.printStackTrace(); } finally { conn.disconnect(); } return textResult; } }
package com.yedam.KimSuho.extendPkg; public class Man { String name; String company; String major; Man(){ } Man(String name){ this.name = name; } public void tellYourName() { System.out.println("이름: " + name); } }
package classholder; import java.util.Comparator; import android.net.Uri; public class ClassHolderOne { public String NAME; public Uri URI; public ClassHolderOne(String name, Uri uri) { NAME = name; URI = uri; } }
package me.pixka; import java.io.IOException; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.Date; import org.apache.http.client.ClientProtocolException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.PinState; import com.pi4j.io.gpio.RaspiPin; import me.pixka.c.Ds18b20; import me.pixka.c.Font; import me.pixka.c.HttpControl; import me.pixka.c.Led; import me.pixka.c.PiDevice; import me.pixka.data.ISODateAdapter; import me.pixka.device.c.DeviceControl; import me.pixka.device.c.DeviceconfigControl; import me.pixka.device.c.DeviceconfigUtil; import me.pixka.device.d.Device; import me.pixka.device.d.Deviceconfig; /** * ใช้สำหรับ ส่ง ค่า ความร้อน ไปยัง service * * @author kykub * */ @Component public class ReaddsTask { @Autowired private Ds18b20 ds; @Autowired private HttpControl http; @Autowired private PiDevice pi; @Autowired private DeviceconfigControl dc; @Autowired private DeviceControl dic; @Autowired private DeviceconfigUtil dcfu; private String url = "http://61.19.255.23:3333/getdeviceconfigmac/"; private Deviceconfig deviceconfig; private static Gson g = new GsonBuilder().registerTypeAdapter(Date.class, new ISODateAdapter()).create(); private BigDecimal def = new BigDecimal("95.0"); private GpioController gpio = null; // private BigDecimal data = BigDecimal.ZERO; // private BigDecimal last = BigDecimal.ZERO; private Deviceconfig currentconfig = null; private GpioPinDigitalOutput pin0; private GpioPinDigitalOutput pin1; public ReaddsTask() { // pin.high(); // gpio.shutdown(); } public void setup() { try { gpio = GpioFactory.getInstance(); pin0 = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_00, "MyDelay0", PinState.HIGH); pin1 = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_01, "MyDelay1", PinState.HIGH); pin0.setShutdownOptions(true, PinState.HIGH); pin1.setShutdownOptions(true, PinState.HIGH); System.out.println("Start Thread"); } catch (Exception e) { e.printStackTrace(); } } public BigDecimal read() { BigDecimal value = null; try { value = ds.read(); } catch (Exception e) { e.printStackTrace(); } return value; } @Scheduled(fixedDelay = 5000) public void check() { System.out.println("check "); BigDecimal value = read(); if (value == null) return; // อ่านค่าไม่ได้ก็ออกเลย if (deviceconfig == null) {// ไม่มี config ให้ใช้ 95องค์ศา System.out.println("Not found config check with default " + def); if (checkvalue(value, def) > 0) { // ถ้ามากกว่า open(); } else close(); } else { // System.out.println("Have config:" + deviceconfig); BigDecimal ht = deviceconfig.getHt(); System.out.println("HT " + ht); if (ht.signum() != 0) if (checkvalue(value, ht) > 0) { open(); } else { close(); } } } @Scheduled(fixedRate = 5000) public void load() { deviceconfig = dcfu.loadfromhttp(url, pi.wifi()); if (deviceconfig == null) { deviceconfig = dcfu.loadfromdevice(); } else { deviceconfig.setRefid(deviceconfig.getId()); } if (deviceconfig == null && currentconfig == null) { System.out.println("Not have config"); return;// not have config } if (currentconfig == null) { currentconfig = deviceconfig; } else {// current config ไม่เท่ากับ null Long crefid = currentconfig.getRefid(); Long refid = deviceconfig.getId(); if (crefid.intValue() != refid.intValue()) {// new config currentconfig = deviceconfig; dcfu.saveConfigtoDevice(currentconfig); } } } public int checkvalue(BigDecimal s, BigDecimal e) { System.out.println("value for check:" + s + " " + e); return s.compareTo(e); } /** * ปิดน้ำ */ public void close() { System.out.println("close"); if (pin0 == null) { setup(); } pin0.high(); pin1.high(); } /** * เปิดน้ำ */ public void open() { System.out.println("open"); if (pin0 == null) { setup(); } pin1.low(); pin0.low(); } /* * @Scheduled(fixedRate = 5000) * * public Deviceconfig loadconfig() { System.out.println("load config "); * Deviceconfig dfs = null; try { dfs = dcfu.loadfromhttp(url, pi.wifi()); } * catch (IOException e) { } * * if (dfs != null) { // ถ้า load มาจาก Server ได้แล้วเทียบกับ * System.out.println("config load from server "); * * if (currentconfig != null) { * * Long refid = currentconfig.getRefid(); if (refid != null && * !refid.equals(dfs.getId())) { deviceconfig = dfs; currentconfig = dfs; * dcfu.saveConfigtoDevice(deviceconfig); } else { deviceconfig = dfs; * currentconfig = dfs; dcfu.saveConfigtoDevice(deviceconfig); } * * // this.saveConfigtoDevice(); } else { currentconfig = dfs; deviceconfig * = dfs; dcfu.saveConfigtoDevice(deviceconfig); } } * * else if (currentconfig == null) {// ถ้า load ไม่ได้ก้ดึงจาก device ที่ * System.out.println("Load local"); // save ไว้ dfs = * dcfu.loadfromdevice(); deviceconfig = currentconfig = dfs; } else { * System.out.println("Not load config use current config"); } * * if (dfs != null) return dfs; * * return null; * * } */ // ส่งข้อมูลทุก 1 นาที // @Scheduled(fixedRate = 60 * 1000) // public void send() { // send("61.19.255.23", "3333", data, pi.wifi()); // } // // public void send(String host, String port, BigDecimal tmp, String mac) { // String s = "http://" + host + ":" + port + "/addds?t=" + tmp + "&m=" + // mac; // try { // http.get(s); // } catch (IOException e) { // e.printStackTrace(); // } // // } }
import java.util.*; class calc{ int add(int i,int j){ return (i+j); } int sub(int i,int j){ return (i-j); } int mul(int i,int j){ return (i*j); } int div(int i,int j){ return (i/j); } } class fourth{ public static void main(String args[]){ Scanner s=new Scanner(System.in); System.out.println(); System.out.println("Calculator: "); System.out.print("Enter the First Number: "); int i=s.nextInt(); System.out.print("Enter the Second Number: "); int j=s.nextInt(); System.out.println("1.Addition\n2.Subtraction\n3.Multiplication\n4.Division"); System.out.print("Enter Your Choice: "); int choice=s.nextInt(); float result=0; calc c=new calc(); switch(choice){ case 1:result=c.add(i,j); break; case 2:result=c.sub(i,j); break; case 3:result=c.mul(i,j); break; case 4:result=c.div(i,j); break; } System.out.print("Answer= "+result); } }
package vip.ph.vueapp.mapper; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update; import vip.ph.vueapp.model.EmailLogin; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import java.util.List; /** * <p> * Mapper 接口 * </p> * * @author Just be alive * @since 2021-04-29 */ public interface EmailLoginMapper extends BaseMapper<EmailLogin> { @Insert("INSERT INTO t_email_login(email,salt,activetion_time,is_active,password,token) " + "VALUES (#{email},#{salt},#{activetionTime},#{isActive},#{password},#{token})") int insertEmailLogin(EmailLogin emailLogin); @Select("SELECT email,activetion_time FROM t_email_login WHERE token = #{token} ") EmailLogin selectEmailLoginByToken(String token); @Update("UPDATE t_email_login SET is_active = 1 where token = #{token}") int update(String token); @Select("select email,password,salt from t_email_login where email=#{email} and is_active=1") List<EmailLogin> selectEmail(String email); }
package edu.hawhamburg.shared.math; import org.junit.Test; import edu.hawhamburg.shared.datastructures.mesh.Vertex; import edu.hawhamburg.shared.datastructures.skeleton.Bone; import edu.hawhamburg.shared.datastructures.skeleton.Skeleton; import static org.junit.Assert.*; public class MathHelpersTest { private static final double DELTA = MathHelpers.EPSILON; @Test public void getDistanceVertexBone() throws Exception { Bone bone = new Bone(new Skeleton(), 10); // distance from end-points to bone has to be zero assertEquals(0, MathHelpers.getDistanceVertexBone(new Vertex(bone.getStart()), bone), DELTA); assertEquals(0, MathHelpers.getDistanceVertexBone(new Vertex(bone.getEnd()), bone), DELTA); // distance to any points on the bone has to be zero Vector boneDirection = bone.getEnd().subtract(bone.getStart()); assertEquals(0, MathHelpers.getDistanceVertexBone(new Vertex(bone.getStart().add(boneDirection.multiply(0.2))), bone), DELTA); assertEquals(0, MathHelpers.getDistanceVertexBone(new Vertex(bone.getStart().add(boneDirection.multiply(0.7))), bone), DELTA); // distance to points orthogonal to the bone has to be the orthogonal's vector length Vector orthogonalDirection = boneDirection.cross(new Vector(0, 0, 1)); assertEquals(orthogonalDirection.getNorm(), MathHelpers.getDistanceVertexBone(new Vertex(bone.getStart().add(orthogonalDirection)), bone), DELTA); assertEquals(orthogonalDirection.getNorm(), MathHelpers.getDistanceVertexBone(new Vertex(bone.getEnd().add(orthogonalDirection)), bone), DELTA); // distance to points on the line through the bone, but not on the bone itself have to have the correct distance assertEquals(boneDirection.getNorm(), MathHelpers.getDistanceVertexBone(new Vertex(bone.getEnd().add(boneDirection)), bone), DELTA); assertEquals(boneDirection.getNorm(), MathHelpers.getDistanceVertexBone(new Vertex(bone.getStart().add(boneDirection.multiply(-1))), bone), DELTA); } }
package swiss.kamyh.elo.arena.scenario; import org.bukkit.Bukkit; import org.bukkit.EntityEffect; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.entity.*; import org.bukkit.inventory.ItemStack; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import swiss.kamyh.elo.enumerate.ScenarioEnum; import swiss.kamyh.elo.tools.Configuration; import java.util.ArrayList; /** * Created by Vincent on 08.06.2016. * <p> * uses horses to fight */ public class MagicPoney extends Scenario implements IScenario { private final ArrayList<Player> participants; public MagicPoney(ArrayList<Player> participants) { super(ScenarioEnum.BRAIN_FUCK_TELEPORTATION); this.participants = participants; } @Override public void activate() { for (Player p : this.participants) { Location location = p.getLocation(); Horse horse = (Horse) location.getWorld().spawnCreature(location, EntityType.HORSE); horse.playEffect(EntityEffect.FIREWORK_EXPLODE); horse.setDomestication(1); horse.addPotionEffect(new PotionEffect(PotionEffectType.DAMAGE_RESISTANCE,9999999,2)); horse.addPotionEffect(new PotionEffect(PotionEffectType.REGENERATION,9999999,2)); horse.addPotionEffect(new PotionEffect(PotionEffectType.WATER_BREATHING,9999999,2)); horse.setMaxHealth(20); horse.setHealth(20); horse.setJumpStrength(2); horse.getInventory().addItem(new ItemStack(Material.SADDLE)); horse.setPassenger(p); } } }
package com.easyway.fixinventory.ui.login; import android.Manifest; import android.animation.ObjectAnimator; import android.os.Bundle; import android.os.Handler; import android.widget.ImageView; import android.widget.TextView; import com.easyway.fixinventory.MainActivity; import com.easyway.fixinventory.MainOffActivity; import com.easyway.fixinventory.R; import com.easyway.fixinventory.base.BaseApplication; import com.hanks.frame.base.HjjActivity; import com.hanks.frame.utils.UPermissionsTool; import com.hanks.frame.utils.Uintent; import butterknife.BindView; import butterknife.ButterKnife; /** * @author 侯建军 47466436@qq.com * @date 2018/5/28 * @description 欢迎界面 */ public class WelcomeActivity extends HjjActivity { @BindView(R.id.ac_welcome_iv_logo) ImageView mIvLogo; @BindView(R.id.ac_welcome_iv_company_name) TextView mTvCompanyName; int DURATION = 800; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_welcome); ButterKnife.bind(this); getPermission();//获取权限 new Handler().postDelayed(new Runnable() { @Override public void run() { intentActivity(); } }, 1100); initAnimation();//初始化动画 } /** * 初始化属性动画并执行 */ private void initAnimation() { float curTranslationY = mIvLogo.getTranslationY(); ObjectAnimator OAtranslationY = ObjectAnimator.ofFloat(mIvLogo, "translationY", curTranslationY + 150f, curTranslationY); OAtranslationY.setDuration(DURATION); OAtranslationY.start(); ObjectAnimator OAalpha = ObjectAnimator.ofFloat(mIvLogo, "alpha", 0.1f, 1f); OAalpha.setDuration(DURATION); OAalpha.start(); float tVcurTranslationY2 = mTvCompanyName.getTranslationY(); ObjectAnimator OAtVtranslationY = ObjectAnimator.ofFloat(mTvCompanyName, "translationY", tVcurTranslationY2 + 20, tVcurTranslationY2); OAtVtranslationY.setDuration(DURATION); OAtVtranslationY.start(); ObjectAnimator OAtValpha = ObjectAnimator.ofFloat(mTvCompanyName, "alpha", 0.1f, 1f); OAtValpha.setDuration(DURATION); OAtValpha.start(); ObjectAnimator OAtVscaleY = ObjectAnimator.ofFloat(mTvCompanyName, "scaleY", 0.1f, 1f); OAtVscaleY.setDuration(DURATION); OAtVscaleY.start(); ObjectAnimator OAtVscaleX = ObjectAnimator.ofFloat(mTvCompanyName, "scaleX", 0.1f, 1f); OAtVscaleX.setDuration(DURATION); OAtVscaleX.start(); } /** * 获取权限 */ private void getPermission() { UPermissionsTool. getIntance(this). addPermission(Manifest.permission.READ_EXTERNAL_STORAGE). addPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE). addPermission(Manifest.permission.CAMERA). addPermission(Manifest.permission.READ_PHONE_STATE). initPermission(); } /** * 跳转到下一个界面 */ private void intentActivity() { switch (BaseApplication.getInstance().userModel.getLoginState()) { case 1://登录在线 Uintent.intentDIYLeftToRight(this, MainActivity.class); break; case 2://登录离线 Uintent.intentDIYLeftToRight(this, MainOffActivity.class); break; default: Uintent.intentDIYLeftToRight(this, LoginActivity.class); } finish(); } }
package com.shihang.myframe.dialog; import android.app.Dialog; import android.content.Context; import com.shihang.myframe.R; public class LoadingDialog extends Dialog { public LoadingDialog(Context context) { super(context, R.style.dialog_loading); setContentView(R.layout.dialog_loading); } @Override public void cancel() { super.cancel(); } @Override public void show() { super.show(); } @Override public void dismiss() { super.dismiss(); } }
package com.vivek.sampleapp.activity; import android.content.Intent; import android.os.Bundle; import android.os.Environment; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.View; import com.vivek.sampleapp.R; import com.vivek.sampleapp.adapter.GalleryAdapter; import com.vivek.sampleapp.interfaces.ClickListener; import java.io.File; public class GalleryActivity extends BaseActivity implements ClickListener { public static File[] imageFiles; RecyclerView recyclerView; GalleryAdapter adapter; boolean usePicasso; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_gallery); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); recyclerView = (RecyclerView) findViewById(R.id.gallery_recycler_view); final GridLayoutManager layoutManager = new GridLayoutManager(getApplicationContext(),3); // layoutManager.setOrientation(LinearLayoutManager.VERTICAL); recyclerView.setLayoutManager(layoutManager); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } }); usePicasso = getIntent().getBooleanExtra("usePicasso",false); String CameraFolder="Camera"; File CameraDirectory = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).toString()); File[] files = CameraDirectory.listFiles(); for (File CurFile : files) { if (CurFile.isDirectory()) { Log.d("vvk","dir "+CurFile.getName() + " usePicasso " +usePicasso); imageFiles = CurFile.listFiles(); if(imageFiles!=null && imageFiles.length > 20) { adapter = new GalleryAdapter(getApplicationContext(),imageFiles,this,usePicasso); recyclerView.setAdapter(adapter); break; } // CameraDirectory=CurFile.getName(); } else { Log.d("vvk","file "+CurFile.getName()); } } } @Override public void itemClicked(int position, String type) { Intent i = new Intent(this,OpenImageActivity.class); i.putExtra("position",position); i.putExtra("usePicasso",usePicasso); startActivity(i); } }
package com.bofsoft.laio.customerservice.DataClass.Order; import com.bofsoft.laio.data.BaseData; /** * 找教练招生产品查找list item * * @author yedong */ public class FindTeacherData extends BaseData { public int ProductID; // Integer 产品Id,招生类产品直接返回i商品的Id public String CoachUUID; // String 教练Auth.UUID public String CoachUserUUID; // String 教练用户Account.UUID public String CoachName; // String 教练名字 public String CoachPhone; // String 联系电话 public String CoachHeadUrl; // String 教练头像路径Url public double CoachCredit; // Integer 信用评价 2014.10.15由int修改为double public int CoachLevel; // Integer 推荐指数 public String CoachInfo; // String // 教练简介信息,包含口碑<br>所属驾校<br>招生地址<br>联系电话<br>准教车型<br>初领日期<br>到期日期 // 新增字段 2014.10.15(web端使用) public int ClassType; // 招生产品收费模式,0一费制,1计时计程 /** * 产品名称 */ public String ProName; // 产品名称 public String ProDeadTime; // 产品截至日期 public int AuthStatus; // 是否通过实名认证,0未认证,1已认证 public int AllPapersReady; // 五证齐全,0不齐,1齐全 public String Addr; // 招生产品返回招生地址,培训产品返回训练场地 public String School; // 驾校名称 public int DealNo; // 成交量 public int EvaluateNo; // 评价数量 public double ProPrice; // 价格,培训产品返回最低价 public double ProPriceMax; // 价格,培训产品返回最高价与ProPrice构成价格区间 public String CarPicUrl; // 教练车图片路径Url public String CarType; // 报考车型 public String CarModel; // 教练车型,学时产品返回(网页端使用) // public String FindContent; //查询条件,对查找接口进行匹配过滤,为空时不做处理 public String Distance; // 距离学员所在位置距离,招生产品是与招生点的距离,培训产品是与训练场的距离,返回内容如:1.20公里或500米 public String SaleTag; // 促销信息标签,不为空时展示 public String SaleContent; // 促销内容描述,不为空时展示 public int ProType; // 产品类型,0招生类产品,1初学培训产品,2补训产品,3陪练产品,4计时培训; public String ProShortName; // 产品名称简称,列表中显示 public String ProContent; // 产品简介,优先显示SaleContent,当SaleContent为空时显示ProContent(仅招生产品显示) public double FirstPayAmount; // 首付金额,当金额大于0时才显示(仅招生产品显示) }
package com.barnettwong.view_library.callback; /** * 分享回调 */ public interface ShareListener { public abstract void shareSuccess(); public abstract void shareFailure(Exception e); public abstract void shareCancel(); }
package New.practice; import java.util.Scanner; public class AllTest { final static int THISYEAR = 2020; public int getAge(int year) { int age = THISYEAR - year + 1; return age; } public String getZodiac(int year) { switch (year % 12) { case 1: return "닭"; case 2: return "개"; case 3: return "돼지"; case 4: return "쥐"; case 5: return "소"; case 6: return "호랑이"; case 7: return "토끼"; case 8: return "용"; case 9: return "뱀"; case 10: return "말"; case 11: return "양"; default: return "원숭이"; } } public boolean leapYear(int year) { // 논리형 메소드 leapYear boolean leapyear = year % 4 == 0 && year % 100 != 0 || year % 400 == 0; // 윤년은 4년마다 돌아오고, 100년 주기로는 윤년이 아니다. 하지만 400년 주기로는 윤년. return leapyear; // 출생년도 값을 인자로 받아 true, false 리턴 } public int getCnt(int year, int month, int day) { int cnt = (year - 1) * 365; // 전체 일수 (출생년도-1)*365일 // 출생년도 -1 이유? --> 태어난 년도부터는 전체일수를 더하지 않고, 태어난 일 이전까지만 날짜를 더하기 때문. for (int i = 1; i < year; i++) { // 출생년도 이전까지의 년 수 if (leapYear(i)) // 윤년인지 아닌지 검사. cnt++; // 윤년인 경우 평년보다 하루가 많기때문에 cnt값 증가. } // 출생년도 이전까지의 전체 일수를 구했음. for (int i = 1; i < month; i++) {// 출생년도의 출생 월까지의 일수를 구함. switch (i) { case 1: // 출생 월 이전까지의, 일수가 31일인 달을 구해 cnt에 일수를 더함. case 3: case 5: case 7: case 8: case 10: case 12: cnt += 31; break; case 2: // 2월인 경우 if (leapYear(year)) // 윤년인지 체크한 후에 true값이 리턴되면 29일을 더함 cnt += 29; else cnt += 28; // false값이 리턴되면 28을 더함 break; default: cnt += 30; // 평년의 일수가 30일인 모든 달 break; } } cnt += day; // 태어난 일을 더함 return cnt; // 전체 일수를 리턴. } public String getWeek(int year, int month, int day) { switch (getCnt(year, month, day) % 7) { // int형 getCnt메소드 호출(인자값-getWeek에서 받아온 년,월,일)-->리턴값(전체 일수)%7 후에 요일값 리턴. case 1: return "월요일"; case 2: return "화요일"; case 3: return "수요일"; case 4: return "목요일"; case 5: return "금요일"; case 6: return "토요일"; default: return "일요일"; } } public void input(int year, int month, int day) { int age = getAge(year); // int형 메소드 getAge호출(인자값-출생년도) -->나이 구해서 리턴 int값. String zodiac = getZodiac(year); // String형 메소드 getZodiac호출(인자값- 출생년도)--->띠 구해서 리턴 String값 String week = getWeek(year, month, day);// String형 메소드 getWeek호출(인자값-출생년도,월,일)-->요일구해서 리턴 String값. System.out.println("나이:" + age + "\n띠:" + zodiac + "\n요일:" + week+"\n태어난지:"+getCnt(year, month, day)+"일 째"); } public static void main(String[] args) { AllTest at = new AllTest(); Scanner sc=new Scanner(System.in); System.out.println("출생년도 입력:"); int year=sc.nextInt(); System.out.println("태어난 월 입력:"); int month=sc.nextInt(); System.out.println("태어난 날짜 입력:"); int day=sc.nextInt(); at.input(year, month, day); } }
/** * Classes supporting the {@code org.springframework.orm.hibernate5} package. */ @NonNullApi @NonNullFields package org.springframework.orm.hibernate5.support; import org.springframework.lang.NonNullApi; import org.springframework.lang.NonNullFields;
package com.funnums.funnums.uihelpers; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.util.Log; import android.view.MotionEvent; import com.funnums.funnums.R; import com.funnums.funnums.maingame.GameActivity; /** * Adapted from James Cho's "Beginner's Guide to Android Game Development * Menu displayed when the game is over */ public class GameFinishedMenu { public String VIEW_LOG_TAG = "gameFinished"; private Context mContext; //back ground (board) for the menu private Bitmap bg; //fade the current game behind this menu private Rect fade; //buttons for the player to choose from private UIButton playAgain, mainMenu; //space between each button private int padding; //the score stored as a string, makes drawing easier private String score; //the message displayed on the game over menu private String gameFinishedMessage; //coords, along with dimensions int x; int y; int width, height; //scale of the text size so it fits inside the menu float xScale; float TEXT_SIZE = 60; public GameFinishedMenu(Context context, int left, int top, int width, int height, UIButton resumeButton, UIButton menuButton, Bitmap bg, Paint paint) { mContext = context; x = left; y = top; this.width = width; this.height = height; //create a scaled version of the given background image for the board; this.bg = Bitmap.createScaledBitmap(bg, left + width,top + height,true); //create translucent Rect to draw over game behind the menu fade = new Rect(0, 0, com.funnums.funnums.maingame.GameActivity.screenX, com.funnums.funnums.maingame.GameActivity.screenY); //create the buttons the player can use playAgain = new UIButton(0,0,0,0, resumeButton.getImg(), resumeButton.getImgDown()); mainMenu = new UIButton(0,0,0,0, menuButton.getImg(), menuButton.getImgDown()); //magic number for spacing, but seems to look good across different sized phones padding = (int)(com.funnums.funnums.maingame.GameActivity.screenY * 0.084459);//100; //Y coord for the buttons int buttonY = y + height *5/8; //in case we add more buttons, spacing between buttons will already be handled int numButtons = 2; //calculate space between buttons based on number of buttons //if there were more buttons, each would be placed at buttonY + spaceBetweenButtons*n int spaceBetweenButtons = (height - buttonY) / numButtons; int centeredButtonX = GameActivity.screenX/2 - playAgain.getWidth()/2; //set region corresponding to button clicks playAgain.setRect(centeredButtonX, buttonY); mainMenu.setRect(centeredButtonX, buttonY + spaceBetweenButtons*1); //give message for game over screen gameFinishedMessage = mContext.getString(R.string.game_finish_msg); //adjust the size of the text so it fits inside the menu //adjustTextSize(paint, gameFinishedMessage); adjustTextScale(paint, gameFinishedMessage); } public void setScore(int score) { this.score = String.valueOf(score); } public void draw(Canvas canvas, Paint paint) { //draw grey, tanslucent rectangle over entire screen paint.setColor(Color.argb(126, 0, 0, 0)); canvas.drawRect(fade, paint); paint.setColor(Color.argb(255, 100, 100, 100)); //draw the board canvas.drawBitmap(bg, x, y, paint); //center of screen int centeredX = GameActivity.screenX/2; //Set up the text appropriately paint.setColor(Color.argb(255, 0, 0, 255)); paint.setTextSize(TEXT_SIZE); paint.setTextAlign(Paint.Align.CENTER); paint.setTextScaleX(xScale); //draw the text canvas.drawText(gameFinishedMessage, centeredX, y + height/3, paint); canvas.drawText(score, centeredX, y + + height/3 + padding, paint); //draw the buttons playAgain.render(canvas, paint); mainMenu.render(canvas, paint); } //handle touches public boolean onTouch(MotionEvent e) { int x = (int)e.getX(); int y = (int)e.getY(); //if user touches down, change button appearances so they look pressed if (e.getAction() == MotionEvent.ACTION_DOWN) { playAgain.onTouchDown(x, y); mainMenu.onTouchDown(x, y); } if (e.getAction() == MotionEvent.ACTION_UP) { //check if either button is pressed down, and perform appropriate actions for each button if they are if (playAgain.isPressed(x, y)) { playAgain.cancel(); com.funnums.funnums.maingame.GameActivity.gameView.restart(); } else if(mainMenu.isPressed(x, y)) { mainMenu.cancel(); Intent i = new Intent(com.funnums.funnums.maingame.GameActivity.gameView.getContext(), com.funnums.funnums.maingame.MainMenuActivity.class); // Start our GameActivity class via the Intent i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); com.funnums.funnums.maingame.GameActivity.gameView.getContext().startActivity(i); } //otherwise make buttons appear unselected else { playAgain.cancel(); mainMenu.cancel(); } } return true; } /* Adjust the x scale of the text so it fits inside the menu */ void adjustTextScale(Paint paint, String text) { // do calculation with scale of 1.0 (no scale) paint.setTextScaleX(1.0f); Rect bounds = new Rect(); // ask the paint for the bounding rect if it were to draw this text. paint.setTextSize(TEXT_SIZE); paint.getTextBounds(text, 0, text.length(), bounds); // determine the width int w = bounds.right - bounds.left; // determine how much to scale the width to fit the view float xscale = ((float) width) / w; // set the scale for the text paint paint.setTextScaleX(xscale); this.xScale = xscale; } /* Change the backdrop image */ public void setBackDrop(Bitmap bg){ this.bg = Bitmap.createScaledBitmap(bg, x + width,y + height,true); } /* Adjust text size, in Y direction */ void adjustTextSize(Paint paint, String text) { //start with large size paint.setTextSize(100); paint.setTextScaleX(1.0f); Rect bounds = new Rect(); // ask the paint for the bounding rect if it were to draw this large text paint.getTextBounds(text, 0, text.length(), bounds); // get the height that would have been produced int w = bounds.right - bounds.left; // make the text text up 80% of the height float target = (float)width *.8f; // figure out what textSize setting would create that height of text float size = ((target/w)*100f); // and set it into the paint paint.setTextSize(size); TEXT_SIZE = size; } }
package com.example.mschyb.clockingapp; import android.content.Intent; import android.location.Address; import android.location.Geocoder; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import com.mysql.jdbc.Util; import java.io.IOException; import java.util.List; public class EnterAddressActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_enter_address); Button gc = (Button) findViewById(R.id.GetAddressCoordinatesButton); Button bk = (Button) findViewById(R.id.btnBkAddress); bk.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(getApplicationContext(), HomeScreenActivity.class)); } }); gc.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { TextView addressMessage = (TextView) findViewById(R.id.addressErrorText); EditText street = (EditText) findViewById(R.id.editTextStreetName); EditText city = (EditText) findViewById(R.id.editTextCityName); EditText state = (EditText) findViewById(R.id.editTextStateName); EditText zip = (EditText) findViewById(R.id.editTextZipcode); String address = street.getText().toString() + ", "+city.getText().toString()+", "+state.getText().toString()+" "+zip.getText().toString(); List<Address> addresses = null; try { Thread.sleep(100); } catch(InterruptedException e) {Log.e(Config.TAG, "Error when tryign to sleep");} Geocoder geo = new Geocoder(EnterAddressActivity.this); try { Thread.sleep(100); } catch(InterruptedException e) {Log.e(Config.TAG, "Error when tryign to sleep");} try { int counter = 0; while(counter < 8) //Try to get the address several times { addresses = geo.getFromLocationName(address, 5); if(!(address == null)) break; counter++; } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { // TextView lo = (TextView) findViewById(R.id.textViewLo); // TextView la = (TextView) findViewById(R.id.textViewLa); // lo.setText(String.valueOf(addresses.get(0).getLatitude())); // la.setText(String.valueOf(addresses.get(0).getLongitude())); TextView distance = (TextView) findViewById(R.id.distance); if(Utilities.saveGpsCoordinates(String.valueOf(addresses.get(0).getLatitude()) , String.valueOf(addresses.get(0).getLatitude()), distance.getText().toString())) addressMessage.setText("Coordinates have been saved!"); } catch(NullPointerException e) { Log.e(Config.TAG, "Null pointer when trying to get address information"); addressMessage.setText("Error when getting coordinates from Android..."); } } }); } }
package com.codingchili.instance.model.movement; public enum Animation { dance_1, dance_2, jump }
package com.mycompany.interacciondb; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; /** * * @author elias */ public class TablaAdministradores { private StringProperty Nombre,TelMovil,TelFijo,Email; public TablaAdministradores(String Nombre,String paterno, String materno, String TelMovil, String TelFijo, String Email){ this.Nombre = new SimpleStringProperty(Nombre+" "+paterno+" "+materno); this.TelMovil= new SimpleStringProperty(TelMovil); this.TelFijo = new SimpleStringProperty(TelFijo); this.Email = new SimpleStringProperty(Email); } public TablaAdministradores(){ } public String getNombre() { return Nombre.get(); } public void setNombre(String Nombre) { this.Nombre = new SimpleStringProperty(Nombre); } /** * @return the TelMovil */ public String getTelMovil() { return TelMovil.get(); } /** * @param TelMovil the TelMovil to set */ public void setTelMovil(String TelMovil) { this.TelMovil = new SimpleStringProperty(TelMovil); } /** * @return the TelFijo */ public String getTelFijo() { return TelFijo.get(); } /** * @param TelFijo the TelFijo to set */ public void setTelFijo(String TelFijo) { this.TelFijo = new SimpleStringProperty(TelFijo); } /** * @return the Email */ public String getEmail() { return Email.get(); } /** * @param Email the Email to set */ public void setEmail(String Email) { this.Email = new SimpleStringProperty(Email) ; } }
import java.io.*; import java.text.DecimalFormat; import java.util.*; public class AppRunner { public static void main(String[] args) throws IOException { System.out.print("Введите название файла: "); String fileName; fileName = args[0]; BufferedReader br = new BufferedReader(new FileReader(fileName)); var allSymbols = new HashMap<String, Integer>(); String line; int countSym = 0; double info = 0; while ((line = br.readLine()) != null) { char[] chars = line.toCharArray(); for (char aChar : chars) { countSym++; if (!allSymbols.containsKey(String.valueOf(aChar))) { allSymbols.put(String.valueOf(aChar), 1); } else { allSymbols.replace(String.valueOf(aChar), allSymbols.get(String.valueOf(aChar)) + 1); } } } DecimalFormat numberFormat = new DecimalFormat("0.000000"); // File file = new File("freq_result.txt"); // boolean newFile = file.createNewFile(); // if (!newFile) { // throw new RuntimeException("file not created"); // } // BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file)); Map<String, Integer> sortByValue = sortByValue(allSymbols); String res; for (Map.Entry<String, Integer> map : sortByValue.entrySet()) { double freq = (double) map.getValue() / countSym; if (map.getKey().equals(" ")) res = "space" + " : " + map.getValue() + " : " + numberFormat.format(freq); else res = map.getKey() + " : " + map.getValue() + " : " + numberFormat.format(freq); // bufferedWriter.write(res + "\n"); System.out.println(res); info += (freq * log2(freq)); // bufferedWriter.flush(); } System.out.println(Math.log1p(625)); // bufferedWriter.write("countSym = " + countSym + "\n"); // bufferedWriter.write("info = " + info * -1); // bufferedWriter.flush(); System.out.println("countSym = " + countSym); System.out.println("info = " + info * -1); } static Map<String, Integer> sortByValue(Map<String, Integer> map) { List<Map.Entry<String, Integer>> list = new LinkedList<>(map.entrySet()); list.sort(Map.Entry.comparingByValue()); Map<String, Integer> sortedMap = new LinkedHashMap<>(); for (Map.Entry<String, Integer> entry : list) { sortedMap.put(entry.getKey(), entry.getValue()); } return sortedMap; } private static double log2(double num) { return Math.log(num) / Math.log(2); } }
package model; import view.PlayerView; import view.ScoreView; import java.util.ArrayList; public interface Subject { void registerObserver(Observer observer); void removeObserver(Observer observer); void notifyObservers(ArrayList<PlayerView> spelers, PlayerView p, ScoreView view, int i1, int i2, int totaal); }
package day4; import java.util.ArrayList; import java.util.Iterator; public class ArrayListExample { public static void main(String[] args) { ArrayList<String> list = new ArrayList<String>(); list.add("Apple"); list.add("Mango"); list.add("Guava"); list.add("Banana"); list.add("Grapes"); list.add("Jackfruit"); //traverse through list Iterator res = list.iterator(); while(res.hasNext()) { System.out.println(res.next()); } System.out.println("--------------------------------------------------"); list.remove(2); res = list.iterator(); //res object is specified again since we have removed an element from the list!!! while(res.hasNext()) { System.out.println(res.next()); } } }
package com.gcc.vo; import lombok.Data; /** * @author SoraNimi * @className LineVO * @email 434624198@qq.com * @github https://github.com/SoraNimi */ @Data public class LineVO { Integer lineId; String cityName; String lineName; }
package org.qw3rtrun.aub.engine.property.quaternion; import com.sun.javafx.binding.FloatConstant; import javafx.beans.Observable; import javafx.beans.binding.Binding; import javafx.beans.value.ObservableNumberValue; import org.qw3rtrun.aub.engine.property.BaseBinding; import org.qw3rtrun.aub.engine.property.vector.ObservableVector3f; import org.qw3rtrun.aub.engine.property.vector.Vector3fBinding; import org.qw3rtrun.aub.engine.property.vector.Vector3fConstant; import org.qw3rtrun.aub.engine.vectmath.Quaternion; import java.util.Arrays; import java.util.function.Supplier; import static org.qw3rtrun.aub.engine.vectmath.Quaternion.QXYZ0; import static org.qw3rtrun.aub.engine.vectmath.Quaternion.quaternion; public class QuaternionBinding extends BaseBinding<Quaternion> implements Binding<Quaternion>, QuaternionExpression { public QuaternionBinding(Supplier<Quaternion> func, Observable... dependencies) { super(func, dependencies); } public static QuaternionBinding normalize(ObservableQuaternion quat) { return new QuaternionBinding(() -> quat.get().normalize(), quat); } public static Vector3fBinding rotate(ObservableQuaternion rotation, ObservableVector3f vector) { return new Vector3fBinding(() -> { Quaternion normalized = rotation.get().normalize(); return normalized.product(quaternion(vector.getValue())).product(normalized.conjugate()).getVectorPart(); }, rotation, vector); } public static QuaternionBinding axisRotation(ObservableVector3f axis, ObservableNumberValue radian) { return new QuaternionBinding(() -> { Vector3fBinding normalizedAxis = Vector3fBinding.normalize(axis); double a2 = radian.doubleValue() / 2; double sin = (float) Math.sin(a2); double cos = (float) Math.cos(a2); return quaternion( (float) (normalizedAxis.getX() * sin), (float) (normalizedAxis.getY() * sin), (float) (normalizedAxis.getZ() * sin), (float) cos); }, axis, radian); } public static QuaternionBinding orientation(ObservableVector3f rotation) { return concatRotations( axisRotation(Vector3fConstant.CONST_X, FloatConstant.valueOf(rotation.getX())), axisRotation(Vector3fConstant.CONST_Y, FloatConstant.valueOf(rotation.getY())), axisRotation(Vector3fConstant.CONST_Z, FloatConstant.valueOf(rotation.getZ())) ); } public static QuaternionBinding concatRotation(ObservableQuaternion quaternion1, ObservableQuaternion orientation2) { return new QuaternionBinding(() -> orientation2.get().product(quaternion1.get()).normalize()); } public static QuaternionBinding concatRotations(ObservableQuaternion... quaternions) { switch (quaternions.length) { case 0: return new QuaternionBinding(() -> QXYZ0); case 1: return new QuaternionBinding(quaternions[0]::get, quaternions[0]); default: //noinspection OptionalGetWithoutIsPresent return (QuaternionBinding) Arrays.stream(quaternions).<QuaternionBinding>reduce(QuaternionBinding::concatRotation).get(); } } public String toString() { return isValid() ? "Quaternion [" + getValue() + "]" : "Quaternion [invalid]"; } }
package stephen.ranger.ar.materials; import java.awt.Color; import stephen.ranger.ar.Camera; import stephen.ranger.ar.IntersectionInformation; import stephen.ranger.ar.RTStatics; public class ReflectionMaterial extends ColorInformation { public ReflectionMaterial(final Color diffuse) { super(diffuse, 100); } @Override public float[] getMaterialColor(final Camera camera, final IntersectionInformation info, final int depth) { final IntersectionInformation mirrorInfo = camera.getClosestIntersection(info.intersectionObject, info.intersection, RTStatics .getReflectionDirection(info), info.normal, depth + 1); if (mirrorInfo == null) { return camera.light.ambient.getColorComponents(new float[3]); } else { return mirrorInfo.intersectionObject.getColor(mirrorInfo, camera, depth + 1); } } }
import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.Clip; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.UnsupportedAudioFileException; public class Music { static Clip clip; static long clipTimePosition; static File musicPath = new File("src\\main\\resources\\batmanpiano.wav"); static void play() throws LineUnavailableException, UnsupportedAudioFileException, IOException { if (musicPath.exists()) { AudioInputStream audioInput = AudioSystem.getAudioInputStream(musicPath); clip = AudioSystem.getClip(); clip.open(audioInput); clip.start(); clip.loop(Clip.LOOP_CONTINUOUSLY); } } }
package com.hyper.components.table; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.event.CellEditorListener; import javax.swing.event.ChangeEvent; import com.hyper.components.rr.FunctionPanel; public class FunctionTableListener implements CellEditorListener, MouseListener { private FunctionPanel functions; public FunctionTableListener(FunctionPanel functions) { this.functions = functions; //Default editor functions.getTable().getCellEditor(0, 0).addCellEditorListener(this); //Color button editor functions.getTable().getCellEditor(0, 2).addCellEditorListener(this); functions.getTable().addMouseListener(this); } @Override public void editingStopped(ChangeEvent e) { boolean isFull = true; for(int row = 0; row < functions.getTable().getRowCount(); row++) { String funcName = (String) functions.getTable().getValueAt(row, 0); if(funcName == null || funcName.isEmpty()) isFull = false; } if(isFull) functions.getTable().addRow(); functions.revalidate(); } @Override public void editingCanceled(ChangeEvent e) {} @Override public void mouseClicked(MouseEvent e) {} @Override public void mousePressed(MouseEvent e) { if(e.getSource().equals(functions.getTable())) functions.mousePressed(e.getX(), e.getY()); } @Override public void mouseReleased(MouseEvent e) {} @Override public void mouseEntered(MouseEvent e) {} @Override public void mouseExited(MouseEvent e) {} }
package com.weichuang; public class Main { public static void main(String[] args) { System.out.println("sdfsd"); // 一些基本操作 int i = 22; // i= ++i; // System.out.println(i); if(23 == ++i){ System.out.println("真"); }else{ System.out.println("假"); } int a = 14; int b = 17; if(a < b){ System.out.println(a-=b); } if (a < 10 | b < 12) { System.out.println(a + "\n" + b); System.out.println(b%=a); }else{ System.out.println(a*=b); } } }
/* * Copyright © 2020-2022 ForgeRock AS (obst@forgerock.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.org.openbanking.testsupport.payment; import uk.org.openbanking.datamodel.payment.*; import java.util.UUID; /** * Test data factory for the various "SCASupportData" classes. */ public class OBWriteDomesticScaSupportDataTestDataFactory { public static OBWriteDomesticConsent3DataSCASupportData aValidOBWriteDomesticConsent3DataSCASupportData() { return (new OBWriteDomesticConsent3DataSCASupportData()) .appliedAuthenticationApproach(OBAppliedAuthenticationApproachEnum.CA) .referencePaymentOrderId(UUID.randomUUID().toString()) .requestedSCAExemptionType(OBRequestedSCAExemptionTypeEnum.BILLPAYMENT); } public static OBWriteDomesticConsent4DataSCASupportData aValidOBWriteDomesticConsent4DataSCASupportData() { return (new OBWriteDomesticConsent4DataSCASupportData()) .appliedAuthenticationApproach(OBAppliedAuthenticationApproachEnum.CA) .referencePaymentOrderId(UUID.randomUUID().toString()) .requestedSCAExemptionType(OBRequestedSCAExemptionTypeEnum.BILLPAYMENT); } public static OBSCASupportData1 aValidOBSCASupportData1() { return (new OBSCASupportData1()) .appliedAuthenticationApproach(OBAppliedAuthenticationApproachEnum.CA) .referencePaymentOrderId(UUID.randomUUID().toString()) .requestedSCAExemptionType(OBRequestedSCAExemptionTypeEnum.BILLPAYMENT); } }
package com.devpmts.dropaline.api; import java.util.stream.Stream; import javax.inject.Inject; import javax.inject.Singleton; import org.eclipse.e4.core.di.annotations.Creatable; import org.eclipse.e4.core.di.annotations.Optional; import org.eclipse.e4.core.di.extensions.Preference; import com.devpmts.DevsLogger; import com.devpmts.dropaline.CORE; import com.devpmts.dropaline.delivery.CacheDeliveryService; import com.devpmts.dropaline.io.FileAndDataAccess; import com.devpmts.dropaline.ui.UserInterface; import com.devpmts.util.StringUtil; import com.devpmts.util.e4.DI; @Singleton @Creatable public abstract class Authenticator { @Inject @Optional protected UserInterface userInterface; @Inject @Optional private static FileAndDataAccess fileSystemAccess; @Inject @Optional @Preference(nodePath = CORE.NODE_PATH, value = CORE.USERNAME) String user; @Inject @Optional @Preference(nodePath = CORE.NODE_PATH, value = CORE.PASSWORD) String password; @Inject public Authenticator() { } public static void attemptAuthenticationOfPendingAccounts() { if (!DI.get(FileAndDataAccess.class).hasOnlineAccess()) { return; } DevsLogger.log(Authenticator.class, "Starting authentication process..."); getPendingAuthenticators().forEach(authenticator -> authenticator.attemptAuthentication()); } private static Stream<Authenticator> getPendingAuthenticators() { return PimApi.getAvailableApis()// .map(pimApi -> pimApi.authenticator())// .filter(authenticator -> !authenticator.isAuthenticated()); } protected boolean authenticated; protected PimApi pimApi; public void attemptAuthentication() { if (StringUtil.isEmpty(userName())) { DevsLogger.log("no userid specified. cancelling authentication attempt"); return; } try { assert !authenticated; authenticate(); authenticated = true; } catch (AuthenticationException a) { handleAuthenticationException(a); } finalizeAuthentication(); } public abstract void authenticate() throws AuthenticationException; private void finalizeAuthentication() { if (!authenticated) { return; } DevsLogger.log("# successfully authenticated " + pimApi.name()); CacheDeliveryService.trigger(); } public boolean isAuthenticated() { return authenticated; } public String password() { return password; } public PimApi pimApi() { return pimApi; } public void setCredentials(String email, String password) throws AuthenticationException { DI.setPreference(CORE.USERNAME, email); DI.setPreference(CORE.PASSWORD, password); } void setPimApi(PimApi api) { this.pimApi = api; } public String userName() { return user; } public void authenticate(String email, String password) { try { setCredentials(email, password); } catch (AuthenticationException e) { handleAuthenticationException(e); } attemptAuthentication(); } private void handleAuthenticationException(AuthenticationException e) { authenticated = false; DevsLogger.log(this, e); userInterface.handleAuthenticationFailed(pimApi(), e); } }
// https://www.youtube.com/watch?v=KE5Axm7uzok public class Solution { // you need treat n as an unsigned value public int reverseBits(int n) { int res = 0; List<Integer> l = new ArrayList<>(); int time = 32; while (time != 0) { int t = n & 1; l.add(0, t); n >>= 1; time--; } for (int i = l.size() - 1; i >= 0; i--) { res <<= 1; res = res | l.get(i); } return res; } }
package SQLDate; import Connection.DBConnection; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import static javax.management.remote.JMXConnectorFactory.connect; public class AuthorList { private ArrayList<Author> authorList = new ArrayList<Author>(); Statement stmt = null; ResultSet rs = null; Connection conn = null; private ArrayList<Author> getAuthors(){ try { conn = DBConnection.init(); stmt = conn.createStatement(); rs = stmt.executeQuery("SELECT * FROM author ORDER BY fio"); while(rs.next()){ Author author = new Author(); author.setId(rs.getLong("id")); author.setFio(rs.getString("fio")); authorList.add(author); } } catch (SQLException ex) { ex.printStackTrace(); }finally{ try { if (stmt!=null) stmt.close(); if (rs!=null)rs.close(); if (conn!=null)conn.close(); } catch(SQLException ex){ ex.printStackTrace(); } } return authorList; } public ArrayList<Author> getAuthorList(){ if(!authorList.isEmpty()){ return authorList; }else{ return getAuthors(); } } }
package concurrency; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; public class CompletableFutureTests { public static void main(String[] args) { new CompletableFutureTests(); } public CompletableFutureTests() { create(); createAndTransform(); createAndTransformAndOutput(); createTransformException(); createTwoWaitAndInform(); createTwoWaitAndCombine(); createTwoAndOutputFirstFinished(); createManyWaitForAllAndCombine(); loadWebPage(); } public void loadWebPage() { getWebPage("http://www.google.pl").thenAccept( content -> System.out.println(content));// .join(); System.out.println("Thread requesting page: " + Thread.currentThread().getName()); } private CompletableFuture<String> getWebPage(String urlString) { CompletableFuture<String> cf = new CompletableFuture<String>(); new Thread(new Runnable() { @Override public void run() { try { URL oracle = new URL(urlString); BufferedReader in = new BufferedReader( new InputStreamReader(oracle.openStream())); String inputLine; StringBuffer buffer = new StringBuffer(); while ((inputLine = in.readLine()) != null) { buffer.append(inputLine); } in.close(); System.out.println("Thread loading page: " + Thread.currentThread().getName()); cf.complete(buffer.toString()); } catch (IOException e) { cf.completeExceptionally(e); } } },"MySpecialThead").start();; return cf; } public void create() { try { System.out.println(CompletableFuture.supplyAsync(() -> "4") .exceptionally(ex -> ex.toString()).get()); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } public void createAndTransform() { try { System.out.println(CompletableFuture.supplyAsync(() -> "4") .thenApply(n -> Integer.valueOf(n)).thenApply(n -> n * n) .get()); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } public void createAndTransformAndOutput() { CompletableFuture.supplyAsync(() -> "4") .thenApply(n -> Integer.valueOf(n)).thenApply(n -> n * n) .thenAccept(it -> System.out.println("Output: " + it)); } public void createTransformException() { CompletableFuture.supplyAsync(() -> 4 / 0).exceptionally(ex -> { System.out.println("Exception: " + ex.toString()); return -1; }).thenAccept(it -> System.out.println("Exception Output: " + it)); } public void createTwoWaitAndInform() { CompletableFuture<Integer> cf1 = CompletableFuture .supplyAsync(() -> "4").thenApply(n -> Integer.valueOf(n)) .thenApply(n -> n * n); CompletableFuture<Integer> cf2 = CompletableFuture .supplyAsync(() -> "5").thenApply(n -> Integer.valueOf(n)) .thenApply(n -> n * n); cf1.thenAcceptBoth(cf2, (n1, n2) -> System.out.println(String.format( "Processing finish! Results %d,%d", n1, n2))); } public void createTwoWaitAndCombine() { CompletableFuture<Integer> cf1 = CompletableFuture .supplyAsync(() -> "4").thenApply(n -> Integer.valueOf(n)) .thenApply(n -> n * n); CompletableFuture<Integer> cf2 = CompletableFuture .supplyAsync(() -> "5").thenApply(n -> Integer.valueOf(n)) .thenApply(n -> n * n); cf1.thenCombine(cf2, (n1, n2) -> n1 + n2).thenAccept( n -> System.out.println("Combination results: " + n)); } public void createTwoAndOutputFirstFinished() { CompletableFuture<Integer> cf1 = CompletableFuture .supplyAsync(() -> "4").thenApply(n -> Integer.valueOf(n)) .thenApply(n -> n * n); CompletableFuture<Integer> cf2 = CompletableFuture .supplyAsync(() -> "5").thenApply(n -> Integer.valueOf(n)) .thenApply(n -> n * n); cf1.acceptEither(cf1, zahl -> System.out.println("First completed: " + zahl)); } public void createManyWaitForAllAndCombine() { CompletableFuture<Integer> cf1 = CompletableFuture .supplyAsync(() -> "4").thenApply(n -> Integer.valueOf(n)) .thenApply(n -> n * n); CompletableFuture<Integer> cf2 = CompletableFuture .supplyAsync(() -> "5").thenApply(n -> Integer.valueOf(n)) .thenApply(n -> n * n); CompletableFuture.allOf(cf1, cf2).thenAccept( n -> System.out.println("Combination of all results: " + n)); } }
package io.nuls.consensus.tx.v1; import io.nuls.base.data.BlockHeader; import io.nuls.base.data.Transaction; import io.nuls.base.protocol.TransactionProcessor; import io.nuls.consensus.model.bo.Chain; import io.nuls.consensus.model.bo.tx.txdata.Agent; import io.nuls.consensus.model.bo.tx.txdata.RedPunishData; import io.nuls.consensus.utils.LoggerUtil; import io.nuls.consensus.utils.manager.AgentDepositNonceManager; import io.nuls.consensus.utils.manager.ChainManager; import io.nuls.core.basic.Result; import io.nuls.core.constant.TxType; import io.nuls.core.core.annotation.Autowired; import io.nuls.core.core.annotation.Component; import io.nuls.core.crypto.HexUtil; import io.nuls.core.exception.NulsException; import io.nuls.consensus.constant.ConsensusErrorCode; import io.nuls.consensus.utils.manager.AgentManager; import io.nuls.consensus.utils.validator.CreateAgentValidator; import java.util.*; /** * 创建节点处理器 * * @author tag * @date 2019/6/1 */ @Component("CreateAgentProcessorV1") public class CreateAgentProcessor implements TransactionProcessor { @Autowired private AgentManager agentManager; @Autowired private ChainManager chainManager; @Autowired private CreateAgentValidator validator; @Override public int getType() { return TxType.REGISTER_AGENT; } @Override public int getPriority() { return 8; } @Override public Map<String, Object> validate(int chainId, List<Transaction> txs, Map<Integer, List<Transaction>> txMap, BlockHeader blockHeader) { Chain chain = chainManager.getChainMap().get(chainId); Map<String, Object> result = new HashMap<>(2); if (chain == null) { LoggerUtil.commonLog.error("Chains do not exist."); result.put("txList", txs); result.put("errorCode", ConsensusErrorCode.CHAIN_NOT_EXIST.getCode()); return result; } List<Transaction> invalidTxList = new ArrayList<>(); String errorCode = null; Set<String> redPunishAddressSet = new HashSet<>(); Set<String> createAgentAddressSet = new HashSet<>(); List<Transaction> redPunishTxList = txMap.get(TxType.RED_PUNISH); if (redPunishTxList != null && redPunishTxList.size() > 0) { for (Transaction redPunishTx : redPunishTxList) { RedPunishData redPunishData = new RedPunishData(); try { redPunishData.parse(redPunishTx.getTxData(), 0); String addressHex = HexUtil.encode(redPunishData.getAddress()); redPunishAddressSet.add(addressHex); } catch (NulsException e) { chain.getLogger().error(e); } } } Result rs; for (Transaction createAgentTx : txs) { try { rs = validator.validate(chain, createAgentTx, blockHeader); if (rs.isFailed()) { invalidTxList.add(createAgentTx); chain.getLogger().info("Failure to create node transaction validation"); errorCode = rs.getErrorCode().getCode(); continue; } Agent agent = new Agent(); agent.parse(createAgentTx.getTxData(), 0); String agentAddressHex = HexUtil.encode(agent.getAgentAddress()); String packAddressHex = HexUtil.encode(agent.getPackingAddress()); /* * 获得过红牌交易的地址不能创建节点 * */ if (!redPunishAddressSet.isEmpty()) { if (redPunishAddressSet.contains(agentAddressHex) || redPunishAddressSet.contains(packAddressHex)) { invalidTxList.add(createAgentTx); chain.getLogger().info("Creating Node Trading and Red Card Trading Conflict"); errorCode = ConsensusErrorCode.CONFLICT_ERROR.getCode(); continue; } } /* * 重复创建节点 * */ if (!createAgentAddressSet.add(agentAddressHex) || !createAgentAddressSet.add(packAddressHex)) { invalidTxList.add(createAgentTx); chain.getLogger().info("Repeated transactions"); errorCode = ConsensusErrorCode.CONFLICT_ERROR.getCode(); } } catch (NulsException e) { invalidTxList.add(createAgentTx); chain.getLogger().error("Conflict calibration error"); chain.getLogger().error(e); errorCode = e.getErrorCode().getCode(); } } result.put("txList", invalidTxList); result.put("errorCode", errorCode); return result; } @Override public boolean commit(int chainId, List<Transaction> txs, BlockHeader blockHeader, int syncStatus) { Chain chain = chainManager.getChainMap().get(chainId); if (chain == null) { LoggerUtil.commonLog.error("Chains do not exist."); return false; } List<Transaction> commitSuccessList = new ArrayList<>(); boolean commitResult = true; for (Transaction tx : txs) { if (createAgentCommit(tx, blockHeader, chain)) { commitSuccessList.add(tx); } else { commitResult = false; break; } } //回滚已提交成功的交易 if (!commitResult) { for (Transaction rollbackTx : commitSuccessList) { createAgentRollBack(rollbackTx, chain, blockHeader); } } return commitResult; } @Override public boolean rollback(int chainId, List<Transaction> txs, BlockHeader blockHeader) { Chain chain = chainManager.getChainMap().get(chainId); if (chain == null) { LoggerUtil.commonLog.error("Chains do not exist."); return false; } List<Transaction> rollbackSuccessList = new ArrayList<>(); boolean rollbackResult = true; for (Transaction tx : txs) { if (createAgentRollBack(tx, chain, blockHeader)) { rollbackSuccessList.add(tx); } else { rollbackResult = false; break; } } //保存已回滚成功的交易 if (!rollbackResult) { for (Transaction commitTx : rollbackSuccessList) { createAgentCommit(commitTx, blockHeader, chain); } } return rollbackResult; } private boolean createAgentCommit(Transaction transaction, BlockHeader blockHeader, Chain chain) { Agent agent = new Agent(); try { agent.parse(transaction.getTxData(), 0); } catch (NulsException e) { chain.getLogger().error(e); return false; } agent.setTxHash(transaction.getHash()); agent.setBlockHeight(blockHeader.getHeight()); agent.setTime(transaction.getTime()); if (!agentManager.addAgent(chain, agent)) { chain.getLogger().error("Agent record save fail"); return false; } if (!AgentDepositNonceManager.init(agent, chain, transaction.getHash())) { agentManager.removeAgent(chain, transaction.getHash()); chain.getLogger().error("Agent deposit nonce record init error"); return false; } return true; } private boolean createAgentRollBack(Transaction transaction, Chain chain, BlockHeader blockHeader) { if (!AgentDepositNonceManager.delete(chain, transaction.getHash())) { chain.getLogger().error("Agent deposit init nonce rollback error"); return false; } if (!agentManager.removeAgent(chain, transaction.getHash())) { Agent agent = new Agent(); try { agent.parse(transaction.getTxData(), 0); } catch (NulsException e) { chain.getLogger().error(e); return false; } agent.setTxHash(transaction.getHash()); agent.setBlockHeight(blockHeader.getHeight()); agent.setTime(transaction.getTime()); AgentDepositNonceManager.init(agent, chain, transaction.getHash()); chain.getLogger().error("Create agent tx rollback error"); return false; } return true; } }
import java.io.BufferedReader; import java.io.InputStreamReader; public class Main { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] nums = br.readLine().split(" "); int r = Integer.parseInt(nums[4]); int a = Integer.parseInt(nums[0]) - r * 2; int b = Integer.parseInt(nums[1]) - r * 2; int x = Integer.parseInt(nums[2]); int y = Integer.parseInt(nums[3]); int t = Integer.parseInt(nums[5]); int l = Integer.parseInt(nums[6]); double dx = l*Math.cos(Math.PI * t / 180) + x; double dy = l*Math.sin(Math.PI * t / 180) + y; // 水平方向にぶつかる回数 int ao = (int)Math.floor(dx) / (a); if (dx < 0) ao--; // 垂直方向にぶつかる回数 int bo = (int)Math.floor(dy) / (b); if (dy < 0) bo--; // 座標の反転係数 int as = ao % 2; int bs = bo % 2; System.out.println( (as == 0 ? dx % a : a - dx % a + r * 2) + " " + (bs == 0 ? dy % b : b - dy % b + r * 2) ); } }
package com.xi.alibaba.inter; import com.xi.alibaba.TestEnum; public class Test { public static void main(String[] args) { System.out.println("EnumTest.FRIDAY 的 value = " + TestEnum.FRIDAY.getValue()); } }
package com.cloubiot.buddyWAPI.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.cloubiot.buddWAPI.model.content.ContentData; import com.cloubiot.buddyWAPI.dao.ContentQuery; import com.cloubiot.buddyWAPI.dao.ContentRepository; import com.cloubiot.buddyWAPI.model.dbentity.Content; import com.cloubiot.buddyWAPI.util.JSONUtil; @Service public class ContentService { @Autowired ContentRepository contactRepository; @Autowired ContentQuery contactQuery; public Content saveContact(Content contact) { return contactRepository.save(contact); } public List<Content> getAllContent(){ return contactRepository.findAll(); } public List<Content> getContentByChannelId(String channelId){ List<ContentData> data = contactQuery.getContentByChannelId(channelId); System.out.println(JSONUtil.toJson("Data "+JSONUtil.toJson(data))); return contactRepository.findByChannelId(channelId); } }
package com.jwebsite.dao; import java.sql.ResultSet; import java.sql.SQLException; import com.jwebsite.vo.OnDuty; public interface OnDutyDao { //显示所有值班信息 public ResultSet showAllODt() throws Exception; //添加值班信息 public void insertODt(OnDuty onduty) throws Exception; //删除值班信息 public void delODt(OnDuty onduty) throws Exception; //更新值班信息 public void updateODt(OnDuty onduty) throws Exception; //查询一条 public OnDuty quaryOneODt(int ID) throws Exception; public String showSel(String selstr)throws Exception; }
package com.example.springhibernate.hibernate.services; import com.example.springhibernate.hibernate.models.Book; import com.example.springhibernate.hibernate.models.BookDetail; import com.example.springhibernate.hibernate.models.Chapter; import com.example.springhibernate.hibernate.models.Writer; import com.example.springhibernate.hibernate.repositories.BookRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; @Service public class BookService { @Autowired private BookRepository bookRepository; public List<Book> list() { return bookRepository.findAll(); } public Book save() { Book book = this.getBook(); return bookRepository.save(book); } private Book getBook() { BookDetail bookDetail = this.getBookDetail(); Book book = new Book(); book.setName("Anonto Nokkhotro"); book.setBookDetail(bookDetail); return book; } private BookDetail getBookDetail() { BookDetail bookDetail = new BookDetail(); bookDetail.setIsbn("124-34-4345"); bookDetail.setDescription("Osdharon Book"); return bookDetail; } public Object addChaptersAndDetail() { Chapter chapter1 = new Chapter(); chapter1.setChapterNo(1); chapter1.setTitle("Onidro Rojoni"); Chapter chapter2 = new Chapter(); chapter2.setChapterNo(2); chapter2.setTitle("Jongole Ami"); Book book = new Book(); book.setName("Runita"); book.addChapter(chapter1); book.addChapter(chapter2); BookDetail bookDetail = new BookDetail(); bookDetail.setIsbn("323-33-235435"); bookDetail.setDescription("This is a nice book!"); book.setBookDetail(bookDetail); return bookRepository.save(book); } public Object addChapters() { Chapter chapter1 = new Chapter(); chapter1.setChapterNo(1); chapter1.setTitle("Onidro Rojoni"); Chapter chapter2 = new Chapter(); chapter2.setChapterNo(2); chapter2.setTitle("Jongole Ami"); Book book = new Book(); book.setName("Runita"); book.addChapter(chapter1); book.addChapter(chapter2); return bookRepository.save(book); } public Object findById(Long bookId) { return bookRepository.findById(bookId); } public Object addWriters() { Writer humayun = new Writer(); humayun.setName("Humayun Ahmed"); Writer jafor = new Writer(); jafor.setName("Jafor Iqbal"); Writer brown = new Writer(); brown.setName("Dawn Brown"); Writer mitchel = new Writer(); mitchel.setName("Tom Mitchel"); Book book1 = new Book(); book1.setName("Book 1"); Set<Writer> book1Writer = new HashSet<>(); book1Writer.add(humayun); book1Writer.add(jafor); book1.setWriters(book1Writer); Book book2 = new Book(); book2.setName("Book 2"); Set<Writer> book2Writer = new HashSet<>(); book2Writer.add(jafor); book2Writer.add(brown); book2Writer.add(mitchel); book2.setWriters(book2Writer); Book book3 = new Book(); book3.setName("Book 3"); Set<Writer> book3Writer = new HashSet<>(); book3Writer.add(humayun); book3Writer.add(brown); book3.setWriters(book1Writer); List<Book> savedBook = new ArrayList<>(); savedBook.add(bookRepository.save(book1)); savedBook.add(bookRepository.save(book2)); savedBook.add(bookRepository.save(book3)); return savedBook; } }
package wangyi; import java.util.Scanner; public class LeastMajorityMul { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s = sc.nextLine(); String[] strs = s.split(","); int[] arr = new int[5]; for (int i = 0; i < arr.length; i++) { arr[i] = Integer.valueOf(strs[i]); } int n = 1; int count = 0; while(n > 0){ for (int i = 0; i < arr.length; i++) { if(n % arr[i] == 0) count++; } if (count >= 3) break; count = 0; //要记录每个n能够被五个数中的几个整除,,所以每循环一次都要置为0 n++; } System.out.println(n); } }
package com.zc.schedule.product.manager.entity; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Date; /** * 班次实体类 * * @author Justin * @version v1.0 */ public class WorkBean implements Serializable { private static final long serialVersionUID = -887023189657210078L; /** * 班次id */ private Integer workId; /** * 班次名称 */ private String workName; /** * 定义类型,默认值0:自定义 */ private String defineType; /** * 班次类型,默认值0:工作1:其他 2:正常休息 3:非工作 */ private String workType; /** * 总时间小时 */ private String totalTime; /** * 起止时间 */ private String time_interval; /** * 班次配色,存放16进制颜色值 */ private String workColour; /** * 班次是否使用,0:否/1:是 */ private String workStatus; /** * 班次状态,0:无效/1:有效 */ private String status; /** * 每日次数 */ private Integer count; /** * 创建时间 */ private Date creationTime; /** * 创建人 */ private Integer creater; /** * 复制workid */ private Integer copyId; /** * 两头班 */ private String splitWork; /** * 班次页面显示位置 */ private String left; private String width; public Integer getWorkId() { return workId; } public void setWorkId(Integer workId) { this.workId = workId; } public String getWorkName() { return workName; } public void setWorkName(String workName) { this.workName = workName; } public String getDefineType() { return defineType; } public void setDefineType(String defineType) { this.defineType = defineType; } public String getWorkType() { return workType; } public void setWorkType(String workType) { this.workType = workType; } public String getTime_interval() { return time_interval; } public void setTime_interval(String time_interval) { this.time_interval = time_interval; } public String getWorkColour() { return workColour; } public void setWorkColour(String workColour) { this.workColour = workColour; } public String getWorkStatus() { return workStatus; } public void setWorkStatus(String workStatus) { this.workStatus = workStatus; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public Integer getCount() { return count; } public void setCount(Integer count) { this.count = count; } public Date getCreationTime() { if (creationTime != null) { return (Date)creationTime.clone(); } else { return null; } } public void setCreationTime(Date creationTime) { if (creationTime != null) { this.creationTime = (Date)creationTime.clone(); } else { this.creationTime = null; } } public Integer getCreater() { return creater; } public void setCreater(Integer creater) { this.creater = creater; } public Integer getCopyId() { return copyId; } public void setCopyId(Integer copyId) { this.copyId = copyId; } public String getTotalTime() { return totalTime; } public void setTotalTime(String totalTime) { this.totalTime = totalTime; } public String getLeft() { return left; } public void setLeft(String left) { this.left = left; } public String getWidth() { return width; } public void setWidth(String width) { this.width = width; } public String getSplitWork() { return splitWork; } public void setSplitWork(String splitWork) { this.splitWork = splitWork; } public Object deepClone() throws Exception { // 序列化 ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(this); // 反序列化 ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bis); return ois.readObject(); } }
package team; import iron_man.*; /** * Write a description of class Sportsmen here. * * @author (your name) * @version (a version number or a date) */ public class Team1 extends Sportsmen implements Runable,Swimable,Bikeable { private int swim_limit; private int run_limit; private int bike_limit; private boolean neproshel; public Team1(String name) { this.name = name; this.run_limit = 50; swim_limit = 5; this.bike_limit = 190; this.neproshel=true; } @Override public boolean doIt (Sportsmen sportsmen){ neproshel=false; return true; } @Override public boolean swim(int b) { return swim_limit >= b; } @Override public boolean run(int a) { return run_limit >= a; } @Override public boolean bike(int c) { return bike_limit >= c; } @Override public void info(){ System.out.println(name+" result: " +run_limit+" "+swim_limit+" "+bike_limit); } }
/* * (c) Copyright 2001-2007 PRODAXIS, S.A.S. All rights reserved. * PRODAXIS PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ package com.prodaxis.junitgenerator.utils; import org.eclipse.core.runtime.CoreException; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.search.SearchMatch; import org.eclipse.jdt.core.search.SearchRequestor; import org.eclipse.jdt.internal.core.ResolvedSourceType; public class CompilationUnitRequestor extends SearchRequestor { private ICompilationUnit compilationUnit; public void acceptSearchMatch(SearchMatch match) throws CoreException { try { if (match.getElement() instanceof ResolvedSourceType) { ResolvedSourceType resolvedSourceType = (ResolvedSourceType) match.getElement(); compilationUnit = resolvedSourceType.getCompilationUnit(); } } catch (Exception exception) { } } public ICompilationUnit getCompilationUnit() { return compilationUnit; } }
package com.alibaba.druid.bvt.filter; import com.alibaba.druid.PoolTestCase; import junit.framework.TestCase; import org.junit.Assert; import com.alibaba.druid.filter.encoding.EncodingConvertFilter; import com.alibaba.druid.filter.stat.StatFilter; import com.alibaba.druid.pool.DruidDataSource; public class ClearFilterTest extends PoolTestCase { public void test_filters() throws Exception { DruidDataSource dataSource = new DruidDataSource(); Assert.assertEquals(0, dataSource.getProxyFilters().size()); dataSource.setFilters("encoding"); Assert.assertEquals(1, dataSource.getProxyFilters().size()); dataSource.setFilters("!stat"); Assert.assertEquals(1, dataSource.getProxyFilters().size()); Assert.assertEquals(StatFilter.class.getName(), dataSource.getFilterClassNames().get(0)); dataSource.setClearFiltersEnable(false); dataSource.setFilters("!encoding"); Assert.assertEquals(StatFilter.class.getName(), dataSource.getFilterClassNames().get(0)); Assert.assertEquals(EncodingConvertFilter.class.getName(), dataSource.getFilterClassNames().get(1)); dataSource.setConnectionProperties("druid.clearFiltersEnable=false"); Assert.assertFalse(dataSource.isClearFiltersEnable()); dataSource.setConnectionProperties("druid.clearFiltersEnable=true"); Assert.assertTrue(dataSource.isClearFiltersEnable()); dataSource.setConnectionProperties("druid.clearFiltersEnable=xx"); // no change Assert.assertTrue(dataSource.isClearFiltersEnable()); dataSource.close(); } }
/****************************************************************************** * __ * * <-----/@@\-----> * * <-< < \\// > >-> * * <-<-\ __ /->-> * * Data / \ Crow * * ^ ^ * * info@datacrow.net * * * * This file is part of Data Crow. * * Data Crow is free software; you can redistribute it and/or * * modify it under the terms of the GNU General Public * * License as published by the Free Software Foundation; either * * version 3 of the License, or any later version. * * * * Data Crow is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * See the GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public * * License along with this program. If not, see http://www.gnu.org/licenses * * * ******************************************************************************/ package net.datacrow.core.web.beans; import java.util.List; import javax.faces.event.ActionEvent; import net.datacrow.core.resources.DcResources; import net.datacrow.core.web.DcSecured; import org.apache.myfaces.custom.navmenu.NavigationMenuItem; import org.apache.myfaces.custom.navmenu.jscookmenu.HtmlCommandJSCookMenu; public abstract class DcBean extends DcSecured { public abstract String current(); public abstract String back(); public abstract List<NavigationMenuItem> getMenuItems(); public abstract String getActionListener(); protected void addLogoffMenuItem(List<NavigationMenuItem> menu) { NavigationMenuItem user = getMenuItem(DcResources.getText("lblUser"), null, null); user.add(getMenuItem(DcResources.getText("lblLogoff"), "#{security.logoff}", "logoff.png")); menu.add(user); } protected NavigationMenuItem getMenuItem(String label, String action, String icon) { NavigationMenuItem item = new NavigationMenuItem(label, action); item.setActionListener(getActionListener()); item.setValue(label); if (icon != null) item.setIcon("images/" + icon); return item; } public String actionListener(ActionEvent event) { return (String) ((HtmlCommandJSCookMenu) event.getComponent()).getValue(); } }
package gov.nih.mipav.model.file; import gov.nih.mipav.model.structures.*; import gov.nih.mipav.view.dialogs.*; /** * File information related to the Bruker/Biospin scanner format. */ public class FileInfoBRUKER extends FileInfoBase { //~ Static fields/initializers ------------------------------------------------------------------------------------- /** Use serialVersionUID for interoperability. */ private static final long serialVersionUID = 292865443840539139L; //~ Instance fields ------------------------------------------------------------------------------------------------ /** Whether the z resolution is set in the acqp or reco files*/ private boolean haveZResol = false; /** The size of the reconstruction */ private int recoSize = -1; /** The slice inversion time of the scan */ private String sliceSeparationMode = null; /** The inversion time of an MR scan. */ private double inversionTime; //~ Constructors --------------------------------------------------------------------------------------------------- /** * File info storage constructor. * * @param name file name * @param directory directory * @param format file format */ public FileInfoBRUKER(String name, String directory, int format) { super(name, directory, format); } //~ Methods -------------------------------------------------------------------------------------------------------- /** * Displays the file information. * * @param dlog dialog box that is written to * @param matrix transformation matrix */ public void displayAboutInfo(JDialogBase dlog, TransMatrix matrix) { JDialogText dialog = (JDialogText) dlog; displayPrimaryInfo(dialog, matrix); dialog.append("\n\n Other information\n\n"); if (sliceSeparationMode != null) { dialog.append("Slice separation mode:\t" + sliceSeparationMode + "\n"); } if (getSliceThickness() > 0.0f) { dialog.append("Slice thickness:\t" + getSliceThickness() + " mm\n"); } if(inversionTime != 0) { dialog.append("Inversion time:\t\t" + inversionTime + " ms\n"); } } /** * Accessor to get the flag for having a z resolution. * * @return <code>true</code> if has a z resolution. */ public boolean getHaveZResol() { return haveZResol; } /** * Gets the size of the reconstruction. * * @return The reco size. */ public int getRecoSize() { return recoSize; } /** * Gets the inversion time of the scan. * * @return The inversion time. */ public double getInversionTime() { return inversionTime; } /** * Accessor to set the flag for having a z resolution. * * @param haveZResol Flag to set. */ public void setHaveZResol(boolean haveZResol) { this.haveZResol = haveZResol; } /** * Accessor to set the reco size. * * @param recoSize Value to set. */ public void setRecoSize(int recoSize) { this.recoSize = recoSize; } /** * Accessor to set the slice separation mode. * * @param sliceSeparationMode Value to set. */ public void setSliceSeparationMode(String sliceSeparationMode) { this.sliceSeparationMode = sliceSeparationMode; } /** * Accessor to set the inversion time of the scan * * @param inversionTime the inversion time of the scan */ public void setInversionTime(double inversionTime) { this.inversionTime = inversionTime; } }
package regularExpresions; import java.util.regex.Matcher; import java.util.regex.Pattern; public class chal1 { public static void main(String[] args) { String challenge1 = "I want a bike"; String challenge2 = "I want a ball"; System.out.println(challenge1.matches("I want a bike")); String regExp = "I want a \\w+."; System.out.println(challenge2.matches(regExp)); String regexp1 = "I want a (bike|ball)"; System.out.println(challenge2.matches(regExp)); System.out.println(challenge2.matches(regexp1)); String regExp3= "I want a \\w+."; Pattern pattern= Pattern.compile(regExp3); Matcher matcher= pattern.matcher(challenge1); System.out.println(matcher.matches()); matcher = pattern.matcher(challenge2); System.out.println(matcher.matches() ); String challenge4= "Replace all blanks with underscore."; System.out.println(challenge1.replaceAll(" ","_")); System.out.println(challenge4.replaceAll("\\s","_")); String challenge5 ="aaabccccccccefffg"; System.out.println(challenge5.matches("[abcdefg]+")); System.out.println(challenge5.matches("[a-g]+")); System.out.println(challenge5.matches("^a{3}bc{8}d{3}ef{3}g$")); String challenge7 ="abcd.135"; System.out.println(challenge7.matches("^[A-z][a-z]+\\.\\d+$")); String challenge8="abcd.135uvqz.7tzik.999"; Pattern pattern8 = Pattern.compile("[A-Za-z]+\\.(\\d+)"); Matcher matcher8 = pattern8.matcher(challenge8); while(matcher8.find()){ System.out.println("Occurence + "+matcher8.group(1)); } String challenge9="abcd.135\tuvqz.7\ttzik.999\n"; Pattern pattern9 = Pattern.compile("[A-Za-z]+\\.(\\d)\\s"); Matcher matcher9 = pattern9.matcher(challenge9); while(matcher9.find()){ System.out.println("Occurence + "+matcher9.group(1)); } String challenge11 ="{0,2},{0,5},{1,3},{2,4}"; Pattern pattern11 = Pattern.compile("\\{(.+?)\\}"); Matcher matcher11 = pattern11.matcher(challenge11); while(matcher11.find()){ System.out.println("Occurance "+matcher11.group(1)); } System.out.println("000000000000"); String challenge11a ="{0,2},{0,5},{1,3},{2,4} {x,y}, {2,4}"; Pattern pattern11a = Pattern.compile("\\{(\\d+, \\d+)\\}"); Matcher matcher11a = pattern11a.matcher(challenge11a); while(matcher11a.find()){ System.out.println("Occurance "+matcher11a.group(1)); } String challenge12 ="11111"; System.out.println(challenge12.matches("^\\d{5}$")); String challenge13 ="11111-1111"; System.out.println(challenge13.matches("^\\d{5}-\\d{4}$")); System.out.println(challenge12.matches("^\\d{5}(-\\d{4})?$")); } }
package com.fhsoft.system.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.fhsoft.base.bean.Page; import com.fhsoft.model.Role; import com.fhsoft.model.TreeNodeBean; import com.fhsoft.model.Users; import com.fhsoft.system.dao.UserRoleDao; @Service("userRoleService") public class UserRoleService { @Autowired private UserRoleDao userRoleDao; public Page userList(int page,int pageRows,String name,String created){ return userRoleDao.userList(page, pageRows, name, created); } public void saveUser(Users user) { userRoleDao.saveUser(user); } public void userUpdate(Users user) { userRoleDao.userUpdate(user); } public void deleteUser(Users user) { userRoleDao.deleteUser(user); } public Page roleList(int page,int pageRows){ return userRoleDao.roleList(page, pageRows); } public Role getRoleInfoById(Integer id){ return userRoleDao.getRoleInfoById(id); } public void saveRole(Role role) { userRoleDao.saveRole(role); } public void deleteRole(Role role) { userRoleDao.deleteRole(role); } public List<TreeNodeBean> getRoles(int userId) { return userRoleDao.getRoles(userId); } public void saveUserRole(int userId, String roleIds){ userRoleDao.saveUserRole(userId, roleIds); } public List<TreeNodeBean> getRoleMenuTree(int roleId,int level) { return userRoleDao.getRoleMenuTree(roleId,level); } public void saveRoleMenu(String roleId,String menuIds){ userRoleDao.saveUserRole(roleId, menuIds); } }
package cr.ac.tec.ce1103.structures.sort; /** * Clase maestra de todos los algoritmos de ordenaminto * @author Esteban Agüero Pérez * * @param <Tipo> */ public class SortingAlgorithm <Tipo extends Comparable>{ public static String[] inputArr1; private int heapSize; /** * Realiza ordenamiento BubbleSort * @param arreglo * @return arreglo ordenado */ public Tipo[] BubbleSort ( Tipo[] arreglo){ Tipo datoAuxiliar; boolean cambio; boolean bandera=true; while (bandera){ cambio=false; for (int i=1;i<arreglo.length;i++){ int comparacion = arreglo[i].compareTo(arreglo[i-1]); if (comparacion < 0){ datoAuxiliar=arreglo[i]; //guarda el valor antes del swap arreglo[i]=arreglo[i-1]; arreglo[i-1]=datoAuxiliar; cambio=true; } } if (!cambio){break;}//si es false osea no hubo cambios } return arreglo; //Esta de mas ya que el metodo modifica el arreglo original } /** * Realiza ordenamiento SelectionSort * @param arreglo */ public void SelectionSort(Tipo[] arreglo){ int min; for(int i=0; i< arreglo.length; i++){ min=i; for(int j=i+1; j<arreglo.length; j++){ if(arreglo[j].compareTo(arreglo[min])<0){ min=j; } } if(min != i){ final Tipo temp = arreglo[i]; arreglo[i] = arreglo[min]; arreglo[min] = temp; } } } /** * Realiza el ordenamiento InsertionSort * @param arreglo */ public void InsertionSort(Tipo[] arreglo){ Tipo temp; int i; for (int j = 1; j < arreglo.length; j++ ){ temp = arreglo[j]; i = j-1; while ((i>-1)&& (arreglo[i].compareTo(temp) > 0)){ arreglo[i+1] = arreglo[i]; i = i-1; } arreglo[i+1] = temp; } } /** * Realiza ordenamiento QuickSort * @param arreglo */ public void QuickSort ( Tipo[] arreglo){ arreglo=quickSortAux(arreglo,0,arreglo.length-1); //Es el indice maximo y es -1 por que empieza en 0 no en 1 } /** * Metodo Auxiliar del QuickSort * @param nuevoArreglo * @param izquierda * @param derecha * @return */ private Tipo[] quickSortAux ( Tipo[] nuevoArreglo, int izquierda, int derecha){ if (izquierda>=derecha){return nuevoArreglo;} //Quiere decir que el puntero derecho y el puntero izquierdo estan en el mismo lugar int der=derecha,izq=izquierda; //Se hacen nuevos apuntadores para mas adelante poder delimitar los nuevos arreglos if (izquierda!=derecha){ Tipo elementoAux; int pivote=izquierda; //se toma arbitrariamente para empezar a comparar con la lista while (izquierda!=derecha){ while (nuevoArreglo[derecha].compareTo(nuevoArreglo[pivote])>=0 && izquierda<derecha){ derecha--; } while (nuevoArreglo[izquierda].compareTo(nuevoArreglo[pivote])<0 && izquierda<derecha){ izquierda++; } if (derecha!=izquierda){ elementoAux= nuevoArreglo[derecha]; nuevoArreglo[derecha]=nuevoArreglo[izquierda]; nuevoArreglo[izquierda]=elementoAux; } } if (izquierda==derecha){ quickSortAux(nuevoArreglo, izq, izquierda-1); quickSortAux(nuevoArreglo, izquierda+1, der); } } else{ return nuevoArreglo; } return nuevoArreglo; } /** * Realiza ordenamiento HeapSort * @param arreglo */ public void HeapSort(Tipo[] arreglo){ BUILD_MAX_HEAP(arreglo); for(int i=arreglo.length-1;i>=0;i--){ Tipo temp = arreglo[0]; arreglo[0]=arreglo[i]; arreglo[i]=temp; heapSize = heapSize-1; MAX_HEAPIFY(arreglo,0); } } /** * Metodo auxiliar * @param i * @return */ private int LEFT(int i){return 2*i+1;} /** * Metodo auxiliar * @param i * @return */ private int RIGHT(int i){return 2*i+2;} /** * Metodo auxiliar * @param arreglo */ private void BUILD_MAX_HEAP (Tipo[] arreglo){ heapSize=arreglo.length; for(int i=arreglo.length/2; i>=0;i--) { MAX_HEAPIFY(arreglo, i); } } /** * Metodo auxiliar * @param arreglo * @param i */ private void MAX_HEAPIFY(Tipo[] arreglo,int i) { int l=LEFT(i); int r=RIGHT(i); int largestElementIndex = -1; if(l<heapSize && arreglo[l].compareTo(arreglo[i])>0){ largestElementIndex = l; } else{ largestElementIndex=i; } if(r<heapSize && arreglo[r].compareTo(arreglo[largestElementIndex])>0){ largestElementIndex = r; } if(largestElementIndex!=i) { Tipo temp = arreglo[i]; arreglo[i]=arreglo[largestElementIndex]; arreglo[largestElementIndex]=temp; MAX_HEAPIFY(arreglo, largestElementIndex); } } public void mergeSort(Comparable [ ] a) { Comparable[] tmp = new Comparable[a.length]; mergeSort(a, tmp, 0, a.length - 1); } private void mergeSort(Comparable [ ] a, Comparable [ ] tmp, int left, int right) { if( left < right ) { int center = (left + right) / 2; mergeSort(a, tmp, left, center); mergeSort(a, tmp, center + 1, right); merge(a, tmp, left, center + 1, right); } } private void merge(Comparable[ ] a, Comparable[ ] tmp, int left, int right, int rightEnd ) { int leftEnd = right - 1; int k = left; int num = rightEnd - left + 1; while(left <= leftEnd && right <= rightEnd) if(a[left].compareTo(a[right]) <= 0) tmp[k++] = a[left++]; else tmp[k++] = a[right++]; while(left <= leftEnd) // Copy rest of first half tmp[k++] = a[left++]; while(right <= rightEnd) // Copy rest of right half tmp[k++] = a[right++]; // Copy tmp back for(int i = 0; i < num; i++, rightEnd--) a[rightEnd] = tmp[rightEnd]; } /** * Crea arreglos aleatorios * @param N * @return */ public Integer[] RandomArray(int N){ Integer[] arreglo= new Integer[N]; for(int i=0; i<arreglo.length; i++){ arreglo[i] = (int)(Math.random()*100); } return arreglo; } }
package com.git.cloud.bill.service; import java.util.List; import java.util.Map; import com.git.cloud.bill.model.vo.BillInfoVo; import com.git.cloud.bill.model.vo.BillPageParamVo; import com.git.cloud.bill.model.vo.OrderRoot; import com.git.cloud.bill.model.vo.VariableVOs; import com.git.cloud.common.exception.RollbackableBizException; import com.git.cloud.common.support.Pagination; import com.git.cloud.common.support.PaginationParam; import com.git.cloud.tenant.model.po.TenantPo; public interface BillService { /** * 构建订单信息 * @param map * @return * @throws Exception */ public OrderRoot buildOrderData(Map<String,String> map) throws Exception; /** * 根据传递的参数,调用生成订单的接口 * @param orderRoot * @return */ public String createOrderInterface(OrderRoot orderRoot) throws RollbackableBizException; /** * 显示账单信息 */ public Pagination<BillInfoVo> buildBillingPage(PaginationParam paginationParam) throws Exception; /** * 查询账单列表 * @param billPageParam * @return * @throws RollbackableBizException */ public Pagination<BillInfoVo> buildBillingList(BillPageParamVo billPageParam)throws RollbackableBizException; /** * 详单查询 * @param paginationParam * @return * @throws Exception */ Pagination<BillInfoVo> buildBillingDetailPage(PaginationParam paginationParam) throws Exception; /** * 代金券列表 * @param paginationParam * @return * @throws Exception */ Pagination<BillInfoVo> buildBillingVoucherPage(PaginationParam paginationParam) throws Exception; /** * 充值记录列表 * @param paginationParam * @return * @throws Exception */ Pagination<BillInfoVo> buildFundSerialPage(PaginationParam paginationParam) throws Exception; Pagination<TenantPo> queryTenantBalancePage(PaginationParam paginationParam)throws Exception; /** * 查询账户余额 * @param tenantId * @return * @throws Exception */ public int queryAccountBalance(String tenantId)throws Exception; /** * 账户充值 * @param tenantId * @param amount 前台传递的是元,需要转化为厘 * @param busiDesc * @return * @throws Exception */ public String accountRecharge(String tenantId,String amount,String busiDesc,String fundTypeCode)throws Exception; /** * 保存或修改定价接口 * @param jsonParameter * @throws Exception */ public String priceElementAddOrUpdate(String jsonParameter)throws Exception; /** * 查询策略 * @param policyId * @return * @throws Exception */ public Pagination<VariableVOs> queryPriceStrategyById(PaginationParam pagination)throws Exception; /** 获取定价审批信息 */ @SuppressWarnings("rawtypes") public Pagination<Map> queryBmSrRrinfoPriceApproval(PaginationParam pagination) throws Exception; /** * 根据子产品id查询主产品下子产品,主要是为了获取子产品名称categoryName,在页面上显示用 * @param categoryId * @return * @throws Exception */ public String getSubProductInfo(String categoryId)throws Exception; /** * 查询可开发票总额 * @param tenantId * @return * @throws Exception */ public Pagination<TenantPo> queryTotalInvoicePage(PaginationParam paginationParam)throws Exception; /** * 查询租户的可开发票 * @param tenantId * @param billMonth * @return * @throws Exception */ public String queryTotalInvoice(String tenantId,String billMonth)throws Exception; }
package com.nikita.recipiesapp.views.steps; import android.view.View; import com.airbnb.epoxy.EpoxyAttribute; import com.airbnb.epoxy.EpoxyModelWithHolder; import com.nikita.recipiesapp.R; import com.nikita.recipiesapp.common.models.Step; import com.nikita.recipiesapp.views.common.TextViewHolder; class StepModel extends EpoxyModelWithHolder<TextViewHolder> { @EpoxyAttribute Step step; @EpoxyAttribute boolean isSelected; @EpoxyAttribute View.OnClickListener clickListener; @Override protected TextViewHolder createNewHolder() { return new TextViewHolder(); } @Override protected int getDefaultLayout() { return R.layout.step_list_step_item; } @Override public void bind(TextViewHolder holder) { super.bind(holder); holder.text.setText(step.shortDescription); holder.text.setSelected(isSelected); holder.text.setOnClickListener(clickListener); } }
package rong.hngyan.cat; public class show { public static void main(String[] args) { //对象实例化 //Cat one=new Cat("花花",2,1000,"英国短毛猫"); ca one = new ca(); one.setName("花花"); System.out.println(one.month[4]); System.out.println("昵称:" + one.getName() + "\n" + "有" + one.month + "个月大"); } }
package com.gxtc.huchuan.ui.mine.circle; import com.gxtc.commlibrary.utils.ErrorCodeUtil; import com.gxtc.commlibrary.utils.FileUtil; import com.gxtc.commlibrary.utils.GsonUtil; import com.gxtc.commlibrary.utils.LogUtil; import com.gxtc.huchuan.MyApplication; import com.gxtc.huchuan.bean.ChannelBean; import com.gxtc.huchuan.bean.UploadFileBean; import com.gxtc.huchuan.bean.UploadResult; import com.gxtc.huchuan.data.CircleRepository; import com.gxtc.huchuan.data.CircleSource; import com.gxtc.huchuan.data.UserManager; import com.gxtc.huchuan.http.ApiCallBack; import com.gxtc.huchuan.http.ApiObserver; import com.gxtc.huchuan.http.ApiResponseBean; import com.gxtc.huchuan.http.LoadHelper; import com.gxtc.huchuan.http.service.MineApi; import com.upyun.library.common.Params; import com.upyun.library.common.UploadEngine; import com.upyun.library.listener.UpCompleteListener; import com.upyun.library.listener.UpProgressListener; import com.upyun.library.utils.UpYunUtils; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import cn.edu.zafu.coreprogress.listener.impl.UIProgressListener; import okhttp3.MediaType; import okhttp3.MultipartBody; import okhttp3.RequestBody; import rx.Observable; import rx.Subscriber; import rx.Subscription; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Func1; import rx.schedulers.Schedulers; import top.zibin.luban.Luban; import static com.gxtc.huchuan.ui.circle.dynamic.IssueDynamicActivity.maxLen_500k; public class IssueArticlePresenter implements IssueArticleContract.Presenter { private IssueArticleContract.View mView; private CircleSource mData; public IssueArticlePresenter(IssueArticleContract.View mView) { this.mView = mView; this.mView.setPresenter(this); mData = new CircleRepository(); } @Override public void start() { } @Override public void destroy() { mData.destroy(); mView = null; if(uploadSub != null) uploadSub.unsubscribe(); } @Override public void getArticleType() { mView.showLoad(); mData.getArticleType(new ApiCallBack<ChannelBean>() { @Override public void onSuccess(ChannelBean data) { if(mView == null) return; mView.showLoadFinish(); data.getDefaultX().remove(0); String[] items = new String[data.getDefaultX().size() + data.getNormal().size()]; List<ChannelBean.NormalBean> beans = new ArrayList<ChannelBean.NormalBean>(); int k = 0; for (int i = 0; i < data.getDefaultX().size(); i++) { ChannelBean.DefaultBean bean = data.getDefaultX().get(i); items[i] = bean.getNewstypeName(); beans.add(new ChannelBean.NormalBean(bean.getNewstypeId(), bean.getNewstypeName())); k++; } for (int i = 0; i < data.getNormal().size(); i++) { ChannelBean.NormalBean bean = data.getNormal().get(i); items[k] = bean.getNewstypeName(); beans.add(new ChannelBean.NormalBean(bean.getNewstypeId(), bean.getNewstypeName())); k++; } mView.showArticleType(items, beans); } @Override public void onError(String errorCode, String message) { ErrorCodeUtil.handleErr(mView, errorCode, message); } }); } private Subscription uploadSub; @Override public void uploadingFile(final String id, String path) { LogUtil.i("原图路径: " + path); LogUtil.i("img id : " + id); //将图片进行压缩 final File file = new File(path); uploadSub = Luban.get(MyApplication.getInstance()).load(file) //传人要压缩的图片 .putGear(Luban.THIRD_GEAR) //设定压缩档次,默认三挡 .asObservable() .subscribeOn(Schedulers.io()) .map(new Func1<File, File>() { @Override public File call(File compressFile) { if(FileUtil.getSize(file) > maxLen_500k ){ return compressFile; }else { return file; } } }) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Subscriber<File>() { @Override public void onCompleted() {} @Override public void onError(Throwable e) { mView.showUploadingFailure("上传图片失败"); } @Override public void onNext(File file) { LoadHelper.uploadFile(LoadHelper.UP_TYPE_IMAGE, new LoadHelper.UploadCallback() { @Override public void onUploadSuccess(UploadResult result) { if(mView == null) return; mView.showUploadingSuccess(id, result.getUrl()); } @Override public void onUploadFailed(String errorCode, String msg) { ErrorCodeUtil.handleErr(mView, errorCode, msg); } }, null, file); } }); } @Override public void uploadingVideo(final String id, String path) { File file = new File(path); LoadHelper.uploadFile(LoadHelper.UP_TYPE_VIDEO, new LoadHelper.UploadCallback() { @Override public void onUploadSuccess(UploadResult result) { if(mView == null) return; mView.showUploadVideoSuccess(id, result.getUrl()); } @Override public void onUploadFailed(String errorCode, String msg) { if(mView != null){ mView.showUploadVideoFailure(msg); } } },new UIProgressListener() { @Override public void onUIProgress(long currentBytes, long contentLength, boolean done) { LogUtil.i("bytesWrite : " + currentBytes + " contentLength : " + contentLength); } }, file); } @Override public void issueArticle(HashMap<String, String> map) { if(mView == null) return; mView.showLoad(); mData.issueArticle(map, new ApiCallBack<Object>() { @Override public void onSuccess(Object data) { if(mView == null) return; mView.showLoadFinish(); mView.showIssueSuccess(); } @Override public void onError(String errorCode, String message) { ErrorCodeUtil.handleErr(mView,errorCode,message); } }); } }
package org.fiery.md.preview.actions; import com.intellij.openapi.editor.Document; import org.apache.commons.lang.StringEscapeUtils; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import java.io.IOException; public class GithubMarkdownHelper { private static final String MARKDOWN_HTML_WRAPPER_START = "<!DOCTYPE html>\n" + "<html lang=\"en\">\n" + "<head>\n" + " <meta charset=\"utf-8\">\n" + " <title>%1$s</title>\n" + " <link crossorigin=\"anonymous\" href=\"https://assets-cdn.github.com/assets/frameworks-a2a1ae24a31177c689f6ec6d0f320684962f572ef60a84b385ec47dd00c06b38.css\" integrity=\"sha256-oqGuJKMRd8aJ9uxtDzIGhJYvVy72CoSzhexH3QDAazg=\" media=\"all\" rel=\"stylesheet\">\n" + " <link crossorigin=\"anonymous\" href=\"https://assets-cdn.github.com/assets/github-1e541164394dd957f0ccaeb1a6b08b1064064d8491212bc28a3379907db2ef96.css\" integrity=\"sha256-HlQRZDlN2VfwzK6xprCLEGQGTYSRISvCijN5kH2y75Y=\" media=\"all\" rel=\"stylesheet\">\n " + "</head>\n" + "<body>" + "<div class=\"container new-discussion-timeline experiment-repo-nav\">\n" + " <div class=\"repository-content\">\n" + " <div id=\"readme\" class=\"readme boxed-group clearfix announce instapaper_body md\">\n" + " <h3>\n" + " <svg aria-hidden=\"true\" class=\"octicon octicon-book\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path d=\"M3 5h4v1H3V5zm0 3h4V7H3v1zm0 2h4V9H3v1zm11-5h-4v1h4V5zm0 2h-4v1h4V7zm0 2h-4v1h4V9zm2-6v9c0 .55-.45 1-1 1H9.5l-1 1-1-1H2c-.55 0-1-.45-1-1V3c0-.55.45-1 1-1h5.5l1 1 1-1H15c.55 0 1 .45 1 1zm-8 .5L7.5 3H2v9h6V3.5zm7-.5H9.5l-.5.5V12h6V3z\"></path></svg>\n" + " %1$s\n" + " </h3>\n" + "\n" + " <article class=\"markdown-body entry-content\" itemprop=\"text\">\n"; private static final String MARKDOWN_HTML_WRAPPER_END = "</article></div></div></div></body>"; public String toGitMarkdownHtml(String fileName, Document document) { try { return String.format(MARKDOWN_HTML_WRAPPER_START, StringEscapeUtils.escapeHtml(fileName)) + requestGitMarkdownHtml(document) + MARKDOWN_HTML_WRAPPER_END; } catch (IOException e) { throw new RuntimeException(e); } } private String requestGitMarkdownHtml(Document document) throws IOException { try (CloseableHttpClient httpClient = HttpClients.createDefault()) { HttpPost httpPost = createGettingMarkdownRequest(document); try (CloseableHttpResponse response = httpClient.execute(httpPost)) { switch (response.getStatusLine().getStatusCode()) { case 200: return EntityUtils.toString(response.getEntity()); default: throw new RuntimeException(response.getStatusLine().toString()); } } } } private HttpPost createGettingMarkdownRequest(Document document) { HttpPost httpPost = new HttpPost("https://api.github.com/markdown/raw"); StringEntity requestEntity = new StringEntity(document.getText(), ContentType.create("text/plain", "UTF-8")); httpPost.setEntity(requestEntity); httpPost.setConfig(RequestConfig.custom() .setSocketTimeout(200) .setConnectTimeout(200) .setConnectionRequestTimeout(300) .build()); return httpPost; } }
package com.appirio.service.member.api; import lombok.Setter; import lombok.Getter; /** * Represents the Max rating of the user across all stats * * @author mdesiderio@appirio.com * */ public class MaxRating { /** * The highest current rating of the user */ @Getter @Setter private Long rating; /** * The track in which the user has their current highest rating */ @Getter @Setter private String track; /** * The subtrack in which the user has their current highest rating */ @Getter @Setter private String subTrack; }
package com.wso2telco.dep.scope.handler.dto; public class InboundMessage { private ScopeValidationRequest scopeValidationRequest; public ScopeValidationRequest getScopeValidationRequest() { return scopeValidationRequest; } public void setScopeValidationRequest(ScopeValidationRequest scopeValidationRequest) { this.scopeValidationRequest = scopeValidationRequest; } }
package diplomski.autoceste.models; public enum VehicleCategory { I,IA,II, III, IV }
import java.util.*; import java.io.*; public class prob04 { public static void main(String[] args) throws IOException { // TODO Auto-generated method stub //Scanner in = new Scanner(System.in); Scanner in = new Scanner(new File("prob04-1-in.txt")); while (true) { double num = in.nextDouble(), pow = in.nextDouble(); if (num == 0 && pow == 0) break; System.out.printf("%.2f\n", num * Math.pow(10, pow)); } in.close(); } }
package com.facebook.fresco; import java.io.File; import java.lang.ref.WeakReference; import java.util.HashMap; import java.util.Random; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import com.base.utils.FileUtils; import com.base.utils.LogWriter; import com.base.utils.StringUtils; import com.facebook.common.references.CloseableReference; import com.facebook.datasource.BaseDataSubscriber; import com.facebook.datasource.DataSource; import com.facebook.drawee.backends.pipeline.Fresco; import com.facebook.drawee.controller.BaseControllerListener; import com.facebook.drawee.drawable.ScalingUtils; import com.facebook.drawee.generic.GenericDraweeHierarchy; import com.facebook.drawee.generic.RoundingParams; import com.facebook.drawee.interfaces.DraweeController; import com.facebook.drawee.view.SimpleDraweeView; import com.facebook.fresco.FrescoConfigConstants.ActualRatioControllerListener; import com.facebook.fresco.FrescoConfigConstants.FrescoPreHandleListener; import com.facebook.imagepipeline.animated.base.AnimatedImage; import com.facebook.imagepipeline.animated.base.AnimatedImageFrame; import com.facebook.imagepipeline.core.ImagePipeline; import com.facebook.imagepipeline.image.CloseableAnimatedImage; import com.facebook.imagepipeline.image.CloseableBitmap; import com.facebook.imagepipeline.image.CloseableImage; import com.facebook.imagepipeline.image.ImageInfo; import com.facebook.imagepipeline.request.ImageRequest; import com.wmlives.heihei.R; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Handler; import android.os.Looper; import android.util.Log; import android.view.View; import android.widget.ImageView; public class FrescoImageHelper { public static boolean log = false; /** * 通过图片URL获取本地缓存文件 * * @param image_net_url * @return */ public static File getImageDiskCacheFile(String image_net_url) { return FrescoConfigConstants.getImageDiskCacheFile(image_net_url); } public static File getAllImageDiskCacheFile() { return new File(FrescoConfigConstants.DISK_CACHE_DIR); } /** * 把一个本地图片添加成指定网络URL的图片缓存 * * @param localImgPath * 本地图片路径 * @param netImgUrl * 本地图片对应的网络地址 * @return 是否成功 */ public static boolean addDiskCacheFromLocalImg(String localImgPath, String netImgUrl) { boolean ret = false; String cachepath = null; try { if (!StringUtils.isEmpty(localImgPath) && !StringUtils.isEmpty(netImgUrl)) { File localFile = new File(localImgPath); if (localFile != null && localFile.exists()) { cachepath = FrescoConfigConstants.getImageDiskCachePath(netImgUrl); File cacheFile = new File(cachepath); if (cacheFile != null) { if (cacheFile.exists()) { ret = true; // netImgUrl对应的本地缓存文件已经存在 } else { FileUtils.fileChannelCopy(localFile, cacheFile);// 文件通道对拷 ret = cacheFile.exists();// copy是否成功 } } } } } catch (Exception e) { } // Log.e("cccmax", "addDiskCacheFromLocalImg ret=" + ret + "\n localImgPath=" + localImgPath + "\n netImgUrl=" // + netImgUrl + "\ncachepath=" + cachepath); return ret; } /** * 创建SimpleDraweeView * * @param context * @return */ public static SimpleDraweeView createView(Context context) { SimpleDraweeView view = new SimpleDraweeView(context, FrescoConfigConstants.getGenericDraweeHierarchy(context)); return view; } /** * 创建SimpleDraweeView * * @param context * @param hierarchy * @return */ public static SimpleDraweeView createView(Context context, GenericDraweeHierarchy hierarchy) { SimpleDraweeView view = new SimpleDraweeView(context, hierarchy); return view; } // /** // * 简单的获取图片 // * // * @param uri // * 图片地址 // * @param view // */ // public static void getImage(String uri, SimpleDraweeView view) // { // ImageRequest imageRequest = FrescoConfigConstants.getImageRequest(view, // uri); // DraweeController draweeController = // FrescoConfigConstants.getDraweeController(imageRequest, view); // view.setController(draweeController); // } // // /** // * 简单的获取图片 自定义控制器 // * // * @param uri // * 图片地址 // * @param view // * @param controllerlistener // * 控制器回调 // */ // public static void getImage(String uri, SimpleDraweeView view, // BaseControllerListener controllerlistener) // { // ImageRequest imageRequest = FrescoConfigConstants.getImageRequest(view, // uri); // DraweeController draweeController = // FrescoConfigConstants.getDraweeController(imageRequest, view, // controllerlistener); // view.setController(draweeController); // } /** * 获取图片 图片高度按真实比例设置(获取到图片后自动计算的) * * @param uri * 图片地址 * @param view */ public static void getImage_ChangeRatio(FrescoParam param, SimpleDraweeView view, float... ratio_max) { try { ActualRatioControllerListener l = new ActualRatioControllerListener(view); if (ratio_max != null && ratio_max.length > 0) l.ratio_max = ratio_max[0]; getImage(param, view, l); } catch (Exception e) { e.printStackTrace(); } } /** * 获取图片 加载到SimpleDraweeView中,支持Gif图片,自动释放内存 * * @param param * @param view * 需要用SimpleDraweeView来替代ImageView * @param controllerlistener * 加载图片的特殊操作可以在这里加,例如ActualRatioControllerListener */ public static void getImage(FrescoParam param, SimpleDraweeView view, FrescoPreHandleListener controllerlistener) { if (param == null) return; // 服务器假数据图片地址不对 // param.setURI(param.getURI().replace("http://10.9.57.202:9000/", "")); try { // 设置圆角、圆形 ,gif无效 RoundingParams rp = view.getHierarchy().getRoundingParams(); if (!param.isNoRoundingParams()) { if (rp == null) rp = new RoundingParams(); rp.setRoundAsCircle(param.getRoundAsCircle()); if (!param.getRoundAsCircle()) { rp.setCornersRadii(param.getRadius_TL(), param.getRadius_TR(), param.getRadius_BR(), param.getRadius_BL()); } view.getHierarchy().setRoundingParams(rp); } // 设置描边颜色、宽度 if (param.getBordeWidth() >= 0 && rp != null) { rp.setBorder(param.getBordeColor(), param.getBordeWidth()); view.getHierarchy().setRoundingParams(rp); } // 默认图片(占位图) if (param.DefaultImageID > 0) { view.getHierarchy().setPlaceholderImage(param.DefaultImageID); // view.getHierarchy().setPlaceholderImage(view.getContext().getResources().getDrawable(param.DefaultImageID), // param.scaletype); } // view缩放模式 view.getHierarchy().setActualImageScaleType(param.scaletype); // scaletype模式的焦点 if (param.scaleFocusPoint != null) view.getHierarchy().setActualImageFocusPoint(param.scaleFocusPoint); // 请求 ImageRequest imageRequest = FrescoConfigConstants.getImageRequest(view, param.getURI()); // 图片请求log 包括 分辨率、比例、uri // if (controllerlistener == null) { // final String uri = param.getURI(); // controllerlistener = new BaseControllerListener<Object>() { // // public void onFinalImageSet(String id, Object imageInfo, Animatable animatable) { // if (imageInfo != null && imageInfo instanceof ImageInfo) { // boolean isGif = CloseableAnimatedImage.class.isInstance(imageInfo); // ImageInfo ii = (ImageInfo) imageInfo; // int width = ii.getWidth(); // int height = ii.getHeight(); // float ratio = width * 1.0F / (height == 0 ? width : height); // LogUtil.i("fresco", "BaseControllerListener onFinalImageSet w=" + width + " h=" + height // + " isGif=" + isGif + " ratio=" + ratio + " -----URI=" + uri); // } // }; // }; // } DraweeController draweeController = null; if (controllerlistener == null) { // draweeController = FrescoConfigConstants.getDraweeController(imageRequest, // param.getClickToRetryEnabled(), view); // 加一个默认处理 其中有必要的Resize处理 controllerlistener = new FrescoPreHandleListener(view) { public void handle(ImageInfo ii, boolean isgif, int w, int h, float _ratio) {} }; draweeController = FrescoConfigConstants.getDraweeController(imageRequest, param.getClickToRetryEnabled(), view, controllerlistener); } else { draweeController = FrescoConfigConstants.getDraweeController(imageRequest, param.getClickToRetryEnabled(), view, controllerlistener); } view.setController(draweeController); } catch (Exception e) { LogWriter.e("fresco", "getImage exception"); } } /** * 单纯的请求图片和view无关,加回调后可以做自定义操作 * * @param param * @param callback * 请求图片回调 * @param onUIcallback * 是否在UI线程执行callback */ public static void getImage(FrescoParam param, CloseableImageCallback callback, boolean onUIcallback) { try { ImageRequest imageRequest = FrescoConfigConstants.getImageRequest(null, param.getURI()); ImagePipeline imagePipeline = Fresco.getImagePipeline(); DataSource<CloseableReference<CloseableImage>> dataSource = imagePipeline.fetchDecodedImage(imageRequest, null); FrescoBaseDataSubscriber dataSubscriber = new FrescoBaseDataSubscriber(callback, onUIcallback); dataSource.subscribe(dataSubscriber, getExecutor()); } catch (Exception e) { LogWriter.e("fresco", "getImage CloseableImageCallback exception"); } } /** * 从bitmap内存缓存中获取 * * @param param * @return */ public static Bitmap getMemoryCachedImage(FrescoParam param) { ImageRequest imageRequest = FrescoConfigConstants.getImageRequest(null, param.getURI()); DataSource<CloseableReference<CloseableImage>> dataSource = Fresco.getImagePipeline() .fetchImageFromBitmapCache(imageRequest, null); CloseableReference<CloseableImage> imageReference = null; try { imageReference = dataSource.getResult(); if (imageReference != null) { CloseableImage image = imageReference.get(); // do something with the image if (image instanceof CloseableBitmap) { return ((CloseableBitmap) image).getUnderlyingBitmap(); } } } finally { dataSource.close(); CloseableReference.closeSafely(imageReference); } return null; } /** * 从disk缓存中获取图片 * * @param param * @return */ public static Bitmap getDiskCachedImage(FrescoParam param) { try { File file = getImageDiskCacheFile(param.getURI()); if (file != null) { BitmapFactory.Options newOpts = new BitmapFactory.Options(); newOpts.inJustDecodeBounds = true; BitmapFactory.decodeFile(file.getAbsolutePath(), newOpts); int w = newOpts.outWidth; int h = newOpts.outHeight; float hh = 1024; float ww = 1024; int SCALE = 1; if (w > h && w > ww) {// 如果宽度大的话根据宽度固定大小缩放 SCALE = (int) (newOpts.outWidth / ww); } else if (w < h && h > hh) {// 如果高度高的话根据宽度固定大小缩放 SCALE = (int) (newOpts.outHeight / hh); } if (SCALE <= 1) SCALE = 1; BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = false; options.inSampleSize = SCALE; Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), options); return bitmap; } } catch (Exception e) { } return null; } private static ExecutorService executor = null; private static ExecutorService getExecutor() { if (executor == null) executor = Executors.newFixedThreadPool(3); return executor; } public static interface CloseableImageCallback { public void callback(CloseableImage image, Bitmap bitmap); } /** fresco数据源请求监听 */ private static class FrescoBaseDataSubscriber extends BaseDataSubscriber<CloseableReference<CloseableImage>> { boolean callbackOnUI = true; CloseableImageCallback callback; public FrescoBaseDataSubscriber(CloseableImageCallback cb, boolean callbackOnUI) { callback = cb; this.callbackOnUI = callbackOnUI; } protected void onNewResultImpl(DataSource<CloseableReference<CloseableImage>> dataSource) { // if (!dataSource.isFinished()) { // Log.e("fresco", // "Not yet finished - this is just another progressive scan."); // } CloseableReference<CloseableImage> imageReference = dataSource.getResult(); if (imageReference != null) { try { final CloseableImage image = imageReference.get(); if (image != null) { if (log) LogWriter.i("fresco", "onNewResultImpl " + " w=" + image.getWidth() + " h=" + image.getHeight() + " image=" + image); Bitmap bitmap = null; if (image instanceof CloseableBitmap) { // jpg png bitmap = ((CloseableBitmap) image).getUnderlyingBitmap(); } else if (image instanceof CloseableAnimatedImage) { // GIF WEBP try { CloseableAnimatedImage cai = (CloseableAnimatedImage) image; if (cai.getImageResult().getPreviewBitmap() != null) bitmap = cai.getImageResult().getPreviewBitmap().get(); if (bitmap == null) { AnimatedImage ai = cai.getImage(); if (ai != null && ai.getFrameCount() > 0) { AnimatedImageFrame aif = ai.getFrame(0); if (aif != null) { bitmap = Bitmap.createBitmap(aif.getWidth(), aif.getHeight(), Config.ARGB_8888); aif.renderFrame(aif.getWidth(), aif.getHeight(), bitmap); } } } if (bitmap != null) { Bitmap tmp = bitmap.copy(Config.RGB_565, true); bitmap.recycle(); bitmap = null; bitmap = tmp; } } catch (Exception e) { } } if (callbackOnUI) { final Bitmap tmpbitmap = bitmap; Runnable runnable = new Runnable() { public void run() { callback.callback(image, tmpbitmap); } }; Handler handler = new Handler(Looper.getMainLooper()); handler.post(runnable); } else { callback.callback(image, bitmap); } } } finally { imageReference.close(); } } } protected void onFailureImpl(DataSource dataSource) { try { Throwable throwable = dataSource.getFailureCause(); Log.e("fresco", "onFailureImpl Throwable=" + throwable.getMessage()); // handle failure } catch (Exception e) { } } } /** * 清除某一个图片的缓存 * * @param param */ public static void evictFromCache(FrescoParam param) { try { Fresco.getImagePipeline().evictFromCache(Uri.parse(param.getURI())); } catch (Exception e) { e.printStackTrace(); } } // --------------------------fresco框架加载图片设置给ImageView private static HashMap<CloseableImageCallback, WeakReference<View>> mViews = new HashMap<CloseableImageCallback, WeakReference<View>>(); /** * 获取图片 加载到ImageView中,不支持Gif图片 * * @param param * @param view * ImageView */ public static void getImage(FrescoParam param, ImageView view) { if (param == null || view == null) return; if (view instanceof SimpleDraweeView) { getImage(param, (SimpleDraweeView) view, null); return; } // final int key = param.getURI().hashCode(); if (param.DefaultImageID != 0 && view.getDrawable() == null) { // 如果有Imageview已经设置了图片 drawable不是null,就不替换默认图了 view.setImageResource(param.DefaultImageID); } CloseableImageCallback cicb = new CloseableImageCallback() { public void callback(CloseableImage image, Bitmap bitmap) { if (log) LogWriter.d("fresco", "getImageToImageView bitmap=" + bitmap); try { if (bitmap != null && !bitmap.isRecycled()) { FrescoConfigConstants.autoResizeBitmap(bitmap, null); WeakReference<View> br = mViews.get(this); View v = null; if (br != null) { v = br.get(); } if (v != null && (v instanceof ImageView)) { ((ImageView) v).setImageBitmap(bitmap); } } } catch (Exception e) { LogWriter.e("frescoToImageview", "CloseableImageCallback exception"); } mViews.remove(this); } }; mViews.put(cicb, new WeakReference<View>(view)); getImage(param, cicb, true); } /** * 给Fresco图片控件设置图片 * * @param uri * 网络地址、磁盘文件、asset、res * @param view * SimpleDraweeView、FrescoImageView */ public static void getImage(String uri, SimpleDraweeView view) { FrescoParam fp = new FrescoParam(uri); // fp.setDefaultImage(R.drawable.def_image_bg); // 默认图 getImage(fp, view, null); } /** * 给普通的ImageView设置图片 * * @param uri * 网络地址、磁盘文件、asset、res * @param view * ImageView */ public static void getImage(String uri, ImageView view) { if (view instanceof SimpleDraweeView) { getImage(uri, (SimpleDraweeView) view); return; } FrescoParam fp = new FrescoParam(uri); // fp.setDefaultImage(R.drawable.def_image_bg);// 默认图 getImage(fp, view); } /** * 获取用户头像 * * @param uri * 网络地址、磁盘文件、asset、res * @param view * ImageView */ public static void getAvatar(String uri, ImageView view) { if (view instanceof SimpleDraweeView) { getAvatar(uri, (SimpleDraweeView) view); return; } FrescoParam fp = new FrescoParam(uri); fp.setDefaultImage(R.drawable.defaulthead);// 默认图 getImage(fp, view); } /** * 获取用户头像 * * @param uri * 网络地址、磁盘文件、asset、res * @param view * SimpleDraweeView */ public static void getAvatar(String uri, SimpleDraweeView view) { FrescoParam fp = new FrescoParam(uri); fp.setDefaultImage(R.drawable.defaulthead);// 默认图 // 强制给头像默认图设置center_crop view.getHierarchy().setPlaceholderImage(view.getContext().getResources().getDrawable(fp.DefaultImageID), ScalingUtils.ScaleType.CENTER_CROP); getImage(fp, view, null); } /** * @param res * res下的图片id * @param view */ public static void getAvatar(int res, ImageView view) { String url = "res://" + "/" + res; getAvatar(url, view); } /** * 获取用户头像 * * @param uri * 网络地址、磁盘文件、asset、res * @param view * SimpleDraweeView */ public static void getBigAvatar(String uri, SimpleDraweeView view) { FrescoParam fp = new FrescoParam(uri); // fp.setDefaultImage(R.drawable.home_hotperson_default);// 默认图 // 强制给头像默认图设置center_crop view.getHierarchy().setPlaceholderImage(view.getContext().getResources().getDrawable(fp.DefaultImageID), ScalingUtils.ScaleType.CENTER_CROP); getImage(fp, view, null); } public static void getGif(int gifRes, SimpleDraweeView mSimpleDraweeView, BaseControllerListener<ImageInfo> listener) { // ControllerListener listener = new BaseControllerListener<ImageInfo>() { // // public void onFinalImageSet(String id, ImageInfo imageInfo, Animatable anim) { // if (anim != null) { // // 其他控制逻辑 // anim.start(); // } // } // }; Uri uri = Uri.parse("res://" + "/" + gifRes); DraweeController controller = Fresco.newDraweeControllerBuilder().setUri(uri).setControllerListener(listener) // 其他设置(如果有的话) .build(); mSimpleDraweeView.setController(controller); } public static String getRandomImageUrl() { String[] urls = new String[] { "http://fdfs.xmcdn.com/group5/M01/2E/8D/wKgDtVONtOaCCgiQAAHhAAnF2BY165_web_large.jpg", "http://ww1.sinaimg.cn/thumb180/63fb4ad5gw6denp4x9fduj.jpg", "http://www.sc115.com/wenku/uploads/allimg/121214/23440332q-0.jpg", "http://img0.imgtn.bdimg.com/it/u=4238221358,1269566828&fm=21&gp=0.jpg", "http://img2.imgtn.bdimg.com/it/u=3554169248,909688534&fm=11&gp=0.jpg", "http://img5.imgtn.bdimg.com/it/u=1640990049,1096835342&fm=21&gp=0.jpg", "http://img5.imgtn.bdimg.com/it/u=1917782863,3035268524&fm=21&gp=0.jpg", "http://img2.imgtn.bdimg.com/it/u=1571982504,4022887356&fm=21&gp=0.jpg", "http://b.hiphotos.baidu.com/image/h%3D360/sign=d45d77b8b0b7d0a264c9029bfbee760d/b2de9c82d158ccbf15e8ae301bd8bc3eb1354167.jpg", "http://dimg04.c-ctrip.com/images/hhtravel/713/698/484/9159cabcda424168948cd82fb47f5f8d_C_250_140_Q80.jpg" }; int number = new Random().nextInt(urls.length - 1); return urls[number]; } }
package com.kopo.jaemin; import java.util.Locale; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; /** * Handles requests for the application home page. */ @Controller public class HomeController { private static final Logger logger = LoggerFactory.getLogger(HomeController.class); /** * Simply selects the home view to render by returning its name. */ @RequestMapping(value = "/", method = RequestMethod.GET) public String home(Locale locale, Model model) { return "main"; } // ◆◆◆DB common 용◆◆◆ // @RequestMapping(value = "/list", method = RequestMethod.GET) // public String listMethod(Locale locale, Model model) { // DBCommon<Student> db = new DBCommon<Student>("c:/tomcat/studentScore.db", "score"); // ArrayList<Student> student = db.selectArrayList(new Student()); // String htmlString = ""; // for (int i = 0; i < student.size(); i++) { // htmlString = htmlString + "<tr>"; // htmlString = htmlString + "<td>"; // htmlString = htmlString + student.get(i).idx; // htmlString = htmlString + "</td>"; // htmlString = htmlString + "<td>"; // htmlString = htmlString + student.get(i).name; // htmlString = htmlString + "</td>"; // htmlString = htmlString + "<td>"; // htmlString = htmlString + student.get(i).middleScore; // htmlString = htmlString + "</td>"; // htmlString = htmlString + "<td>"; // htmlString = htmlString + student.get(i).finalScore; // htmlString = htmlString + "</td>"; // htmlString = htmlString + "<td>"; // htmlString = htmlString + student.get(i).created; // htmlString = htmlString + "</td>"; // htmlString = htmlString + "<td>"; // htmlString = htmlString + "<a href='update?idx=" + student.get(i).idx + "'>수정하기</a>"; // htmlString = htmlString + "</td>"; // htmlString = htmlString + "<td>"; // htmlString = htmlString + "<a href='delete?idx=" + student.get(i).idx + "'>삭제하기</a>"; // htmlString = htmlString + "</td>"; // htmlString = htmlString + "</tr>"; // } // model.addAttribute("list", htmlString); // return "list"; // } // ◆◆◆userDB용◆◆◆ @RequestMapping(value = "/list", method = RequestMethod.GET) public String listMethod(Locale locale, Model model) { UserDB db = new UserDB(); String htmlString = db.selectData(); model.addAttribute("list", htmlString); return "list"; } @RequestMapping(value = "/insert", method = RequestMethod.GET) public String insertMethod(Locale locale, Model model) { return "insert"; } // ◆◆◆DB common 용◆◆◆ // @RequestMapping(value = "/insert_action", method = RequestMethod.GET) // public String insertAction(Locale locale, Model model // , @RequestParam("student_name") String name // , @RequestParam("middlescore") String middleScore // , @RequestParam("finalscore") String finalScore) { // int mScore = Integer.parseInt(middleScore); // int fScore = Integer.parseInt(finalScore); // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss"); // String now = sdf.format(Calendar.getInstance().getTime()); // DBCommon<Student> db = new DBCommon<Student>("c:/tomcat/studentScore.db", "score"); // db.insertData(new Student(name, mScore, fScore, now)); // model.addAttribute("m1", "성적이 입력되었습니다."); // // return "message"; // } // ◆◆◆userDB 용◆◆◆ @RequestMapping(value = "/insert_action", method = RequestMethod.GET) public String insertAction(Locale locale, Model model , @RequestParam("student_name") String name , @RequestParam("middlescore") String middleScoreString , @RequestParam("finalscore") String finalScoreString) { UserDB db = new UserDB(); double middleScore = Double.parseDouble(middleScoreString); double finalScore = Double.parseDouble(finalScoreString); db.insertData(name, middleScore, finalScore); model.addAttribute("m1", "성적이 입력되었습니다."); return "message"; } // ◆◆◆DBCommon용◆◆◆ // @RequestMapping(value = "/update", method = RequestMethod.GET) // public String updateMethod(Locale locale, Model model, @RequestParam("idx") int idx) { // DBCommon<Student> db = new DBCommon<Student>("c:/tomcat/user.db", "score"); // Student selectStudent = db.detailsData(new Student(), idx); // // if (selectStudent != null) { // model.addAttribute("idx", selectStudent.idx); // model.addAttribute("student_name", selectStudent.name); // model.addAttribute("middleScore", selectStudent.middleScore); // model.addAttribute("finalScore", selectStudent.finalScore); // } // return "update"; // } // ◆◆◆UserDB용◆◆◆ @RequestMapping(value = "/update", method = RequestMethod.GET) public String updateMethod(Locale locale, Model model, @RequestParam("idx") int idx) { UserDB db = new UserDB(); Student selectStudent = db.detailsData(idx); if (selectStudent != null) { model.addAttribute("idx", selectStudent.idx); model.addAttribute("student_name", selectStudent.name); model.addAttribute("middleScore", selectStudent.middleScore); model.addAttribute("finalScore", selectStudent.finalScore); } return "update"; } // ◆◆◆DBCommon용◆◆◆ // @RequestMapping(value = "/update_action", method = RequestMethod.GET) // public String updateAction(Locale locale, Model model // , @RequestParam("idx") int idx // , @RequestParam("student_name") String sname // , @RequestParam("middlescore") String middleScore // , @RequestParam("finalscore") String finalScore) { // int mScore = Integer.parseInt(middleScore); // int fScore = Integer.parseInt(finalScore); // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss"); // String now = sdf.format(Calendar.getInstance().getTime()); // // DBCommon<Student> db = new DBCommon<Student>("c:/tomcat/user.db", "score"); // db.updateData(new Student(idx, sname, mScore, fScore, now)); // // model.addAttribute("m1", "성적이 수정되었습니다."); // return "message"; // } // ◆◆◆UserDB용◆◆◆ @RequestMapping(value = "/update_action", method = RequestMethod.GET) public String updateAction(Locale locale, Model model , @RequestParam("idx") int idx , @RequestParam("student_name") String name , @RequestParam("middlescore") String middleScoreString , @RequestParam("finalscore") String finalScoreString) { UserDB db = new UserDB(); double middleScore = Double.parseDouble(middleScoreString); double finalScore = Double.parseDouble(finalScoreString); db.updateData(idx, name, middleScore, finalScore); model.addAttribute("m1", "데이터가 수정되었습니다."); return "message"; } // ◆◆◆DBcommon용◆◆◆ // @RequestMapping(value = "/delete", method = RequestMethod.GET) // public String delete(Locale locale, Model model, @RequestParam("idx") int idx) { // DBCommon<Student> db = new DBCommon<Student>("c:\\tomcat\\user.db", "studnet"); // Student deleteStudent = db.detailsData(new Student(), idx); // // db.deleteData(deleteStudent); // model.addAttribute("m1", " 테이블이 삭제되었습니다"); // return "message"; // } // ◆◆◆UserDB용◆◆◆ @RequestMapping(value = "/delete", method = RequestMethod.GET) public String delete(Locale locale, Model model, @RequestParam("idx") int idx) { UserDB db = new UserDB(); db.deleteData(idx); model.addAttribute("m1", " 테이블이 삭제되었습니다"); return "message"; } // ◆◆◆DBcommon용◆◆◆ // @RequestMapping(value = "/create", method = RequestMethod.GET) // public String create(Locale locale, Model model) { // DBCommon<Student> db = new DBCommon<Student>("c:\\tomcat\\studentScore.db", "score"); // db.createTable(new Student()); // model.addAttribute("m1", "성적 테이블이 생성되었습니다."); // return "message"; // } // ◆◆◆userDB용◆◆◆ @RequestMapping(value = "/create", method = RequestMethod.GET) public String create(Locale locale, Model model) { UserDB db = new UserDB(); db.createTable(); model.addAttribute("m1", "성적 테이블이 생성되었습니다."); return "message"; } @RequestMapping(value = "/message", method = RequestMethod.GET) public String messageMethod(Locale locale, Model model) { return "message"; } }
package View.Allenamento; import javax.swing.*; import javax.swing.event.ChangeListener; import java.awt.event.ActionListener; import java.util.ArrayList; public class ProgAllenManView { private JPanel mainPanel; private JTabbedPane settimanaPane; private JPanel lunediPanel; private JPanel martediPanel; private JPanel mercolediPanel; private JPanel giovediPanel; private JPanel venerdiPanel; private JPanel sabatoPanel; private JPanel domenicaPanel; private JButton annullaProgrammaButton; private JButton confermaProgrammaButton; private GiornoAllenForm lunedimanuale; private GiornoAllenForm martedimanuale; private GiornoAllenForm mercoledimanuale; private GiornoAllenForm giovedimanuale; private GiornoAllenForm venerdimanuale; private GiornoAllenForm sabatomanuale; private GiornoAllenForm domenicamanuale; private ArrayList<GiornoAllenForm> giornimanuali; public ProgAllenManView() { giornimanuali = new ArrayList<GiornoAllenForm>(7); giornimanuali.add(lunedimanuale); giornimanuali.add(martedimanuale); giornimanuali.add(mercoledimanuale); giornimanuali.add(giovedimanuale); giornimanuali.add(venerdimanuale); giornimanuali.add(sabatomanuale); giornimanuali.add(domenicamanuale); } public JPanel getMainPanel() { return mainPanel; } public void addTabbedSelectionListener (ChangeListener listener) { settimanaPane.addChangeListener(listener); } public void addAnnullaProgrammaButtonListener(ActionListener listener) { annullaProgrammaButton.addActionListener(listener); } public void addConfermaProgrammaButtonListener(ActionListener listener){ confermaProgrammaButton.addActionListener(listener); } public GiornoAllenForm getTabView (int panel) { return giornimanuali.get(panel); } private void createUIComponents() { lunedimanuale = new GiornoAllenForm("Quale attività vuoi svolgere il lunedi"); martedimanuale = new GiornoAllenForm("Quale attività vuoi svolgere il martedi"); mercoledimanuale = new GiornoAllenForm("Quale attività vuoi svolgere il mercoledi"); giovedimanuale = new GiornoAllenForm("Quale attività vuoi svolgere il giovedi"); venerdimanuale = new GiornoAllenForm("Quale attività vuoi svolgere il venerdi"); sabatomanuale = new GiornoAllenForm("Quale attività vuoi svolgere il sabato"); domenicamanuale = new GiornoAllenForm("Quale attività vuoi svolgeree la domenica"); lunedimanuale.setButtonsVisible(); martedimanuale.setButtonsVisible(); mercoledimanuale.setButtonsVisible(); giovedimanuale.setButtonsVisible(); venerdimanuale.setButtonsVisible(); sabatomanuale.setButtonsVisible(); domenicamanuale.setButtonsVisible(); lunediPanel = lunedimanuale.getMainPanel(); martediPanel = martedimanuale.getMainPanel(); mercolediPanel = mercoledimanuale.getMainPanel(); giovediPanel = giovedimanuale.getMainPanel(); venerdiPanel = venerdimanuale.getMainPanel(); sabatoPanel = sabatomanuale.getMainPanel(); domenicaPanel = domenicamanuale.getMainPanel(); } }
package lesson5.hw; /** * GBJava3 * Algorithms and data structures in Java. 24.09.2019 Webinar. Teacher: Fanzil' Kusyapkulov * Урок 5. Рекурсия * Зачем функция вызывает саму себя? * Домашнее задание. * DONE 3*. Добавить в рекурсивный метод recMultiply возможность перемножения отрицательных чисел. */ public class Less5_hw_3 { public static void main(String[] args) { System.out.println("4 * 7 = " + multiply(4, 7)); System.out.println("-4 * 7 = " + multiply(-4, 7)); System.out.println("4 * -7 = " + multiply(4, -7)); System.out.println("-4 * -7 = " + multiply(-4, -7)); } //метод перемножения целочисленных чисел с любым знаком private static int multiply(int a, int b) { //если одно из чисел равно 0, возвращаем 0 if (a == 0 || b == 0) { return 0; } //если первое число равно 1, возвращаем второе число if (a == 1) { return b; } int neg = 1; //если только одно из чисел отрицательное if((a < 0 && b > 0) || (b < 0 && a > 0)){ //берем модули чисел //a = Math.abs(a); //b = Math.abs(b); neg = -1; } return neg * recMultiply(Math.abs(a), Math.abs(b)); } //Рекуперативный метод, где второе число - множитель private static int recMultiply(int a, int b) { //если второе число равно 1, возвращаем первое число if (b == 1) { return a; } return recMultiply(a, b - 1) + a; } }
package com.main.impl; import com.main.AbstractApplicationContext; public class XmlApplicationContext extends AbstractApplicationContext { public XmlApplicationContext(String[] xmlPaths) { setUpElements(xmlPaths); createBeans(); } }
package com.ms.module.wechat.clear.activity.file; import android.view.View; import android.widget.CheckBox; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.chad.library.adapter.base.entity.node.BaseNode; import com.chad.library.adapter.base.provider.BaseNodeProvider; import com.chad.library.adapter.base.viewholder.BaseViewHolder; import com.ms.module.wechat.clear.R; import com.ms.module.wechat.clear.utils.ByteSizeToStringUnitUtils; import com.ms.module.wechat.clear.utils.ListDataUtils; import com.ms.module.wechat.clear.utils.OpenFileUtils; import org.jetbrains.annotations.NotNull; import java.io.File; public class FileChildProvider extends BaseNodeProvider { @Override public int getItemViewType() { return 2; } @Override public int getLayoutId() { return R.layout.provider_details_file_child; } @Override public void convert(@NotNull BaseViewHolder baseViewHolder, BaseNode baseNode) { ImageView iamgeViewLogo = baseViewHolder.findView(R.id.iamgeViewLogo); TextView textViewName = baseViewHolder.findView(R.id.textViewName); TextView textViewSize = baseViewHolder.findView(R.id.textViewSize); ImageView imageViewCheck = baseViewHolder.findView(R.id.imageViewCheck); if (baseNode instanceof FileChildNode) { FileChildNode childNode = (FileChildNode) baseNode; File file = new File(childNode.getPath()); String name = file.getName(); long length = file.length(); textViewName.setText(name); textViewSize.setText(ByteSizeToStringUnitUtils.byteToStringUnit(length)); imageViewCheck.setSelected(childNode.isCheck()); baseViewHolder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { OpenFileUtils.openFileByPath(context,childNode.getPath()); } }); imageViewCheck.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { boolean selected = imageViewCheck.isSelected(); if (selected) { imageViewCheck.setSelected(false); childNode.setCheck(false); } else { imageViewCheck.setSelected(true); childNode.setCheck(true); } getAdapter().notifyDataSetChanged(); if (FileDetailsActivity.getInstance() != null) { FileDetailsActivity.getInstance().updateSelectAll(); } } }); if (file.getName().endsWith(".txt")) { Glide.with(context).load(R.drawable.image_txt).into(iamgeViewLogo); } else if (file.getName().endsWith(".ppt")) { Glide.with(context).load(R.drawable.image_ppt).into(iamgeViewLogo); } else if (file.getName().endsWith(".pdf")) { Glide.with(context).load(R.drawable.image_pdf).into(iamgeViewLogo); } else if (file.getName().endsWith(".mp4")) { Glide.with(context).load(R.drawable.image_video).into(iamgeViewLogo); } else if (file.getName().endsWith(".mp3")) { Glide.with(context).load(R.drawable.image_music).into(iamgeViewLogo); } else if (file.getName().endsWith(".xls")) { Glide.with(context).load(R.drawable.image_xls).into(iamgeViewLogo); } else if (file.getName().endsWith(".doc") || file.getName().endsWith(".docx")) { Glide.with(context).load(R.drawable.image_doc).into(iamgeViewLogo); } else { Glide.with(context).load(R.drawable.image_other).into(iamgeViewLogo); } } } }
public class Algebra { public Double term1(double Y1,double Y2,double Y3) { double X=(Y3-Y2)/Y1; return X; } public Double term2(double Y1,double Y2,double Y3) { double X=(Y3-Y1)/Y2; return X; } public Double term3(double Y1,double Y2,double Y3) { double X=(Y3+Y2)/Y1; return X; } public Double term4(double Y1,double Y2,double Y3) { double X=(Y3-Y1)/(-Y2); return X; } }
package com.eomcs.basic.oop.ex06.bb; public class Exam120 { static class Calculator { static int plus(int a, int b) { return a + b; } static int plus(int a) { return a + a; } static float plus(float a, float b) { return a + b; } } public static void main(String[] args) { int r1 = Calculator.plus(100,200); int r2 = Calculator.plus(100); float r3 = Calculator.plus(35.7f,22.2f); float r4 = Calculator.plus(35.7f,22); System.out.printf("%d, %d, %.1f\n", r1, r2, r3); System.out.printf("%d, %d, %.1f\n", r1, r2, r3); } }
package com.cs.report; import java.io.Serializable; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * @author Hadi Movaghar */ public class ReportData implements Serializable { private static final long serialVersionUID = 1L; private Date startTime; private String[] headers; private final List<Object[]> data; public ReportData() { startTime = new Date(); data = new ArrayList<>(); } public String[] getHeaders() { return headers; } public void setHeaders(final String... headers) { this.headers = headers; } public void addRow(final Object... objects) { data.add(objects); } public List<Object[]> getData() { return data; } public Date getStartTime() { return startTime; } }
package com.arpit.equityposition.utilities; /** * Enum of the valid actions. * @author : Arpit * @version 1.0 * @since : 23-Jun-2020 */ public enum ValidActions { INSERT,UPDATE,CANCEL; }
package com.favour.dome.entity; import javax.persistence.*; /** * Created by fernando on 26/05/15. */ @Entity public class FavourType { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name="ID", unique=true, nullable=false) private Integer id; @Column(name="Type", length=45) private String type; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getType() { return type; } public void setType(String type) { this.type = type; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; FavourType that = (FavourType) o; if (id != null ? !id.equals(that.id) : that.id != null) return false; return !(type != null ? !type.equals(that.type) : that.type != null); } @Override public int hashCode() { int result = id != null ? id.hashCode() : 0; result = 31 * result + (type != null ? type.hashCode() : 0); return result; } @Override public String toString() { return "FavourType{" + "id=" + id + ", type='" + type + '\'' + '}'; } }
package com.nube.core.vo.idm; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import org.springframework.security.core.GrantedAuthority; /** * New user roles, it contains zero or more privs * @author kamoorr * */ public class Role implements GrantedAuthority, Serializable{ /** * */ private static final long serialVersionUID = 1L; /*Not logged in*/ public final static String role_guest = "ROLE_GUEST"; /*end user*/ public final static String role_consumer = "ROLE_CONSUMER"; /*admin for one or more site*/ public final static String role_admin = "ROLE_ADMIN"; /*access to all sites*/ public final static String role_super_admin = "ROLE_SUPER_ADMIN"; /*support person. system access*/ public final static String role_support = "ROLE_OPS"; private String name; private List<Privilege> privileges; public Role(String name){ this(name, null); } public Role(String name, List<Privilege> privs){ this.name = name; this.privileges = (privs == null? new ArrayList<Privilege>(): privs); } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<Privilege> getPrivileges() { return privileges; } public void setPrivileges(List<Privilege> privileges) { this.privileges = privileges; } @Override public String toString() { return name; } /** * role name is used as authority */ public String getAuthority() { return name; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Role other = (Role) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } }
/* * Created by VisualGDB. Based on hello-jni example. * Copyright (C) 2009 The Android Open Source Project * * 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.RtspServer; import android.app.Activity; import android.view.View; import android.widget.Button; import android.os.Bundle; public class RtspServer extends Activity { private int m_clickCount = 0; private RtspServerAPI rtspServerAPI = new RtspServerAPI(); /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); /* Create a Button and set its content. * the text is retrieved by calling a native * function. */ final Button button = new Button(this); button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { m_clickCount++; if(m_clickCount%5==1) { rtspServerAPI.RtspCreate(); button.setText("RtspCreate Called!"); } else if(m_clickCount%5==2) { rtspServerAPI.RtspStart(); button.setText("RtspStart Called!"); } else if(m_clickCount%5==3) { rtspServerAPI.RtspStop(); button.setText("RtspStop Called!"); } else if(m_clickCount%5==4) { rtspServerAPI.RtspDestory(); button.setText("RtspDestory Called!"); } else if(m_clickCount%5==0) { button.setText(rtspServerAPI.stringFromJNI()); } //button.setText( stringFromJNI()); } }); //button.setText( stringFromJNI() ); setContentView(button); } /* A native method that is implemented by the * 'RtspServer' native library, which is packaged * with this application. */ /* this is used to load the 'RtspServer' library on application * startup. The library has already been unpacked into * /data/data/com.RtspServer/lib/RtspServer.so at * installation time by the package manager. */ }
package com.xdddw.dao; import java.io.UnsupportedEncodingException; import java.sql.ResultSet; import java.sql.SQLException; import org.json.JSONException; import com.mysql.jdbc.Connection; import com.mysql.jdbc.PreparedStatement; import com.xdddw.util.DBUtil; import com.xdddw.util.Util; public class IndexDao { public ResultSet GetArticleList(String pagesize, String currentPage) throws Exception { DBUtil dbUtil = new DBUtil(); Connection con = (Connection) dbUtil.getConnection(); ResultSet rs = null; int a = Integer.parseInt(pagesize); int b = Integer.parseInt(currentPage); String sql = "select id,content,title,addTime,image from content limit "+(b-1)*a+","+a; PreparedStatement ps = (PreparedStatement) con.prepareStatement(sql); rs = ps.executeQuery(); return rs; } public int GetCounts() throws Exception { DBUtil dbUtil = new DBUtil(); Connection con = (Connection) dbUtil.getConnection(); ResultSet rs = null; String sql = "select count(1) from content"; PreparedStatement ps = (PreparedStatement) con.prepareStatement(sql); rs = ps.executeQuery(); int sum = 0; while(rs.next()){ sum = rs.getInt(1); } return sum; } }
package com.pitang.util.datastructure; public class Tuple<T1, T2, T3> { private final T1 value1; private final T2 value2; private final T3 value3; public Tuple(final T1 value1, final T2 value2, final T3 value3) { this.value1 = value1; this.value2 = value2; this.value3 = value3; } public T1 getValue1() { return this.value1; } public T2 getValue2() { return this.value2; } public T3 getValue3() { return this.value3; } }
package com.itsoul.lab.generalledger.entities; import com.it.soul.lab.sql.entity.Ignore; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Request object describing a balanced, multi-legged monetary transaction between two * or more accounts. A request must have at least two legs. Different money currencies * are allowed as long as the total balance for the legs with the same currency is zero. * <p> * This class uses a nested builder state machine to provide a clear building path with * compile-time safety and coding guidance. * * */ /** * @author towhid * @since 19-Aug-19 */ public final class TransferRequest extends LedgerEntity { @Ignore private static final long serialVersionUID = 1L; private String transactionRef; private String transactionType; private final List<TransactionLeg> legs = new ArrayList<>(); private TransferRequest() { } /** * Returns a new builder for creating a transfer request. * * @return the first build step */ public static ReferenceStep builder() { return new Builder(); } @FunctionalInterface public interface ReferenceStep { /** * @param transactionRef client defined transaction reference * @return the next build step */ TypeStep reference(String transactionRef); } @FunctionalInterface public interface TypeStep { /** * @param transactionType the transaction type for grouping transactions or other purposes * @return the next build step */ default AccountStep type(String transactionType) { return type(transactionType, AccountingType.Liability); } /** * Universal Accounting Type:- * Asset, Income, Contingent-Asset : Debit (+) * Liability, Expense, Contingent-Liability : Debit (-) * @param transactionType * @param acType * @return */ AccountStep type(String transactionType, AccountingType acType); } @FunctionalInterface public interface AccountStep { /** * @param accountRef the client defined account reference * @return the next build step */ AmountStep account(String accountRef); } public interface AmountStep { /** * @param money the transfer amount for the account * @return the final build step */ BuildStep amount(Money money); BuildStep debit(String amount, String currency); BuildStep credit(String amount, String currency); } public interface BuildStep { AmountStep account(String accountRef); TransferRequest build(); } private static final class Builder implements ReferenceStep, TypeStep, AccountStep, AmountStep, BuildStep { private final TransferRequest request = new TransferRequest(); private String accountRef; private AccountingType acType; @Override public TypeStep reference(String transactionRef) { request.transactionRef = transactionRef; return this; } @Override public AccountStep type(String transactionType) { return type(transactionType, AccountingType.Liability); } @Override public AccountStep type(String transactionType, AccountingType acType) { request.transactionType = transactionType; this.acType = acType; return this; } @Override public AmountStep account(String accountRef) { this.accountRef = accountRef; return this; } @Override public BuildStep amount(Money money) { request.legs.add(new TransactionLeg(accountRef, money, "dr")); accountRef = null; return this; } @Override public BuildStep debit(String amount, String currency) { String debitAmount = acType.sign() + amount; request.legs.add(new TransactionLeg(accountRef, Money.toMoney(debitAmount, currency), "dr")); accountRef = null; return this; } @Override public BuildStep credit(String amount, String currency) { String creditAmount = acType.reverseSign() + amount; request.legs.add(new TransactionLeg(accountRef, Money.toMoney(creditAmount, currency), "cr")); accountRef = null; return this; } @Override public TransferRequest build() { return request; } } public List<TransactionLeg> getLegs() { return Collections.unmodifiableList(legs); } public String getTransactionRef() { return transactionRef; } public String getTransactionType() { return transactionType; } }
package com.jd.jarvisdemonim.entity; import java.util.List; /** * Auther: Jarvis Dong * Time: on 2016/12/23 0023 * Name: * OverView: * Usage: */ public class TestGroupBean { private boolean isExpand; public String getContentTitle() { return contentTitle; } public void setContentTitle(String contentTitle) { this.contentTitle = contentTitle; } private String contentTitle; public TestGroupBean(boolean isExpand, String contentTitle, List<TestChildBean> bean) { this.isExpand = isExpand; this.contentTitle = contentTitle; this.bean = bean; } public TestGroupBean(boolean isExpand, String contentTitle) { this.isExpand = isExpand; this.contentTitle = contentTitle; } public TestGroupBean(boolean isExpand, List<TestChildBean> bean) { this.isExpand = isExpand; this.bean = bean; } public boolean isExpand() { return isExpand; } public void setExpand(boolean expand) { isExpand = expand; } public List<TestChildBean> getBean() { return bean; } public void setBean(List<TestChildBean> bean) { this.bean = bean; } private List<TestChildBean> bean; }
package com.lsjr.zizisteward.http; /** * Created by admin on 2017/5/4. */ public interface AppUrl { String URLKEY="TNNYF17DbevNyxVv"; /* 正式服务器 */ String Http = "https://app.zizi.com.cn"; /*开发服务器*/ // String Http = "https://dev.zizi.com.cn"; String baseUrl = Http + "/app/"; String HOST = Http + "/app/services?"; // 微信授权 String GET_REQUEST_ACCESS_TOKEN = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code"; String GET_REQUEST_USER_INFO = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID"; public static final String Qr_code = Http + "/app/qrcodeisgenerated"; public static final String UPLOAD_IMAGE = Http + "/app/uploadUserPhoto"; public static final String uploadGroupPhoto = Http + "/app/uploadGroupPhoto"; public static final String uploadFriendCircle = Http + "/app/uploadFriendCircle"; public static final String adduploadGroupPhoto = Http + "/app/adduploadGroupPhoto"; public static final String Up_friend_cicle = Http + "/app/uploadbackgroundPicture"; }
/** * * Copyright (c) 2017, Yustinus Nugroho * * This software is created to help SIMPEG division in Badan Kepegawaian Daerah * gathering and organizing data from other divisions. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Let me know if you use this code by email yustinus.nugroho@gmail.com * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Hope this make changes. */ package net.yustinus.crud.backend.beans; import java.util.Date; import java.util.List; import net.yustinus.crud.backend.dto.AtasNamaDto; import net.yustinus.crud.backend.dto.MemperhatikanDto; import net.yustinus.crud.backend.dto.MengingatDto; import net.yustinus.crud.backend.dto.MenimbangDto; import net.yustinus.crud.backend.dto.SpecimentDto; import net.yustinus.crud.backend.dto.TembusanDto; import net.yustinus.crud.backend.dto.TemplateSkMutasiDto; /** * @author Yustinus Nugroho * */ public class SkMutasiBean { private int skMutasiId; private Date tglSkMutasi; private Date tmtSkMutasi; private String noSkMutasi; private List<MemberMutasiBean> memberMutasi; private MemperhatikanDto memperhatikan; private MenimbangDto menimbang; private MengingatDto mengingat; private TembusanDto tembusan; private SpecimentDto speciment; private AtasNamaDto atasNama; private TemplateSkMutasiDto templateSkMutasi; private int spaceBeforeMenimbang; private int spaceBeforeMengingat; private int spaceBeforeMemperhatikan; private int spaceBeforeMenetapkan; private int spaceBeforePenutup; private int spaceBeforeTembusan; private int spaceBeforeSpeciment; public SkMutasiBean() { } public Date getTglSkMutasi() { return tglSkMutasi; } public void setTglSkMutasi(Date tglSkMutasi) { this.tglSkMutasi = tglSkMutasi; } public Date getTmtSkMutasi() { return tmtSkMutasi; } public void setTmtSkMutasi(Date tmtSkMutasi) { this.tmtSkMutasi = tmtSkMutasi; } public List<MemberMutasiBean> getMemberMutasi() { return memberMutasi; } public void setMemberMutasi(List<MemberMutasiBean> memberMutasi) { this.memberMutasi = memberMutasi; } public MemperhatikanDto getMemperhatikan() { return memperhatikan; } public void setMemperhatikan(MemperhatikanDto memperhatikan) { this.memperhatikan = memperhatikan; } public MenimbangDto getMenimbang() { return menimbang; } public void setMenimbang(MenimbangDto menimbang) { this.menimbang = menimbang; } public MengingatDto getMengingat() { return mengingat; } public void setMengingat(MengingatDto mengingat) { this.mengingat = mengingat; } public TembusanDto getTembusan() { return tembusan; } public void setTembusan(TembusanDto tembusan) { this.tembusan = tembusan; } public SpecimentDto getSpeciment() { return speciment; } public void setSpeciment(SpecimentDto speciment) { this.speciment = speciment; } public AtasNamaDto getAtasNama() { return atasNama; } public void setAtasNama(AtasNamaDto atasNama) { this.atasNama = atasNama; } public TemplateSkMutasiDto getTemplateSkMutasi() { return templateSkMutasi; } public void setTemplateSkMutasi(TemplateSkMutasiDto templateSkMutasi) { this.templateSkMutasi = templateSkMutasi; } public String getNoSkMutasi() { return noSkMutasi; } public void setNoSkMutasi(String noSkMutasi) { this.noSkMutasi = noSkMutasi; } public int getSkMutasiId() { return skMutasiId; } public void setSkMutasiId(int skMutasiId) { this.skMutasiId = skMutasiId; } public int getSpaceBeforeMenimbang() { return spaceBeforeMenimbang; } public void setSpaceBeforeMenimbang(int spaceBeforeMenimbang) { this.spaceBeforeMenimbang = spaceBeforeMenimbang; } public int getSpaceBeforeMengingat() { return spaceBeforeMengingat; } public void setSpaceBeforeMengingat(int spaceBeforeMengingat) { this.spaceBeforeMengingat = spaceBeforeMengingat; } public int getSpaceBeforeMemperhatikan() { return spaceBeforeMemperhatikan; } public void setSpaceBeforeMemperhatikan(int spaceBeforeMemperhatikan) { this.spaceBeforeMemperhatikan = spaceBeforeMemperhatikan; } public int getSpaceBeforeMenetapkan() { return spaceBeforeMenetapkan; } public void setSpaceBeforeMenetapkan(int spaceBeforeMenetapkan) { this.spaceBeforeMenetapkan = spaceBeforeMenetapkan; } public int getSpaceBeforePenutup() { return spaceBeforePenutup; } public void setSpaceBeforePenutup(int spaceBeforePenutup) { this.spaceBeforePenutup = spaceBeforePenutup; } public int getSpaceBeforeTembusan() { return spaceBeforeTembusan; } public void setSpaceBeforeTembusan(int spaceBeforeTembusan) { this.spaceBeforeTembusan = spaceBeforeTembusan; } public int getSpaceBeforeSpeciment() { return spaceBeforeSpeciment; } public void setSpaceBeforeSpeciment(int spaceBeforeSpeciment) { this.spaceBeforeSpeciment = spaceBeforeSpeciment; } }
package structural.bridge.my.engines; // 顶层引擎接口 public interface Engine { void start(); }
package org.narl.hrms.visual.rest; import static org.springframework.data.mongodb.core.aggregation.Aggregation.group; import static org.springframework.data.mongodb.core.aggregation.Aggregation.match; import static org.springframework.data.mongodb.core.aggregation.Aggregation.newAggregation; import static org.springframework.data.mongodb.core.aggregation.Aggregation.sort; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.List; import javax.ws.rs.FormParam; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import org.narl.hrms.visual.mongo.service.CommondServiceImpl; import org.narl.hrms.visual.rest.output.DeptOutput; import org.narl.hrms.visual.rest.output.EmpOutput; import org.narl.hrms.visual.rest.output.OrgOutput; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Sort; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.aggregation.Aggregation; import org.springframework.data.mongodb.core.aggregation.AggregationResults; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; @Path("commondata") public class CommonDataService { private static final Logger logger = LoggerFactory.getLogger(CommonDataService.class); @Autowired MongoTemplate mongoTemplate; @Autowired CommondServiceImpl commondServiceImpl; String collectionName="ORG_DEPT_EMP_"; /** * 取得organization according to login user's role * * 1代表super user,2代表人事,3代表主管,4代表員工 * ,2代表人事,3代表主管,4代表員工>>都是只有自己的中心 * db.getCollection('ORG_DEPT_EMP_2015').aggregate([ { $match : { "$and" : [ {'emp_id': '957' }]}}, { "$group": { "_id": { org_id: "$org_id", org_name: "$org_name" }}}, { "$sort" : { "org_id" : -1}} ]) */ @POST @Path("postOrgList") @Produces({ MediaType.APPLICATION_JSON }) public List<OrgOutput> getOrgList(@FormParam("login_id") String login_id, @FormParam("year") String yearString, @FormParam("role") String role){ logger.info("postDeptList>> login id : " +",yearString: "+yearString +", role:" +role); if (yearString==null || login_id==null || login_id.equals("")) return new ArrayList<OrgOutput>(); String collectName=this.collectionName+yearString; if (!commondServiceImpl.collectionExisted(collectName)) return new ArrayList<OrgOutput>(); Criteria criteriaDefinition = new Criteria(); if (role!=null && "1".equals(role)) { } else { criteriaDefinition.andOperator(Criteria.where("emp_id").is(Integer.valueOf(login_id))); } Aggregation aggregation=newAggregation( match(criteriaDefinition), group("org_id", "org_name"), sort(Sort.Direction.ASC, "org_id") ); AggregationResults groupResults = mongoTemplate.aggregate( aggregation, collectName, OrgOutput.class); List<OrgOutput> aggList = groupResults.getMappedResults(); return aggList; } /** * 取得Department according to organization * * * 1代表super user,2代表人事,3代表主管,4代表員工 * 3代表主管,4代表員工>>自己的部門 * db.getCollection('ORG_DEPT_EMP_2015').aggregate([ { $match : { "$and" : [ {'emp_id': '957' }]}}, { "$group": { "_id": { dept_id: "$dept_id", dept_name: "$dept_name" }}}, { "$sort" : { "dept_id" : -1}}]) * 1代表主管,2代表員工>>自己中心的所有部門 */ @POST @Path("postDeptList") @Produces({ MediaType.APPLICATION_JSON }) public List<DeptOutput> getDeptList(@FormParam("org_id") String org_id, @FormParam("login_id") String login_id, @FormParam("year") String yearString, @FormParam("role") String role){ logger.info("postDeptList>> login id : " +login_id+ ", org_id: " +org_id +",yearString: "+yearString +", role:" +role); if (yearString==null || org_id.equals("-1") || login_id==null || login_id.equals("")) return new ArrayList<DeptOutput>(); String collectName=this.collectionName+yearString; if (!commondServiceImpl.collectionExisted(collectName)) return new ArrayList<DeptOutput>(); Criteria criteriaDefinition = new Criteria(); if (role!=null && "1".equals(role)) { criteriaDefinition.andOperator(Criteria.where("org_id").is(Integer.valueOf(org_id))); } else if (role!=null && "2".equals(role)) { criteriaDefinition.andOperator(Criteria.where("org_id").is(Integer.valueOf(org_id))); } else { criteriaDefinition.andOperator(Criteria.where("emp_id").is(Integer.valueOf(login_id))); } Aggregation aggregation=newAggregation( match(criteriaDefinition), group("dept_id", "dept_name"), sort(Sort.Direction.ASC, "dept_id") ); AggregationResults groupResults = mongoTemplate.aggregate( aggregation, collectName, DeptOutput.class); List<DeptOutput> aggList = groupResults.getMappedResults(); return aggList; } /** * 取得Emp List accordintgto organization , department and login user's role * 1代表super user,2代表人事,3代表主管,4代表員工 * 1代表super user,2代表人事,3代表主管>>ALL * db.getCollection('ORG_DEPT_EMP_2015').aggregate([ { $match : { "$and" : [ {'org_id': '82' }, {'dept_id': '614' }]}}, { "$group": { "_id": { emp_id: "$emp_id", emp_name: "$emp_name" }}}, { "$sort" : { "emp_id" : -1}}]) * 4代表員工>>自己 * db.getCollection('ORG_DEPT_EMP_2015').aggregate([ { $match : { "$and" : [ {'emp_id': '957' }]}}, { "$group": { "_id": { emp_id: "$emp_id", emp_name: "$emp_name" }}}, { "$sort" : { "emp_id" : -1}}]) */ @POST @Path("postEmpList") @Produces({ MediaType.APPLICATION_JSON }) public List<EmpOutput> postEmpList(@FormParam("org_id") String org_id, @FormParam("dept_id") String dept_id, @FormParam("login_id") String login_id, @FormParam("year") String yearString, @FormParam("role") String role){ logger.info("postEmpList>> login id : " +login_id+ ", org_id: " +org_id +", dept_id:" +dept_id +",yearString: "+yearString +", role:" +role); //if (yearString==null || org_id.equals("-1") || dept_id.equals("-1") || login_id==null || login_id.equals("")) if (yearString==null || org_id.equals("-1") || login_id==null || login_id.equals("")) return new ArrayList<EmpOutput>(); String collectName=this.collectionName+yearString; if (!commondServiceImpl.collectionExisted(collectName)) return new ArrayList<EmpOutput>(); Criteria criteriaDefinition = new Criteria(); if (role!=null && "4".equals(role)) { criteriaDefinition.andOperator(Criteria.where("emp_id").is(Integer.valueOf(login_id))); } else { if (dept_id.equals("-1")) criteriaDefinition.andOperator(Criteria.where("org_id").is(Integer.valueOf(org_id))); else criteriaDefinition.andOperator(Criteria.where("org_id").is(Integer.valueOf(org_id)), Criteria.where("dept_id").is(Integer.valueOf(dept_id))); } Aggregation aggregation=newAggregation( match(criteriaDefinition), group("emp_id", "emp_name", "emp_number"), sort(Sort.Direction.ASC, "emp_id") ); AggregationResults groupResults = mongoTemplate.aggregate( aggregation, collectName, EmpOutput.class); List<EmpOutput> aggList = groupResults.getMappedResults(); return aggList; } @POST @Path("postFindFerialName") @Produces({ MediaType.APPLICATION_JSON }) public List<String> postFindFerialName() { List<String> result = Arrays.asList(commondServiceImpl.ferial_names); return result; } /** * get last 3 years list * @return */ @POST @Path("postYearList") @Produces({ MediaType.APPLICATION_JSON }) public List<String> getYearList(){ List<String> resultList=new ArrayList<String>(); Calendar cal=Calendar.getInstance(); for (int i=0; i<3;i++) { int y=cal.get(Calendar.YEAR)-i; resultList.add(String.valueOf(y)); } return resultList; } /** * 取得login user's employee information including role */ @POST @Path("postLoginEmp") @Produces({ MediaType.APPLICATION_JSON }) public EmpOutput postLoginEmp(@FormParam("login_id") String login_id, @FormParam("year") String yearString ){ return getEmpOutput(login_id, yearString); } public EmpOutput getEmpOutput(String login_id, String yearString) { logger.info("Login>> login id : " +login_id+ ", yearString: "+yearString); String collectName=this.collectionName+yearString; if (!commondServiceImpl.collectionExisted(collectName)) return null; Criteria criteriaDefinition = new Criteria(); criteriaDefinition.andOperator(Criteria.where("emp_id").is(Integer.valueOf(login_id))); Query query = new Query(); query.addCriteria(criteriaDefinition); List<EmpOutput> result = mongoTemplate.find(query, EmpOutput.class, collectName); if (result.size()>0) { EmpOutput emp=result.get(0); return emp; } return null; } }
package com.sodatracker.apptastic.sodatracker.activities; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.support.v7.widget.helper.ItemTouchHelper; import android.view.Menu; import android.view.MenuItem; import android.view.View; import com.sodatracker.apptastic.sodatracker.R; import com.sodatracker.apptastic.sodatracker.objects.Soda; import com.sodatracker.apptastic.sodatracker.adapters.SodaAdapter; import com.sodatracker.apptastic.sodatracker.SodaTrackerApp; import com.sodatracker.apptastic.sodatracker.utilities.DialogUtils; import com.sodatracker.apptastic.sodatracker.utilities.Utils; import java.util.ArrayList; public class MainActivity extends AppCompatActivity implements SodaAdapter.SodaClickListener { public static final String CLASS_NAME = MainActivity.class.getName(); public static final boolean DEBUG_CLASS = false; public static final boolean DEBUG_METHOD_CALLS = false; public static final String EXTRA_SODA = "extra_extra_soda_plz"; public static final int REQUEST_CODE_FOR_SODA = 1234; private RecyclerView mRecyclerView; private SodaAdapter mSodaAdapter; private ArrayList<Soda> mSodaList = null; private FloatingActionButton mFab; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.main_activity_toolbar); toolbar.setTitle(getString(R.string.app_name)); setSupportActionBar(toolbar); mRecyclerView = (RecyclerView) findViewById(R.id.main_activity_rv); mFab = (FloatingActionButton) findViewById(R.id.fab); initUI(); } private void initUI() { mSodaList = SodaTrackerApp.getSodaList(this); LinearLayoutManager mLayoutManager = new LinearLayoutManager(this); mRecyclerView.setHasFixedSize(true); mRecyclerView.setLayoutManager(mLayoutManager); mSodaAdapter = new SodaAdapter(mSodaList); mSodaAdapter.setSodaClickListener(this); mRecyclerView.setAdapter(mSodaAdapter); ItemTouchHelper.SimpleCallback simpleItemTouchCallback = new ItemTouchHelper.SimpleCallback(ItemTouchHelper.DOWN | ItemTouchHelper.UP, ItemTouchHelper.START | ItemTouchHelper.END) { @Override public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) { int fromPosition = viewHolder.getAdapterPosition(); int targetPosition = target.getAdapterPosition(); if (mSodaList != null) { Soda soda = mSodaList.get(fromPosition); mSodaList.remove(fromPosition); mSodaList.add(targetPosition, soda); mSodaAdapter.updateSodaList(mSodaList); mSodaAdapter.notifyItemMoved(fromPosition, targetPosition); } return true; } @Override public void onSwiped(RecyclerView.ViewHolder viewHolder, int swipeDir) { int position = viewHolder.getAdapterPosition(); mSodaList.remove(position); mSodaAdapter.updateSodaList(mSodaList); mSodaAdapter.notifyItemRemoved(position); } }; ItemTouchHelper itemTouchHelper = new ItemTouchHelper(simpleItemTouchCallback); itemTouchHelper.attachToRecyclerView(mRecyclerView); mFab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { SodaTrackerApp.addMoreSoda(MainActivity.this); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main_activity, menu); MenuItem miAppVersion = menu.findItem(R.id.action_app_version); miAppVersion.setTitle(SodaTrackerApp.MENU_APP_VERSION); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_rate_the_app: startActivity(Utils.rateApp(this)); break; case R.id.action_share_the_app: startActivity(Utils.shareApp(this)); break; case R.id.action_about_the_app: DialogUtils.showAboutAppDialog(this); break; case R.id.action_app_version: startActivity(Utils.rateApp(this)); break; } return super.onOptionsItemSelected(item); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_CODE_FOR_SODA && resultCode == RESULT_OK) { Soda soda = data.getParcelableExtra(EXTRA_SODA); if (soda != null) { if (mSodaList == null) { mSodaList = new ArrayList<>(); } mSodaList.add(soda); SodaTrackerApp.saveSodaList(this, mSodaList); mSodaAdapter.updateSodaList(mSodaList); mSodaAdapter.notifyItemInserted(mSodaList.size() - 1); } } } @Override protected void onPause() { super.onPause(); SodaTrackerApp.saveSodaList(this, mSodaList); } @Override public void onItemLongClick(final int position, View v) { AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(MainActivity.this); dialogBuilder.setTitle("Delete?"); dialogBuilder.setMessage("Are you sure you want to delete this soda?"); dialogBuilder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); dialogBuilder.setPositiveButton("DELETE", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mSodaList.remove(position); mSodaAdapter.updateSodaList(mSodaList); mSodaAdapter.notifyItemRemoved(position); dialog.cancel(); } }); if (!isFinishing()) { dialogBuilder.show(); } } @Override public void onChildClick(int adapterPosition) { mSodaAdapter.notifyItemChanged(adapterPosition); } }
/** * Interface for any class that deals with * trip operators */ /** * @author Killian * @version 15 November 2018 */ import java.util.ArrayList; public interface OperatorInterface { public ArrayList<Trip> getAllTrips( Trip trip ); public void displayTrips(ArrayList<Trip> trips); public void book( Trip trip ); }// End AllTrips interface
/** * SendSoapTestMessage.java * * Last Update $Id: SendSoapTestMessage.java,v 1.1.1.1 2008-07-01 17:47:54 rba Exp $ * * History: * $Log: SendSoapTestMessage.java,v $ * Revision 1.1.1.1 2008-07-01 17:47:54 rba * Initial import of IDETestHarness * */ package org.imo.lrit.test.common; /** * */ import javax.xml.soap.MessageFactory; import javax.xml.soap.SOAPBody; import javax.xml.soap.SOAPMessage; import javax.xml.soap.SOAPException; import javax.xml.ws.Dispatch; import javax.xml.ws.Service; import javax.xml.ws.WebServiceException; import java.net.URL; import java.io.*; import org.imo.lrit.ide.testToIDE.IdeService; import org.imo.lrit.test.common.XMLHelper; import org.w3c.dom.Document; import javax.xml.namespace.QName; import javax.xml.parsers.DocumentBuilderFactory; public class SendSoapTestMessage extends TestBase{ public SendSoapTestMessage(String arg0) { super(arg0); } protected void setUp() throws Exception { // super.setUp(); } protected void tearDown() throws Exception { super.tearDown(); } public static String SendMessageToIDE(URL ideURL, SOAPMessage soapmsg) throws SOAPException, IOException{ String outcome = ""; SOAPMessage genResponse = MessageFactory.newInstance().createMessage(); String responseXML = ""; try{ IdeService svc = new IdeService(ideURL, new QName( XMLHelper.IDE_SERVICE_NS,XMLHelper.IDE_SERVICE_NAME)); Dispatch<SOAPMessage> disp = svc.createDispatch(new QName( XMLHelper.IDE_SERVICE_NS,XMLHelper.IDE_PORT_NAME), SOAPMessage.class,Service.Mode.MESSAGE); genResponse = disp.invoke(soapmsg); responseXML = genResponse.getSOAPBody().toString(); TestDataReadWrite.writeXMLFile("Response.xml", TestProperties("test.xml.spr.ideresponsefile.location"),responseXML); } catch (WebServiceException e) { log.debug("DataCentre not available: " + e); TestDataReadWrite.writeXMLFile("Response.xml", TestProperties("test.xml.spr.ideresponsefile.location"), TestConstants.WEBSERVICES_WEBEXCEPTION_SPR_ERROR); } catch (Exception unexpectedException) { log.debug("Caught an unexpected exception " + "while sending SOAP message : ", unexpectedException); TestDataReadWrite.writeXMLFile("Response.xml", TestProperties("test.xml.spr.ideresponsefile.location"), TestConstants.WEBSERVICES_UNEXPECTED_SPR_ERROR); } return outcome; } public static SOAPMessage createSOAPMessage(String body) throws Exception { ByteArrayInputStream bais = new ByteArrayInputStream(body.getBytes()); SOAPMessage soapmsg = MessageFactory.newInstance().createMessage(); SOAPBody soapbody = soapmsg.getSOAPBody(); Document doc = DocumentBuilderFactory.newInstance() .newDocumentBuilder().parse(bais); soapbody.addDocument(doc); return soapmsg; } }
package loginTest; import org.openqa.selenium.WebDriver; import org.testng.Assert; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import commonMethods.CommonMethods; import driverSetup.DriverSetup; import globalVariables.GlobalVariables; import navigationPages.LoginPage; public class TC_02_IncorrectLogin { //LINEA STANDARD WebDriver driver = DriverSetup.setupDriver(); //LINEA STANDARD Login PageObject crear LoginPage login = new LoginPage(driver); @BeforeTest //LINEA STANDARD metodo que inicia wdriver public void startWebDriver() { driver.get(GlobalVariables.HOME_PAGE); driver.manage().window().maximize(); } @Test public void TC_02() { boolean isTrue = login.incorrectLogin(GlobalVariables.USER_ADMIN, "IncorrectPassword"); //CAMBIAR POR admin123 "IncorrectPassword" PARA QUE SALGA EL TEST CORRECTO Assert.assertTrue(isTrue); } @AfterTest public void closeDriver() { CommonMethods.takeScreenshot(driver, "TC_02_IncorrectLogin"); driver.quit(); } }
package ar.edu.unju.fi.model; import java.time.LocalDate; /** * @author Damian Merlos * Clase Resultado */ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component //Clase bean administrada Resultado public class Resultado { //Atributo de tipo fecha que guarda la fecha del resultado. private LocalDate fechaResultado; @Autowired //Inyección de dependencia hacia un objeto tipo Equipo. //Atributo de tipo Equipo que contiene información del primero equipo. private Equipo equipo1; @Autowired //Inyección de dependencia hacia un objeto tipo Equipo. //Atributo de tipo Equipo que contiene información del segundo equipo. private Equipo equipo2; //Atributo de tipo entero que guarda la cantidad de goles hechas por el primer equipo durante el partido. private int golesEquipo1; //Atributo de tipo entero que guarda la cantidad de goles hechas por el segundo equipo durante el partido. private int golesEquipo2; /** * constructor por defecto */ public Resultado() { // TODO Auto-generated constructor stub } /** * Constructor parametrizado. * @param fechaResultado * @param equipo1 * @param equipo2 * @param golesEquipo1 * @param golesEquipo2 */ public Resultado(LocalDate fechaResultado, Equipo equipo1, Equipo equipo2, int golesEquipo1, int golesEquipo2) { this.fechaResultado = fechaResultado; this.equipo1 = equipo1; this.equipo2 = equipo2; this.golesEquipo1 = golesEquipo1; this.golesEquipo2 = golesEquipo2; } /** * @return the fechaResultado */ public LocalDate getFechaResultado() { return fechaResultado; } /** * @param fechaResultado the fechaResultado to set */ public void setFechaResultado(LocalDate fechaResultado) { this.fechaResultado = fechaResultado; } /** * @return the equipo1 */ public Equipo getEquipo1() { return equipo1; } /** * @param equipo1 the equipo1 to set */ public void setEquipo1(Equipo equipo1) { this.equipo1 = equipo1; } /** * @return the equipo2 */ public Equipo getEquipo2() { return equipo2; } /** * @param equipo2 the equipo2 to set */ public void setEquipo2(Equipo equipo2) { this.equipo2 = equipo2; } /** * @return the golesEquipo1 */ public int getGolesEquipo1() { return golesEquipo1; } /** * @param golesEquipo1 the golesEquipo1 to set */ public void setGolesEquipo1(int golesEquipo1) { this.golesEquipo1 = golesEquipo1; } /** * @return the golesEquipo2 */ public int getGolesEquipo2() { return golesEquipo2; } /** * @param golesEquipo2 the golesEquipo2 to set */ public void setGolesEquipo2(int golesEquipo2) { this.golesEquipo2 = golesEquipo2; } @Override /** * Metodo toString, este metodo muestra los atruibutos en forma de cadena cuando se es invocado. */ public String toString() { return "Resultado [fechaResultado=" + fechaResultado + ", equipo1=" + equipo1 + ", equipo2=" + equipo2 + ", golesEquipo1=" + golesEquipo1 + ", golesEquipo2=" + golesEquipo2 + "]"; } }
package se.rtz.flowchart.poc.flowchart; import org.junit.Test; import se.rtz.flowchart.poc.domän.Kund; import se.rtz.flowchart.poc.domän.Skadeanmälan; import std.StateTransitionException; public class Test1 { @Test public void dödKund() throws StateTransitionException{ Skadeanmälan enSkadeanmälan = Skadeanmälan.medKund(Kund.dödKund()); InkommenSkadeanmälanHandläggare inkommenSkadeanmälan = new InkommenSkadeanmälanHandläggare(); inkommenSkadeanmälan.process(enSkadeanmälan); } @Test public void levandeIckeKund() throws StateTransitionException { Skadeanmälan enSkadeanmälan = Skadeanmälan.medKund(Kund.inteKund()); InkommenSkadeanmälanHandläggare inkommenSkadeanmälan = new InkommenSkadeanmälanHandläggare(); inkommenSkadeanmälan.process(enSkadeanmälan); } @Test public void levandeKund() throws StateTransitionException { Skadeanmälan enSkadeanmälan = Skadeanmälan.medKund(Kund.vanligKund("1")); InkommenSkadeanmälanHandläggare inkommenSkadeanmälan = new InkommenSkadeanmälanHandläggare(); inkommenSkadeanmälan.process(enSkadeanmälan); }}
package hr.fer.utr.lab4; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.LinkedHashMap; public class Parser { public static ArrayList<Character> ulaz; public static LinkedHashMap<Character, String> gramatika; public static void main(String[] args) throws IOException { BufferedReader read = new BufferedReader(new InputStreamReader(System.in)); inicijaliziraj(); postavigramatiku(); String ulaz_str; ulaz_str = read.readLine(); for (int y = 0; y < ulaz_str.length(); ++y) { ulaz.add(ulaz_str.charAt(y)); } //Provjera.provjeri(datoteka); boolean OK = Parsiraj.S(); System.out.println(); if (ulaz.size() == 0 && OK) { System.out.println("DA"); } else System.out.println("NE"); read.close(); } private static void postavigramatiku() { gramatika.put('S', "aAB|bBA"); gramatika.put('A', "bC|a"); gramatika.put('B', "ccSbc|$"); gramatika.put('C', "AA"); } private static void inicijaliziraj() { gramatika = new LinkedHashMap<>(); ulaz = new ArrayList<>(); } }
package com.spaceComment.controller; import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; import javax.servlet.http.*; import java.io.IOException; import java.io.InputStream; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.MultipartConfig; 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 javax.servlet.http.Part; import com.google.gson.Gson; import com.spaceComment.model.*; @MultipartConfig(fileSizeThreshold = 1024 * 1024, maxFileSize = 5 * 1024 * 1024, maxRequestSize = 5 * 5 * 1024 * 1024) @WebServlet("/spacecomment/spacecomment.do") public class SpaceCommentServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doPost(req, res); } public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { req.setCharacterEncoding("UTF-8"); String action = req.getParameter("action"); if ("getOne_For_Display".equals(action)) { List<String> errorMsgs = new LinkedList<String>(); // Store this set in the request scope, in case we need to // send the ErrorPage view. req.setAttribute("errorMsgs", errorMsgs); try { /*************************** 1.接收請求參數 - 輸入格式的錯誤處理 **********************/ String str = req.getParameter("spaceCommentId"); if (str == null || (str.trim()).length() == 0) { errorMsgs.add("請輸入場地明細ID"); } // Send the use back to the form, if there were errors if (!errorMsgs.isEmpty()) { RequestDispatcher failureView = req.getRequestDispatcher("/frontend/spacecomment/spaceCommentHome.jsp"); failureView.forward(req, res); return;// 程式中斷 } if (!errorMsgs.isEmpty()) { RequestDispatcher failureView = req.getRequestDispatcher("/frontend/spacecomment/spaceCommentHome.jsp"); failureView.forward(req, res); return;// 程式中斷 } /*************************** 2.開始查詢資料 *****************************************/ SpaceCommentService spaceCommentSvc = new SpaceCommentService(); SpaceCommentVO spaceCommentVO = spaceCommentSvc.selectOneSpaceComment(str); if (spaceCommentVO == null) { errorMsgs.add("查無資料"); } // Send the use back to the form, if there were errors if (!errorMsgs.isEmpty()) { RequestDispatcher failureView = req.getRequestDispatcher("/frontend/spacecomment/spaceCommentHome.jsp"); failureView.forward(req, res); return;// 程式中斷 } /*************************** 3.查詢完成,準備轉交(Send the Success view) *************/ req.setAttribute("spaceCommentVO", spaceCommentVO); // 資料庫取出的spaceCommentVO物件,存入req String url = "/frontend/spacecomment/listOneSpaceComment.jsp"; RequestDispatcher successView = req.getRequestDispatcher(url); // 成功轉交 listOneSpaceComment.jsp successView.forward(req, res); /*************************** 其他可能的錯誤處理 *************************************/ } catch (Exception e) { errorMsgs.add("無法取得資料:" + e.getMessage()); RequestDispatcher failureView = req.getRequestDispatcher("/frontend/spacecomment/spaceCommentHome.jsp"); failureView.forward(req, res); } } if ("getOne_For_Update".equals(action)) { // 來自listAllSpaceComment.jsp的請求 List<String> errorMsgs = new LinkedList<String>(); // Store this set in the request scope, in case we need to // send the ErrorPage view. req.setAttribute("errorMsgs", errorMsgs); try { /*************************** 1.接收請求參數 ****************************************/ String spaceCommentId = req.getParameter("spaceCommentId"); /*************************** 2.開始查詢資料 ****************************************/ SpaceCommentService spaceCommentSvc = new SpaceCommentService(); SpaceCommentVO spaceCommentVO = spaceCommentSvc.selectOneSpaceComment(spaceCommentId); /*************************** 3.查詢完成,準備轉交(Send the Success view) ************/ req.setAttribute("spaceCommentVO", spaceCommentVO); // 資料庫取出的spaceCommentVO物件,存入req String url = "/frontend/spacecomment/updateSpaceComment.jsp"; RequestDispatcher successView = req.getRequestDispatcher(url);// 成功轉交 updateSpaceComment.jsp successView.forward(req, res); /*************************** 其他可能的錯誤處理 **********************************/ } catch (Exception e) { errorMsgs.add("無法取得要修改的資料:" + e.getMessage()); RequestDispatcher failureView = req.getRequestDispatcher("/frontend/spacecomment/listAllSpaceComment.jsp"); failureView.forward(req, res); } } if ("update".equals(action)) { // 來自updateSpaceComment.jsp的請求 List<String> errorMessages = new LinkedList<String>(); // Store this set in the request scope, in case we need to // send the ErrorPage view. req.setAttribute("errorMsgs", errorMessages); try { /*************************** 1.接收請求參數 - 輸入格式的錯誤處理 **********************/ String spaceCommentId = new String(req.getParameter("spaceCommentId").trim()); if (spaceCommentId == null || spaceCommentId.trim().length() == 0) { errorMessages.add("場地評價ID請勿空白"); } String spaceId = req.getParameter("spaceId"); if (spaceId == null || spaceId.trim().length() == 0) { errorMessages.add("場地ID請勿空白"); } String memId = req.getParameter("memId"); if (memId == null || memId.trim().length() == 0) { errorMessages.add("會員ID請勿空白"); } String spaceCommentContent = req.getParameter("spaceCommentContent"); if (spaceCommentContent == null || spaceCommentContent.trim().length() == 0) { errorMessages.add("評價內容請勿空白"); } Double spaceCommentLevel = null; try { spaceCommentLevel = Double.parseDouble(req.getParameter("spaceCommentLevel").trim()); if(spaceCommentLevel <= 0 || spaceCommentLevel > 5) errorMessages.add("場地評價星等: 請確認"); } catch (NumberFormatException e) { spaceCommentLevel = 0.0; errorMessages.add("場地評價星等錯誤"); } java.sql.Date spaceCommentDate = null; try { spaceCommentDate = java.sql.Date.valueOf(req.getParameter("spaceCommentDate").trim()); } catch (IllegalArgumentException e) { e.printStackTrace(); errorMessages.add("場地評價日期錯誤"); } SpaceCommentVO spaceCommentVO = new SpaceCommentVO(); spaceCommentVO.setSpaceCommentId(spaceCommentId); spaceCommentVO.setSpaceId(spaceId); spaceCommentVO.setMemberId(memId); spaceCommentVO.setSpaceCommentContent(spaceCommentContent); spaceCommentVO.setSpaceCommentLevel(spaceCommentLevel); spaceCommentVO.setSpaceCommentDate(spaceCommentDate); // Send the use back to the form, if there were errors if (!errorMessages.isEmpty()) { req.setAttribute("spaceCommentVO", spaceCommentVO); // 含有輸入格式錯誤的spaceCommentVO物件,也存入req RequestDispatcher failureView = req.getRequestDispatcher("/frontend/spacecomment/updateSpaceComment.jsp"); failureView.forward(req, res); return; // 程式中斷 } /*************************** 2.開始修改資料 *****************************************/ SpaceCommentService spaceCommentSvc = new SpaceCommentService(); spaceCommentVO = spaceCommentSvc.updateSpaceComment(spaceCommentVO); System.out.println(spaceCommentVO); /*************************** 3.修改完成,準備轉交(Send the Success view) *************/ req.setAttribute("spaceCommentVO", spaceCommentVO); String url = "/frontend/spacecomment/listOneSpaceComment.jsp"; RequestDispatcher successView = req.getRequestDispatcher(url); successView.forward(req, res); /*************************** 其他可能的錯誤處理 *************************************/ } catch (Exception e) { errorMessages.add("修改資料失敗:" + e.getMessage()); RequestDispatcher failureView = req.getRequestDispatcher("/frontend/spacecomment/updateSpaceComment.jsp"); failureView.forward(req, res); } } if ("insert".equals(action)) { res.setContentType("text/html; charset=utf-8"); req.setCharacterEncoding("UTF-8"); List<String> errorMessages = new LinkedList<String>(); //Store this set in the request scope, in case we need to //send the ErrorPage view. req.setAttribute("errorMessages", errorMessages); try { /*************************** 1.接收請求參數 - 輸入格式的錯誤處理 **********************/ String spaceId = req.getParameter("spaceId"); if (spaceId == null || spaceId.trim().length() == 0) { errorMessages.add("場地ID請勿空白"); } String memberId = req.getParameter("memberId"); if (memberId == null || memberId.trim().length() == 0) { errorMessages.add("會員ID請勿空白"); } String spaceCommentContent = req.getParameter("spaceCommentContent"); if (spaceCommentContent == null || spaceCommentContent.trim().length() == 0) { errorMessages.add("場地評價內容請勿空白"); } Double spaceCommentLevel = null; try { spaceCommentLevel = Double.parseDouble(req.getParameter("spaceCommentLevel").trim()); if(spaceCommentLevel <= 0 || spaceCommentLevel > 5) errorMessages.add("場地評價星等: 請確認"); } catch (NumberFormatException e) { spaceCommentLevel = 0.0; errorMessages.add("場地評價星等錯誤"); } // java.sql.Date spaceCommentDate = null; // try { // spaceCommentDate = java.sql.Date.valueOf(req.getParameter("spaceCommentDate").trim()); // } catch (IllegalArgumentException e) { // e.printStackTrace(); // errorMessages.add("場地評價日期錯誤"); // } java.util.Date date = new java.util.Date(); java.sql.Date spaceCommentDate = new java.sql.Date(date.getTime()); SpaceCommentVO spaceCommentVO = new SpaceCommentVO(); spaceCommentVO.setSpaceId(spaceId); spaceCommentVO.setMemberId(memberId); spaceCommentVO.setSpaceCommentContent(spaceCommentContent); spaceCommentVO.setSpaceCommentLevel(spaceCommentLevel); spaceCommentVO.setSpaceCommentDate(spaceCommentDate); spaceCommentVO.setSpaceCommStatus("Y"); spaceCommentVO.setSpaceCommStatusEmp("Y"); spaceCommentVO.setSpaceCommStatusComm("Y"); // Send the use back to the form, if there were errors if (!errorMessages.isEmpty()) { req.setAttribute("spaceCommentVO", spaceCommentVO); // 含有輸入格式錯誤的spaceCommentVO物件,也存入req RequestDispatcher failureView = req.getRequestDispatcher("/frontend/spacecomment/updateSpaceComment.jsp"); failureView.forward(req, res); return; // 程式中斷 } /*************************** 2.開始新增資料 ***************************************/ SpaceCommentService spaceCommentSvc = new SpaceCommentService(); spaceCommentVO = spaceCommentSvc.addSpaceComment(spaceCommentVO); Gson gson = new Gson(); String jsonString = gson.toJson(spaceCommentVO); res.getWriter().write(jsonString); System.out.println(jsonString); System.out.println(spaceCommentVO); // /*************************** 3.新增完成,準備轉交(Send the Success view) ***********/ // String url = "/frontend/spacecomment/listAllSpaceComment.jsp"; // RequestDispatcher successView = req.getRequestDispatcher(url); // successView.forward(req, res); /*************************** 其他可能的錯誤處理 **********************************/ } catch (Exception e) { e.printStackTrace(); errorMessages.add(e.getMessage()); RequestDispatcher failureView = req.getRequestDispatcher("/frontend/spacecomment/addSpaceComment.jsp"); failureView.forward(req, res); } } if ("delete".equals(action)) { // 來自listAllSpace.jsp List<String> errorMsgs = new LinkedList<String>(); // Store this set in the request scope, in case we need to // send the ErrorPage view. req.setAttribute("errorMsgs", errorMsgs); try { /*************************** 1.接收請求參數 ***************************************/ String spaceCommentId = new String(req.getParameter("spaceCommentId")); /*************************** 2.開始刪除資料 ***************************************/ SpaceCommentService spaceCommentSvc = new SpaceCommentService(); spaceCommentSvc.deleteSpaceComment(spaceCommentId); /*************************** 3.刪除完成,準備轉交(Send the Success view) ***********/ String url = "/frontend/spacecomment/listAllSpaceComment.jsp"; RequestDispatcher successView = req.getRequestDispatcher(url);// 刪除成功後,轉交回送出刪除的來源網頁 successView.forward(req, res); /*************************** 其他可能的錯誤處理 **********************************/ } catch (Exception e) { errorMsgs.add("刪除資料失敗:" + e.getMessage()); RequestDispatcher failureView = req.getRequestDispatcher("/frontend/spacecomment/listAllspaceComment.jsp"); failureView.forward(req, res); } } } }
/*REALM Stats for logging and maintaining statistics in bukkit servers. Copyright (C) 2013 Rory Finnegan This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package net.bunnehrealm.realmstats.listeners; import net.bunnehrealm.realmstats.REALMStats; import org.bukkit.entity.Bat; import org.bukkit.entity.Chicken; import org.bukkit.entity.Cow; import org.bukkit.entity.Horse; import org.bukkit.entity.IronGolem; import org.bukkit.entity.Ocelot; import org.bukkit.entity.Pig; import org.bukkit.entity.Player; import org.bukkit.entity.Sheep; import org.bukkit.entity.Snowman; import org.bukkit.entity.Squid; import org.bukkit.entity.Villager; import org.bukkit.entity.Wolf; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityDeathEvent; public class AnimalKillListener implements Listener { REALMStats plugin = REALMStats.plugin; public AnimalKillListener(REALMStats instance){ this.plugin = instance; } @EventHandler(priority = EventPriority.MONITOR) public void onKill(EntityDeathEvent e) { if ((e.getEntity() instanceof Cow || e.getEntity() instanceof Chicken || e.getEntity() instanceof Horse || e.getEntity() instanceof Ocelot || e.getEntity() instanceof Pig || e.getEntity() instanceof Sheep || e.getEntity() instanceof Bat || e.getEntity() instanceof Wolf || e.getEntity() instanceof Snowman || e.getEntity() instanceof IronGolem || e.getEntity() instanceof Squid || e.getEntity() instanceof Villager)&& (e.getEntity().getKiller() instanceof Player)) { Player p = e.getEntity().getKiller(); plugin.players.set(p.getUniqueId() + ".killedanimals", plugin.players.getInt(p.getUniqueId() + ".killedanimals") + 1); } } }