text
stringlengths
10
2.72M
package com.ssgl.bean; public class RoomRank { private String id; private Integer grade; private String title; private Integer lowScore; private Integer maxScore; public String getId() { return id; } public void setId(String id) { this.id = id == null ? null : id.trim(); } public Integer getGrade() { return grade; } public void setGrade(Integer grade) { this.grade = grade; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title == null ? null : title.trim(); } public Integer getLowScore() { return lowScore; } public void setLowScore(Integer lowScore) { this.lowScore = lowScore; } public Integer getMaxScore() { return maxScore; } public void setMaxScore(Integer maxScore) { this.maxScore = maxScore; } }
package com.encore.test1; import java.util.Scanner; /* * 제어문을 사용한 알고리즘을 간단하게 다뤄보자.. */ public class CatchAMouseTest { private static String algoSolv(int catA, int catB, int mouseC) { //if, else if, else 구문과 Math.abs()를 이용해서 알고리즘을 구현하세요 if(Math.abs(mouseC-catA)<Math.abs(mouseC-catB)) return "CatA Catch!!"; else if(Math.abs(mouseC-catA)>Math.abs(mouseC-catB)) return "CatB Catch!!"; else return "Mouse Escapes!!"; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); //순서대로 3개의 값을 입력받는다. int catA = sc.nextInt(); int catB = sc.nextInt(); int mouseC = sc.nextInt(); String result = algoSolv(catA, catB, mouseC); System.out.println("Result :: "+result); } }
/* This class models a Cell from the minesweeper game grid */ package logic; import java.io.*; /** * * @author Eric */ public class Cell implements Serializable{ private boolean hasMine; private boolean isFlagged; private boolean isOpen; private int[] location; private int surroundingMines; private boolean guiOpen; public Cell(int x, int y) { isFlagged = false; isOpen = false; guiOpen = false; location = new int[2]; location[0] = x; location[1] = y; surroundingMines = 0; } public void setHasMine(boolean val) { hasMine = val; } public boolean getHasMine() { return hasMine; } public void setIsFlagged(boolean val) { isFlagged = val; } public boolean getIsFlagged() { return isFlagged; } public int[] getLocation() { return location; } public void setIsOpen(boolean val) { isOpen = val; } public boolean getIsOpen() { return isOpen; } public void setGuiOpen(boolean val) { guiOpen = val; } public boolean getGuiOpen() { return guiOpen; } public void setSurroundingMines(int mines) { surroundingMines = mines; } public int getSurroundingMines() { return surroundingMines; } }
package com.craw_data.utils; public class BaseLinks { public static final String charSetName = "UTF-8"; public static final String udemyLink = "https://www.udemy.com/"; }
package Modeles; import java.util.ArrayList; import Objets.Enrollment; public class MEnrollments extends MDefaultTable<Enrollment> { private static final long serialVersionUID = 1L; public MEnrollments() { super(); data = new ArrayList<Enrollment>(); String[] newheaders = {"Cours", "Etudiant"}; setHeaders(newheaders); } public Object getValueAt(int rowIndex, int columnIndex) { switch(columnIndex) { case 0: return data.get(rowIndex).getCourse(); case 1: return data.get(rowIndex).getStudent(); default: return null; } } }
package tencent; import java.util.Collection; import java.util.List; /** * Created by jiajia on 2017/8/14. */ public class IntersectionOfTwoSets { public List<Integer> solution(List<Integer> integers1, List<Integer> integers2) { return null; } }
package sk.itsovy.strausz.projectdp; public class Main { public static void main(String[] args) { ProteinFactory proteinFactory = new ProteinFactory(); Protein p1 = proteinFactory.getProtein("Whey"); Protein p2 = proteinFactory.getProtein("Egg"); Protein p3 = proteinFactory.getProtein("Casein"); p1.print(); p2.print(); p3.print(); } }
package de.raidcraft.skillsandeffects.pvp.skills.physical; import com.sk89q.minecraft.util.commands.CommandContext; import de.raidcraft.skills.api.character.CharacterTemplate; import de.raidcraft.skills.api.combat.EffectType; import de.raidcraft.skills.api.combat.action.Attack; import de.raidcraft.skills.api.exceptions.CombatException; import de.raidcraft.skills.api.hero.Hero; import de.raidcraft.skills.api.persistance.SkillProperties; import de.raidcraft.skills.api.profession.Profession; import de.raidcraft.skills.api.skill.AbstractSkill; import de.raidcraft.skills.api.skill.SkillInformation; import de.raidcraft.skills.api.trigger.CommandTriggered; import de.raidcraft.skills.effects.disabling.KnockBack; import de.raidcraft.skills.tables.THeroSkill; import org.bukkit.configuration.ConfigurationSection; /** * @author Silthus */ @SkillInformation( name = "Whirlwind", description = "Fügt allen Gegenern im Umkreis physischen Schaden zu.", types = {EffectType.PHYSICAL, EffectType.DAMAGING, EffectType.HARMFUL, EffectType.AREA} ) public class Whirlwind extends AbstractSkill implements CommandTriggered { private int maxTargets = 4; private boolean knockBack = false; public Whirlwind(Hero hero, SkillProperties data, Profession profession, THeroSkill database) { super(hero, data, profession, database); } @Override public void load(ConfigurationSection data) { maxTargets = data.getInt("max-targets", 4); knockBack = data.getBoolean("knockback", false); } @Override public void runCommand(CommandContext args) throws CombatException { int i = 0; for (CharacterTemplate target : getNearbyTargets(false)) { try { if (target.equals(getHolder())) { continue; } if (!(i < maxTargets)) { break; } Attack<CharacterTemplate, CharacterTemplate> attack = attack(target); attack.run(); if (!attack.isCancelled() && knockBack) { addEffect(getHolder().getPlayer().getLocation(), target, KnockBack.class); } } catch (CombatException ignored) { } i++; } } }
package com.technology.share.service.impl; import com.technology.share.domain.BackService; import com.technology.share.mapper.BackServiceMapper; import com.technology.share.service.BackServiceService; import org.springframework.stereotype.Service; /** * @description: 后台服务Service实现 * @author: 朱俊亮 * @time: 2021-03-26 11:55 */ @Service public class BackServiceServiceImpl extends BaseServiceImpl<BackServiceMapper, BackService> implements BackServiceService { }
package com.atn.app.webservices; import java.util.ArrayList; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import com.atn.app.datamodels.LoopForumPostData; import com.atn.app.utils.HttpUtility; import com.atn.app.webservices.WebserviceType.ServiceType; public class LoopForumPostWebService extends WebserviceBase { private static final String FORUM_POST_API = "/forum"; private LoopForumPostWebserviceListener forumPostWebserviceListener; private LoopForumPostData postData; public LoopForumPostWebService() { super(HttpUtility.BASE_SERVICE_URL + FORUM_POST_API); setRequestType(RequestType.POST); setWebserviceType(ServiceType.FORUM_POST); setWebserviceListener(mWebserviceListener); } public void setForumPostWebserviceListener(LoopForumPostWebserviceListener listener) { forumPostWebserviceListener = listener; } public void setForumPostData(LoopForumPostData data) { this.postData = data; } private WebserviceListener mWebserviceListener = new WebserviceListener() { @Override public void onSetUrlError(ServiceType serviceType, Exception ex) { if(forumPostWebserviceListener != null) { if(serviceType == ServiceType.FORUM_POST) { forumPostWebserviceListener.onFailed(WebserviceError.URL_ERROR, ex.getMessage()); } } } @Override public void onServiceResult(ServiceType serviceType, String result) { if(forumPostWebserviceListener != null) { if(serviceType == ServiceType.FORUM_POST) { forumPostWebserviceListener.onSuccess(postData, result); } } } @Override public void onServiceError(ServiceType serviceType, int errorCode, String errorMessage) { if(forumPostWebserviceListener != null) { if(serviceType == ServiceType.FORUM_POST) { forumPostWebserviceListener.onFailed(errorCode, errorMessage); } } } @Override public void onNoInternet(ServiceType serviceType, Exception ex) { if(forumPostWebserviceListener != null) { if(serviceType == ServiceType.FORUM_POST) { forumPostWebserviceListener.onFailed(WebserviceError.INTERNET_ERROR, ex.getMessage()); } } } }; /** * Return synchronous web service response from the server. This should be called within the background * thread. * * @return web service response. */ public WebserviceResponse getSynchronousResponse() { try { ArrayList<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(); nameValuePair.add(new BasicNameValuePair(LoopForumPostData.USER_ID, postData.getUserId())); nameValuePair.add(new BasicNameValuePair(LoopForumPostData.DATE, postData.getMessageDate())); nameValuePair.add(new BasicNameValuePair(LoopForumPostData.LAT, postData.getlatitude())); nameValuePair.add(new BasicNameValuePair(LoopForumPostData.LNG, postData.getlongitude())); if(postData.getMessage() != null) { nameValuePair.add(new BasicNameValuePair(LoopForumPostData.USER_TEXT, postData.getMessage())); } if(postData.getImageUrl() != null) { nameValuePair.add(new BasicNameValuePair(LoopForumPostData.IMAGE, postData.getImageUrl())); setFile(LoopForumPostData.IMAGE, postData.getImageUrl()); } if(postData.getForumId() != null) { nameValuePair.add(new BasicNameValuePair(LoopForumPostData.FORUM_ID, postData.getForumId())); } setPostData(nameValuePair); } catch (Exception e) { e.printStackTrace(); } return doRequestSynch(); } /** * Asynchronously calls the web service to get the registered ATN venues. Response of this web service can * be captured from web service listener. */ public void getResponse() { try { ArrayList<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(); nameValuePair.add(new BasicNameValuePair(LoopForumPostData.USER_ID, postData.getUserId())); nameValuePair.add(new BasicNameValuePair(LoopForumPostData.DATE, postData.getMessageDate())); nameValuePair.add(new BasicNameValuePair(LoopForumPostData.LAT, postData.getlatitude())); nameValuePair.add(new BasicNameValuePair(LoopForumPostData.LNG, postData.getlongitude())); if(postData.getMessage() != null) { nameValuePair.add(new BasicNameValuePair(LoopForumPostData.USER_TEXT, postData.getMessage())); } if(postData.getImageUrl() != null) { nameValuePair.add(new BasicNameValuePair(LoopForumPostData.IMAGE, postData.getImageUrl())); setFile(LoopForumPostData.IMAGE, postData.getImageUrl()); } if(postData.getForumId() != null) { nameValuePair.add(new BasicNameValuePair(LoopForumPostData.FORUM_ID, postData.getForumId())); } setPostData(nameValuePair); doRequestAsync(); } catch (Exception e) { e.printStackTrace(); } } }
package communication.netty; import communication.CommunicationHandler; import communication.CommunicationManager; import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslContextBuilder; import java.io.File; /** * A factory for creating a {@link NettyCommunicationManager}. */ public class NettyCommunicationManagerFactory { CommunicationHandler handler; int port; File cert; File key; /** * @param handler the handler managing incoming requests * @param port the port to be used for communication * @param cert a cert file used for secure communication * @param key a private key file used for secure communication */ public NettyCommunicationManagerFactory(CommunicationHandler handler, int port, File cert, File key) { this.handler = handler; this.port = port; this.cert = cert; this.key = key; } /** * @return a secure {@link CommunicationManager} if valid cert and key files were provided, otherwise an insecure {@link CommunicationManager} */ public CommunicationManager create() { SslContext sslContext = null; try { sslContext = SslContextBuilder.forServer(cert, key).build(); } catch (Exception e) { } NettyCommunicationManager manager; if(sslContext == null) { manager = new NettyCommunicationManager(handler, port); } else { manager = new NettyCommunicationManager(handler, port, sslContext); } return manager; } }
package database; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.Optional; public class DMLStatement { private String sql; private Optional<InputMapper> inputMapper; public DMLStatement(String sql, InputMapper inputMapper) { this.sql = Objects.requireNonNull(sql); this.inputMapper = Optional.ofNullable(inputMapper); } public List<Integer> execute() throws SQLException { List<Integer> resultList = new ArrayList<>(); ResultSet rs = H2Database.getInstance().executeUpdate(this.sql, this.inputMapper); while (rs.next()) { resultList.add(rs.getInt(1)); } rs.close(); return resultList; } }
package chapter08; import java.util.Scanner; public class Exercise08_15 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Enter five points: "); double[][] points = new double[5][2]; for (int i = 0; i < points.length; i++) { points[i][0] = input.nextDouble(); points[i][1] = input.nextDouble(); } if (sameLine(points)) { System.out.println("The five points are on the same line"); } else { System.out.println("The five points are not on the same line"); } } public static double[][] findMaxDistancePoints(double[][] points) { double maxDistance = Double.MIN_VALUE; int firstPointIndex = -1; int secondPointIndex = -1; for (int i = 0; i < points.length - 1; i++) { for (int j = i + 1; j < points.length; j++) { double distance = Math .sqrt(Math.pow(points[i][0] - points[j][0], 2) + Math.pow(points[i][1] - points[j][1], 2)); if (distance > maxDistance) { maxDistance = distance; firstPointIndex = i; secondPointIndex = j; } } } double[][] pointPair = new double[2][2]; pointPair[0][0] = points[firstPointIndex][0]; pointPair[0][1] = points[firstPointIndex][1]; pointPair[1][0] = points[secondPointIndex][0]; pointPair[1][1] = points[secondPointIndex][1]; return pointPair; } public static boolean sameLine(double[][] points) { // return (x1 - x0) * (y2 - y0) - (x2 - x0) * (y1 - y0) == 0; double[][] pointPair = findMaxDistancePoints(points); double x0 = pointPair[0][0]; double x1 = pointPair[0][1]; double y0 = pointPair[1][0]; double y1 = pointPair[1][1]; for (int i = 0; i < pointPair.length; i++) { double x2 = points[i][0]; double y2 = points[i][1]; if ((x1 - x0) * (y2 - y0) - (x2 - x0) * (y1 - y0) != 0) { return false; } } return true; } }
package com.github.ezauton.recorder.base; import com.github.ezauton.core.robot.implemented.TankRobotTransLocDriveable; import com.github.ezauton.core.utils.Clock; import com.github.ezauton.recorder.SequentialDataRecorder; import com.github.ezauton.recorder.base.frame.TankDriveableFrame; import java.util.concurrent.TimeUnit; public class TankDriveableRecorder extends SequentialDataRecorder<TankDriveableFrame> { private TankRobotTransLocDriveable transLocDriveable; public TankDriveableRecorder(String name, Clock clock, TankRobotTransLocDriveable transLocDriveable) { super(name, clock); this.transLocDriveable = transLocDriveable; } private TankDriveableRecorder() { } @Override public boolean checkForNewData() { dataFrames.add(new TankDriveableFrame( stopwatch.read(TimeUnit.MILLISECONDS), transLocDriveable.getLastLeftTarget(), transLocDriveable.getLastRightTarget() )); return true; } // @Override // public IDataProcessor createDataProcessor() // { // return null; // } }
package server.models; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.OneToMany; import java.util.Set; @Entity public class Kompetenz extends Persistent { private String beschreibung; @OneToMany(mappedBy = "kompetenz", fetch = FetchType.EAGER) private Set<Qualifikation> qualifikationen; @OneToMany(mappedBy = "kompetenz", fetch = FetchType.EAGER) private Set<Anforderung> anforderungen; public String getBeschreibung() { return beschreibung; } public void setBeschreibung(String beschreibung) { this.beschreibung = beschreibung; } public Set<Qualifikation> getQualifikationen() { return qualifikationen; } public Set<Anforderung> getAnforderungen() { return anforderungen; } /** * Aktualisiert beide Seiten der @OneToMany-Beziehung. */ public void setQualifikationen(Set<Qualifikation> qualifikationen) { this.qualifikationen = setOneToMany(qualifikationen, Qualifikation::setKompetenz, Kompetenz::getQualifikationen); } /** * Aktualisiert beide Seiten der @OneToMany-Beziehung. */ public void setAnforderungen(Set<Anforderung> anforderungen) { this.anforderungen = setOneToMany(anforderungen, Anforderung::setKompetenz, Kompetenz::getAnforderungen); } }
package _do.com.scala.service; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebResult; import javax.jws.WebService; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.ws.Action; import javax.xml.ws.RequestWrapper; import javax.xml.ws.ResponseWrapper; /** * This class was generated by the JAX-WS RI. * JAX-WS RI 2.2.8 * Generated source version: 2.2 * */ @WebService(name = "ServicePort", targetNamespace = "http://scala.com.do/ports") @XmlSeeAlso({ _do.com.scala.security.ws_policy.ObjectFactory.class, _do.com.scala.types.ObjectFactory.class }) public interface ServicePort { /** * * @param name * @return * returns java.lang.String */ @WebMethod(operationName = "GetService") @WebResult(name = "service", targetNamespace = "http://scala.com.do/types") @RequestWrapper(localName = "GetService", targetNamespace = "http://scala.com.do/types", className = "_do.com.scala.types.GetServiceRequest") @ResponseWrapper(localName = "GetServiceResponse", targetNamespace = "http://scala.com.do/types", className = "_do.com.scala.types.GetServiceResponse") @Action(input = "http://scala.com.do/actions/GetServiceRequest", output = "http://scala.com.do/actions/GetServiceResponse") public String getService( @WebParam(name = "name", targetNamespace = "http://scala.com.do/types") String name); }
package algorithm.baekjoon; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer; public class _15686_ChickenDelivery { static int N, M; static int answer; static ArrayList<int[]> chickenHouse; static ArrayList<int[]> house; static int[] selected; static int size; public static void main(String[] args) throws IOException { // 입력 BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine(), " "); // " " 제시해주는 것이 조금이라도 효율적 N = Integer.parseInt(st.nextToken()); M = Integer.parseInt(st.nextToken()); chickenHouse = new ArrayList<>(); house = new ArrayList<>(); answer = Integer.MAX_VALUE; int tmp; for (int i = 0; i < N; i++) { st = new StringTokenizer(br.readLine()); for (int j = 0; j < N; j++) { tmp = Integer.parseInt(st.nextToken()); if (tmp == 2) { // 치킨집임 chickenHouse.add(new int[]{i, j}); } else if (tmp == 1) { house.add(new int[]{i, j}); } } } // 완전탐색하여 치킨집을 M개만 선택하면서 발생하는 치킨거리를 구한다 size = chickenHouse.size(); selected = new int[M]; comb(0, 0); // 도시의 치킨 거리의 최솟값 출력하기 System.out.println(answer); } private static void comb(int k, int idx) { if (k == M) { // 집을 차례로 뽑으면서 // 선택한 치킨집과의 거리를 구한다 // 치킨거리를 업데이트하면서 가장 작은 값을 고른다 int chickenDist = 0; // 도시의 치킨거리 for (int[] h : house) { int nearChicken = Integer.MAX_VALUE; // 현재 집에서 가장 가까운 치킨거리 for (int i = 0; i < M; i++) { int[] ch = chickenHouse.get(selected[i]); int dist = Math.abs(h[0] - ch[0]) + Math.abs(h[1] - ch[1]); if (nearChicken > dist) nearChicken = dist; } chickenDist += nearChicken; } if (answer > chickenDist) answer = chickenDist; return; } for (int i = idx; i < size; i++) { selected[k] = i; comb(k + 1, i + 1); } } }
package com.ss.flights.flights.AdminRoutes.UpdateRoutes; import com.ss.flights.DBConnection.UpdateRow.UpdateRow; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Component; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @CrossOrigin(origins = "http://localhost:3000", maxAge = 3600) @RequestMapping("/admin") @Component @ResponseBody public class UpdateRoutes { @Autowired UpdateRow update; // modular universal update single table/col post map @PutMapping("/{table}/{item}/{id}") // update any single table/row // as a string format such as; airport,iata_id='LLL',city='Lingenberry' public String updateRow(@PathVariable("table") String table,@PathVariable("item") String item,@PathVariable("id") String id,@RequestBody String data) { // getting new update method from updatecols class try { update.updateRow(table, item, id, data); HttpStatus status = HttpStatus.OK; String statusString = status.toString(); return statusString+" "+item+" "+id+" Updated!"; } catch (Exception e) { // TODO: handle exception } return data + " Updated to Col and Table"; } }
package org.firstinspires.ftc.teamcode.robot; import com.qualcomm.robotcore.hardware.DcMotorEx; import com.qualcomm.robotcore.hardware.HardwareMap; import org.firstinspires.ftc.teamcode.util.Encoder; public class Odometry { Hardware robot; private final float lateralDistance = 15.75f; private final float forwardOffset = 2.0f; private final float wheelRadius = 0.69f; private final float gearRatio = 1.0f; private final float ticksPerRev = 8192.0f; private float[] encoderPosPast = {0.0f, 0.0f, 0.0f}; private float[] position = {0.0f, 0.0f, 0.0f}; public Odometry(Hardware hardware) { robot = hardware; } public void init() { encoderPosPast[0] = (float) robot.leftEncoder.getCurrentPosition(); encoderPosPast[1] = (float) robot.frontEncoder.getCurrentPosition(); encoderPosPast[2] = (float) robot.rightEncoder.getCurrentPosition(); } public void updatePosition() { float[] encoderChange = new float[3]; encoderChange[0] = encoderTicksToInches(robot.leftEncoder.getCurrentPosition() - encoderPosPast[0]); encoderChange[1] = encoderTicksToInches(robot.frontEncoder.getCurrentPosition() - encoderPosPast[1]); encoderChange[2] = encoderTicksToInches(robot.rightEncoder.getCurrentPosition() - encoderPosPast[2]); float[] posChange = new float[3]; float[] posChangeLoc = new float[3]; posChangeLoc[0] = (encoderChange[0] + encoderChange[2]) / 2.0f; posChangeLoc[1] = encoderChange[1] - forwardOffset * (encoderChange[0] - encoderChange[2]) / lateralDistance; posChangeLoc[2] = (encoderChange[0] - encoderChange[2]) / lateralDistance; posChange[0] = posChangeLoc[0] * (float) Math.cos(position[2]) - posChangeLoc[1] * (float) Math.sin(position[2]); posChange[1] = posChangeLoc[0] * (float) Math.sin(position[2]) + posChangeLoc[1] * (float) Math.cos(position[2]); posChange[2] = posChangeLoc[2]; position[0] += posChange[0]; position[1] += posChange[1]; position[2] += posChange[2]; position[2] = (position[2] + 2 * (float) Math.PI) % (2 * (float) Math.PI); encoderPosPast[0] = (float) robot.leftEncoder.getCurrentPosition(); encoderPosPast[1] = (float) robot.frontEncoder.getCurrentPosition(); encoderPosPast[2] = (float) robot.rightEncoder.getCurrentPosition(); } public float encoderTicksToInches(double ticks) { return (float) (wheelRadius * 2 * Math.PI * gearRatio * ticks / ticksPerRev); } public float getX() { return position[0]; } public float getY() { return position[1]; } public float getW() { return position[2]; } }
package com.neo4j.Utils; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Comparator; import java.util.Date; import java.util.List; import org.neo4j.graphdb.Direction; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Transaction; import org.neo4j.graphdb.index.Index; import org.neo4j.graphdb.index.IndexHits; import org.neo4j.graphdb.traversal.Evaluators; import org.neo4j.graphdb.traversal.TraversalDescription; import org.neo4j.graphdb.traversal.Uniqueness; import com.GraphData.Model.AccountProfile; import com.GraphData.Model.Newsfeed; import com.neo4j.Helper.EmbeddedNeo4j; import com.neo4j.Helper.EmbeddedNeo4j.RelTypes; class MyComparator implements Comparator<Newsfeed>{ public int compare(Newsfeed n1, Newsfeed n2 ){ SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date d1 = null; try { d1 = df.parse(n1.getTime()); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } Date d2 = null; try { d2 = df.parse(n2.getTime()); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } long diff = d1.getTime() - d2.getTime(); if(diff > 0){ return 1; } else if(diff < 0){ return -1; } else{ return 0; } } } public class NewsfeedHelper { public static void PublishNewsfeed(String name, String content) { Node people, news; Transaction tx = EmbeddedNeo4j.graphDb.beginTx(); try { Index<Node> peopleIndex = EmbeddedNeo4j.getIndex("people"); System.out.println("user name" + name); IndexHits<Node> hits = peopleIndex.get("name", name); people = hits.getSingle(); Index<Node> newsIndex = EmbeddedNeo4j.getIndex("news"); news = EmbeddedNeo4j.graphDb.createNode(); news.setProperty( "content", content); Date now = new Date(); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");//可以方便地修改日期格式 String time = dateFormat.format( now ); news.setProperty("time", time); news.setProperty("publisher", name); newsIndex.add(news, "content", content); people.createRelationshipTo(news, RelTypes.PUBLISHES); tx.success(); } finally { tx.close(); } return; } public static List<Newsfeed> getNewsfeedList(String name) { List<Newsfeed> news = new ArrayList<Newsfeed>(); Transaction tx = EmbeddedNeo4j.graphDb.beginTx(); String output = ""; Node user; try { Index<Node> peopleIndex = EmbeddedNeo4j.getIndex("people"); IndexHits<Node> hits = peopleIndex.get("name", name); user = hits.getSingle(); TraversalDescription followsTraversal = EmbeddedNeo4j.graphDb.traversalDescription() .depthFirst() .relationships(RelTypes.FOLLOWS, Direction.OUTGOING) .uniqueness(Uniqueness.RELATIONSHIP_GLOBAL); TraversalDescription publishTraversal = EmbeddedNeo4j.graphDb.traversalDescription() .depthFirst() .relationships(RelTypes.PUBLISHES, Direction.OUTGOING) .uniqueness(Uniqueness.RELATIONSHIP_GLOBAL); for (Node follow : followsTraversal .evaluator(Evaluators.toDepth(1)) .traverse(user) .nodes()) { for(Node currentNew : publishTraversal .traverse(follow) .nodes()) { try { Newsfeed n = new Newsfeed(); n.setContent(currentNew.getProperty("content").toString()); n.setPublisher(currentNew.getProperty("publisher").toString()); n.setTime(currentNew.getProperty("time").toString()); news.add(n); System.out.println("add success"); output += n.getContent(); } catch(Exception e) { System.out.println("no content"); } } } System.out.println("news:\n" + output); } finally { tx.close(); } news.sort(new MyComparator()); return news; } public static List<Newsfeed> getUserNewsfeedList(String name) { List<Newsfeed> news = new ArrayList<Newsfeed>(); Transaction tx = EmbeddedNeo4j.graphDb.beginTx(); String output = ""; Node user; try { Index<Node> peopleIndex = EmbeddedNeo4j.getIndex("people"); IndexHits<Node> hits = peopleIndex.get("name", name); user = hits.getSingle(); TraversalDescription publishTraversal = EmbeddedNeo4j.graphDb.traversalDescription() .depthFirst() .relationships(RelTypes.PUBLISHES, Direction.OUTGOING) .uniqueness(Uniqueness.RELATIONSHIP_GLOBAL); for(Node currentNew : publishTraversal .traverse(user) .nodes()) { try { Newsfeed n = new Newsfeed(); n.setContent(currentNew.getProperty("content").toString()); n.setPublisher(currentNew.getProperty("publisher").toString()); n.setTime(currentNew.getProperty("time").toString()); news.add(n); System.out.println("add success"); output += n.getContent(); } catch(Exception e) { System.out.println("no content"); } } } finally { tx.close(); } news.sort(new MyComparator()); return news; } }
/** * Kiva objects can perform actions such as moving around * and picking and dropping items. * A Kiva object's attributes include it's current location on a map, * current direction it's facing, the map layout that it's moving on, status of * whether it's carrying a pod, if it has successfully dropped a pod and a * motor life time that indicates how much of it's motor life has been spent. * * @author Rene B. Dena * @version 8/10/2021 */ import edu.duke.Point; public class Kiva { Point currentLocation; FacingDirection directionFacing; FloorMap map; boolean carryingPod; boolean successfullyDropped; //72,000,000,000 milliseconds in 20,000 hours = robot motor life time double motorLifetime; /** * Creates a Kiva robot instance using only a FloorMap. * @param map FloorMap of the area. Includes the starting location of * the Kiva robot, location of the boundaries, obstacles, pod and drop-zone. */ public Kiva(FloorMap map) { this.currentLocation = map.getInitialKivaLocation(); directionFacing = FacingDirection.UP; carryingPod = false; successfullyDropped = false; this.map= map; motorLifetime=0; } /** * Constructor for Kiva object. * @param newPoint The initial starting Location of the Kiva robot. */ public Kiva (Point newPoint) { this.currentLocation = newPoint; directionFacing = FacingDirection.UP; motorLifetime=0; } /** * Creates a Kiva robot instance using a FloorMap and a Point to set * the starting location of the Kiva robot. * @param map FloorMap of the area. Includes the locations of the Kiva robot, * boudaries, obstacles, pod and drop-zone. * @param currentLocation Starting location of the Kiva robot. */ public Kiva(FloorMap map,Point newPoint) { this.currentLocation = newPoint; directionFacing = FacingDirection.UP; this.map= map; motorLifetime=0; } /** * Returns the current location of the Kiva object. * @return the current location as a * Point (x-y coordinate). */ public Point getCurrentLocation() { return currentLocation; } /** * Returns true if Kiva is carrying the pod and false if not. */ public boolean isCarryingPod() { return carryingPod; } /** * Returns true if Kiva successfully dropped the pod and false if not. */ public boolean isSuccessfullyDropped() { return successfullyDropped; } /** * Returns the motorLifetime utilized by the Kiva, measured in milliseconds. */ public double getMotorLifetime() { return motorLifetime; } /** * Adds 1000 milliseconds to the motorLifetime * (indicating that another 1000 milliseconds have been used). */ public void incrementMotorLifetime() { motorLifetime += 1000; } /** * Depending on the KivaCommand it receives, move() will update the * current location, the direction the robot is pointing, * whether it is carrying a pod or if the pod has been successfully dropped. * @param command KivaCommand that indicates the specific movement the * Kiva robot should perform. * @see #moveForward() * @see #moveTurn_Left() * @see #moveTurn_Right() * @see #Take() * @see #Drop() */ public void move(KivaCommand command) { //System.out.println(this.map.getObjectAtLocation(this.currentLocation)); //System.out.println(this.currentLocation); switch(command) { case FORWARD: this.moveForward(); break; case TURN_LEFT: this.moveTurn_Left(); break; case TURN_RIGHT: this.moveTurn_Right(); break; case TAKE: this.Take(); break; case DROP: this.Drop(); break; default: this.moveForward(); } } //*** HELPER METHODS FOR move(KivaCommand command) method private void moveForward() { //WHEN FACING UP Point temp = this.currentLocation; int x = temp.getX(); int y= temp.getY(); //Obstacle int oldX= x; int oldY=y; if(directionFacing==FacingDirection.UP) { y--; } else if( directionFacing==FacingDirection.LEFT) { x--; } else if( directionFacing==FacingDirection.DOWN) { y++; } else if( directionFacing==FacingDirection.RIGHT) { x++; } this.currentLocation= new Point(x,y); if(x < 0 || x > this.map.getMaxColNum()) { this.currentLocation=new Point (oldX, oldY); throw new IllegalMoveException("Out of bounds"); } if(y < 0 || y > this.map.getMaxRowNum()) { this.currentLocation=new Point (oldX, oldY); throw new IllegalMoveException("Out of bounds"); } if(this.map.getObjectAtLocation(this.currentLocation)==FloorMapObject.OBSTACLE) { Point tempPoint = new Point(x,y); this.currentLocation=new Point (oldX, oldY); throw new IllegalMoveException(String.format("IllegalMoveException: Can't move onto an obstacle at " + tempPoint+"!")); } this.incrementMotorLifetime(); } //WHEN FACING DOWN public FacingDirection getDirectionFacing() { return directionFacing; } //WHEN FACING LEFT private void moveTurn_Left() { this.incrementMotorLifetime(); if(directionFacing==FacingDirection.UP) { directionFacing = FacingDirection.LEFT; } else if( directionFacing==FacingDirection.LEFT) { directionFacing=FacingDirection.DOWN; } else if( directionFacing==FacingDirection.DOWN) { directionFacing=FacingDirection.RIGHT; } else if( directionFacing==FacingDirection.RIGHT) { directionFacing=FacingDirection.UP; } } //WHEN FACING RIGHT private void moveTurn_Right() { this.incrementMotorLifetime(); if(directionFacing==FacingDirection.UP) { directionFacing = FacingDirection.RIGHT; } else if( directionFacing==FacingDirection.LEFT) { directionFacing=FacingDirection.UP; } else if( directionFacing==FacingDirection.DOWN) { directionFacing=FacingDirection.LEFT; } else if( directionFacing==FacingDirection.RIGHT) { directionFacing=FacingDirection.DOWN; } } /** * Kiva object will take/pick up pod. * This will throw a NoPodException if it is already holding a pod * or, if there is no pod at the current location. */ private void Take() { if(this.map.getObjectAtLocation(this.currentLocation)==FloorMapObject.POD) { if (!this.isCarryingPod()) { carryingPod= true; } else { throw new NoPodException("currently carrying POD"); } } else { throw new NoPodException(String.format("NoPodException: Can't take nonexistent pod from location " + this.currentLocation+"!")); } } /** * Kiva object will drop pod. * This will throw a IllegalMoveException if it is not holding a pod at the * time of the drop or, an IllegalDropZoneException if it is not * at a drop-zone location. */ private void Drop() { if(this.map.getObjectAtLocation(this.currentLocation)==FloorMapObject.DROP_ZONE) { if (this.isCarryingPod()) { carryingPod= false; this.successfullyDropped=true; } else { throw new IllegalDropZoneException("No POD carried"); //System.out.println("I'm sorry.The Kiva Robot did not pick up the pod and then drop it off in the right place"); } } else { throw new IllegalDropZoneException(String.format("IllegalDropZoneException: Can't just drop pods willy-nilly at " + this.currentLocation +"!")); } } }
package ru.sg_studio.escapegame.rendering.immediate; public interface IImmediateModeGroupedDrawable { public void draw(Object grouper,float alpha); }
/*请实现两个函数,分别用来序列化和反序列化二叉树 二叉树的序列化是指:把一棵二叉树按照某种遍历方式的结果以某种格式保存为字符串, 从而使得内存中建立起来的二叉树可以持久保存。序列化可以基于先序、中序、后序、层序的二叉树遍历方式来进行修改, 序列化的结果是一个字符串,序列化时通过 某种符号表示空节点(#),以 ! 表示一个结点值的结束(value!)。 二叉树的反序列化是指:根据某种遍历顺序得到的序列化字符串结果str,重构二叉树。*/ public class SerializeBinaryTree { public static void main(String[] args) { TreeNode root = new TreeNode(0); root.left = new TreeNode(1); root.right = new TreeNode(2); SerializeBinaryTree serializeBinaryTree = new SerializeBinaryTree(); System.out.println(serializeBinaryTree.Serialize(root)); serializeBinaryTree.Deserialize(serializeBinaryTree.Serialize(root)); } String Serialize(TreeNode root) { if (root == null) { return ""; } StringBuilder stringBuilder = new StringBuilder(); serializeHelper(root, stringBuilder); return stringBuilder.toString(); } private void serializeHelper(TreeNode root, StringBuilder stringBuilder) { if (root == null) { stringBuilder.append("#,"); return; } stringBuilder.append(root.val); stringBuilder.append(","); serializeHelper(root.left, stringBuilder); serializeHelper(root.right, stringBuilder); } int index = -1; TreeNode Deserialize(String str) { if (str.length() == 0) { return null; } String[] strings = str.split(","); return deserializeHelper(strings); } private TreeNode deserializeHelper(String[] strings) { index++; TreeNode root = new TreeNode(0); if (!strings[index].equals("#")) { root.val = Integer.parseInt(strings[index]); root.left = deserializeHelper(strings); root.right = deserializeHelper(strings); return root; } return null; } }
package com.bin.chatrobot.service; import java.util.ArrayList; import java.util.List; import com.bin.chatrobot.domain.Chat; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.bin.chatrobot.domain.Chat; public class ChatService { private DBOpenHelper dbOpenHelper; public ChatService(Context context){ this.dbOpenHelper=new DBOpenHelper(context); } /** * 添加记录 * @param person */ public void save(Chat chat){ SQLiteDatabase db=dbOpenHelper.getWritableDatabase(); db.execSQL("insert into chat(question,answer)values(?,?)", new Object[]{chat.getQuestion(),chat.getAnswer()}); //db.close();关闭数据库 } /** * 查询记录 * @param id 记录ID * @return */ public Chat find(Integer id){ SQLiteDatabase db = dbOpenHelper.getReadableDatabase(); Cursor cursor = db.rawQuery("select * from chat2 where id=?", new String[]{id.toString()}); if(cursor.moveToFirst()){ int chatid = cursor.getInt(cursor.getColumnIndex("id")); String question = cursor.getString(cursor.getColumnIndex("question")); String answer = cursor.getString(cursor.getColumnIndex("answer")); return new Chat(chatid,question,answer); } cursor.close(); return null; } }
package switch2019.project.domain.domainEntities.group; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import switch2019.project.domain.domainEntities.account.Account; import switch2019.project.domain.domainEntities.person.Address; import switch2019.project.domain.domainEntities.person.Email; import switch2019.project.domain.domainEntities.person.Person; import switch2019.project.domain.domainEntities.shared.*; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import static org.junit.jupiter.api.Assertions.*; class GroupTest { /** * Compare the same Group - Should be the Same */ @Test @DisplayName("Compare the same Group - Should be the Same") public void compareTheSameObject() { //Arrange Person person1 = new Person("John", new DateAndTime(1995, 12, 13), new Address("New York"), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("1234@isep.pt")); Person person2 = new Person("Frank", new DateAndTime(1995, 12, 13), new Address("Washington D.C."), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("123@isep.pt")); Group group1 = new Group(new Description("Amigos"), person1.getID()); group1.addMember(person1.getID()); group1.addMember(person2.getID()); //Act boolean result = group1.equals(group1); //Assert assertTrue(result); } /** * Compare a Group with a null Group */ @Test @DisplayName("Compare one Group with a null Group") public void equalsWithNullGroup() { //Arrange Person person1 = new Person("John", new DateAndTime(1995, 12, 13), new Address("New York"), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("1234@isep.pt")); Person person2 = new Person("Frank", new DateAndTime(1995, 12, 13), new Address("Washington D.C."), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("123@isep.pt")); Group group1 = new Group(new Description("Amigos"), person1.getID()); group1.addMember(person1.getID()); group1.addMember(person2.getID()); Group group2 = null; //Act boolean result = group1.equals(group2); //Assert assertFalse(result); } /** * Compare two groups with same description but different members */ @Test @DisplayName("Compare two groups with same members and different description") public void compareGroupsWithSameDescriptionAndDifferentMembers() { //Arrange Person person1 = new Person("John", new DateAndTime(1995, 12, 13), new Address("New York"), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("1234@isep.pt")); Person person2 = new Person("Frank", new DateAndTime(1995, 12, 13), new Address("Washington D.C."), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("12@isep.pt")); Person person3 = new Person("Mary", new DateAndTime(1995, 12, 13), new Address("Detroit"), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("1@isep.pt")); Person person4 = new Person("Vasylia", new DateAndTime(1995, 12, 13), new Address("California"), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("0@isep.pt")); Group group1 = new Group(new Description("Amigos"), person1.getID()); group1.addMember(person1.getID()); group1.addMember(person2.getID()); Group group2 = new Group(new Description("Amigos"), person3.getID()); group2.addMember(person3.getID()); group2.addMember(person4.getID()); //Act boolean result = group1.equals(group2); //Assert assertTrue(result); } /** * Compare two groups with same members but different description */ @Test @DisplayName("Compare two groups with members but different description") public void compareGroupsWithSameMembersButDifferentDescription() { //Arrange Person person1 = new Person("John", new DateAndTime(1995, 12, 13), new Address("New York"), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("1234@isep.pt")); Person person2 = new Person("Frank", new DateAndTime(1995, 12, 13), new Address("Washington D.C."), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("123@isep.pt")); Group group1 = new Group(new Description("Mary's Gift"), person1.getID()); group1.addMember(person1.getID()); group1.addMember(person2.getID()); Group group2 = new Group(new Description("School Trip"), person2.getID()); group2.addMember(person1.getID()); group2.addMember(person2.getID()); //Act boolean result = group1.equals(group2); //Assert assertFalse(result); } /** * Compare two groups with same members and same description */ @Test @DisplayName("Compare two groups with same members and same description") public void compareGroupsWithSameMembersAndSameDescription() { //Arrange Person person1 = new Person("John", new DateAndTime(1995, 12, 13), new Address("New York"), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("1234@isep.pt")); Person person2 = new Person("Frank", new DateAndTime(1995, 12, 13), new Address("Washington D.C."), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("123@isep.pt")); Group group1 = new Group(new Description("Mary's Gift"), person1.getID()); group1.addMember(person1.getID()); group1.addMember(person2.getID()); Group group2 = new Group(new Description("Mary's Gift"), person2.getID()); group2.addMember(person1.getID()); group2.addMember(person2.getID()); //Act boolean result = group1.equals(group2); //Assert assertTrue(result); } /** * Check if Group and another object are different */ @Test @DisplayName("Compare different objects") public void compareGroupToAnotherObject() { //Arrange Person person = new Person("John", new DateAndTime(2000, 12, 4), new Address("London"), new Address("Rua B", "Feira", "4520-233"), new Email("1234@isep.pt")); Group group1 = new Group(new Description("Mary's Gift"), person.getID()); Account group2 = new Account(new Denomination("Mary"), new Description("Mary Gift"), new GroupID(new Description("Gift"))); //Act boolean result = group1.equals(group2); //Assert assertFalse(result); } /** * US003 (add a member to a group) * Test if a user was added as first member and group admin to a Group and the second as member */ @Test @DisplayName("Validate if members were added to a group") void addMembers() { //Arrange Person person1 = new Person("Marta", new DateAndTime(1995, 12, 13), new Address("Porto"), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("1234@isep.pt")); Person person2 = new Person("Mariana", new DateAndTime(1995, 12, 13), new Address("Lisboa"), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("123@isep.pt")); HashSet<PersonID> setOfMembers = new HashSet<>(Arrays.asList(person1.getID(), person2.getID())); Group group1 = new Group(new Description("OsMaisFixes"), person1.getID()); group1.addMultipleMembers(setOfMembers); //Act boolean areMembersAddedToGroup = (group1.isGroupMember(person1.getID()) && group1.addMember(person2.getID())); //Assert //assertTrue(areMembersAddedToGroup); } @Test @DisplayName("Validate if a member was added to a group - Person null") void addMemberNull() { //Arrange PersonID person1 = null; Group group1 = new Group(new Description("OsMaisFixes"), person1); //Act boolean isMemberAddedToGroup = group1.addMember(person1); //Assert assertFalse(isMemberAddedToGroup); } /** * Test if a member added to the group is automatically promoted to admin if the group is empty */ @Test @DisplayName("Member added to an empty group and Set as Admin") void promoteToAdminMemberAddedToAnEmptyTrue() { //Arrange Person person1 = new Person("Juan", new DateAndTime(1995, 12, 13), new Address("Toledo"), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("1234@isep.pt")); Group group1 = new Group(new Description("Group with no members"), person1.getID()); //Act boolean isMemberAddedToEmpyGroup = group1.addMember(person1.getID()); //Assert assertFalse(isMemberAddedToEmpyGroup); assertTrue(group1.isGroupAdmin(person1.getID())); } @Test @DisplayName("Member added to a non empty group - Not Admin") void addMemberToNonEmptyGroup() { //Arrange Person person = new Person("John", new DateAndTime(2000, 12, 4), new Address("London"), new Address("Rua B", "Feira", "4520-233"), new Email("1234@isep.pt")); Group group1 = new Group(new Description("Group with no members"), person.getID()); Person person1 = new Person("Juan", new DateAndTime(1995, 12, 13), new Address("Toledo"), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("1234@isep.pt")); group1.addMember(person1.getID()); Person person2 = new Person("Pablo", new DateAndTime(1995, 12, 13), new Address("Madrid"), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("123@isep.pt")); //Act boolean isPerson2AddedButNotToSettledAsAdmin = group1.addMember(person2.getID()) && !group1.isGroupAdmin(person2.getID()); //Assert assertTrue(isPerson2AddedButNotToSettledAsAdmin); } @Test @DisplayName("Test if the same person is not added twice") void addSamePersonTwice() { //Arrange Person person = new Person("John", new DateAndTime(2000, 12, 4), new Address("London"), new Address("Rua B", "Feira", "4520-233"), new Email("1234@isep.pt")); Group group1 = new Group(new Description("Maria's Group"), person.getID()); Person person1 = new Person("Maria", new DateAndTime(1995, 12, 13), new Address("Porto"), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("1234@isep.pt")); group1.addMember(person1.getID()); Person person2 = new Person("Maria", new DateAndTime(1995, 12, 13), new Address("Porto"), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("1234@isep.pt")); //Act boolean person2NotAdded = group1.addMember(person2.getID()); //Assert assertFalse(person2NotAdded); } @Test @DisplayName("Test if multiple members are not added to an empty group") void addMultipleMembersEmptyGroup() { //Arrange Person person = new Person("John", new DateAndTime(2000, 12, 4), new Address("London"), new Address("Rua B", "Feira", "4520-233"), new Email("1234@isep.pt")); Group group1 = new Group(new Description("Grupo a ser submetido aos testes"), person.getID()); Person admin = new Person("João", new DateAndTime(1995, 12, 13), new Address("Paranhos"), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("123@isep.pt")); group1.addMember(admin.getID()); Person person1 = new Person("João", new DateAndTime(1995, 12, 13), new Address("Paranhos"), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("123@isep.pt")); Person person2 = new Person("Elsa", new DateAndTime(1995, 12, 13), new Address("Porto"), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("12@isep.pt")); HashSet<PersonID> putMembers = new HashSet<>(Arrays.asList(person1.getID(), person2.getID())); //Act boolean result = group1.addMultipleMembers(putMembers); //Assert assertTrue(result); } /** * Test if member was removed from Group */ @Test @DisplayName("Test if a member was removed from a Group") void removeMemberFromGroup() { //Arrange Person person = new Person("John", new DateAndTime(2000, 12, 4), new Address("London"), new Address("Rua B", "Feira", "4520-233"), new Email("1234@isep.pt")); Group group1 = new Group(new Description("Grupo a ser submetido aos testes"), person.getID()); Person personAdmin = new Person("António", new DateAndTime(1995, 12, 13), new Address("Guimarães"), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("1234@isep.pt")); Person person1 = new Person("João", new DateAndTime(1995, 12, 13), new Address("Paranhos"), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("123@isep.pt")); Person person2 = new Person("Elsa", new DateAndTime(1995, 12, 13), new Address("Porto"), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("12@isep.pt")); HashSet<PersonID> putMembers = new HashSet<>(Arrays.asList(person1.getID(), person2.getID())); group1.addMember(personAdmin.getID()); //Act group1.addMultipleMembers(putMembers); boolean removeSingleMember = group1.removeMember(person2.getID()); //Assert assertTrue(removeSingleMember); } /** * Test if member was removed from Group - null member */ @Test @DisplayName("Test if a null member was removed from a Group") void removeNullMemberFromGroup() { //Arrange Person personAdmin = new Person("Maria", new DateAndTime(1995, 12, 13), new Address("Paranhos"), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("123@isep.pt")); Person person1 = new Person("João", new DateAndTime(1995, 12, 13), new Address("Paranhos"), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("134@isep.pt")); Person person2 = new Person("Elsa", new DateAndTime(1995, 12, 13), new Address("Porto"), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("13@isep.pt")); PersonID person3 = null; Group group1 = new Group(new Description("Grupo a ser submetido aos testes"), personAdmin.getID()); HashSet<PersonID> putMembers = new HashSet<>(Arrays.asList(person1.getID(), person2.getID())); group1.addMember(personAdmin.getID()); group1.addMultipleMembers(putMembers); //Act boolean removeSingleMember = group1.removeMember(person3); //Assert assertFalse(removeSingleMember); } /** * Test if an Administrator was removed from the Group in case he's the only Admin - Shouldn't work */ @Test @DisplayName("Test if a member, not null, that is the only administrator is removed - false") void removeTheOnlyAdministratorFromGroup() { //Arrange Person person = new Person("John", new DateAndTime(2000, 12, 4), new Address("London"), new Address("Rua B", "Feira", "4520-233"), new Email("1234@isep.pt")); Group group1 = new Group(new Description("OS FIXES"), person.getID()); Person person1 = new Person("João", new DateAndTime(1995, 12, 13), new Address("Paranhos"), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("1234@isep.pt")); Person person3 = new Person("Diana", new DateAndTime(1995, 12, 13), new Address("Porto"), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("123@isep.pt")); //Act group1.addMember(person1.getID()); //Admin group1.addMember(person3.getID()); boolean removeAdmin = group1.removeMember(person1.getID()); //Assert assertFalse(removeAdmin); } /** * Test if an Administrator was removed from the Group in case he's the only Admin - Shouldn't work */ @Test @DisplayName("Test if one of the administrators is removed - true em case more then one") void removeTheOneOfTheAdministratorFromGroup() { //Arrange Person person = new Person("John", new DateAndTime(2000, 12, 4), new Address("London"), new Address("Rua B", "Feira", "4520-233"), new Email("1234@isep.pt")); Group group1 = new Group(new Description("OS FIXES"), person.getID()); Person person1 = new Person("João", new DateAndTime(1995, 12, 13), new Address("Paranhos"), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("1234@isep.pt")); Person person2 = new Person("Mariana", new DateAndTime(1995, 12, 13), new Address("Porto"), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("123@isep.pt")); Person person3 = new Person("Diana", new DateAndTime(1995, 12, 13), new Address("Porto"), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("12@isep.pt")); //Act group1.addMember(person1.getID()); //Admin group1.addMember(person2.getID()); group1.setAdmin(person2.getID()); //Admin group1.addMember(person3.getID()); boolean removeAdmin = group1.removeMember(person1.getID()); //Assert assertTrue(removeAdmin); } @Test @DisplayName("Test if a member was removed from a Group") void removeMemberFromGroupNullPerson() { //Arrange Person personAdmin = new Person("Maria", new DateAndTime(1995, 12, 13), new Address("Lisboa"), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("1234@isep.pt")); Person person1 = new Person("João", new DateAndTime(1995, 12, 13), new Address("Paranhos"), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("123@isep.pt")); Person person2 = new Person("Elsa", new DateAndTime(1995, 12, 13), new Address("Porto"), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("12@isep.pt")); Group group1 = new Group(new Description("Grupo a ser submetido aos testes"), personAdmin.getID()); HashSet<PersonID> putMembers = new HashSet<>(Arrays.asList(person1.getID(), person2.getID())); //Act group1.addMultipleMembers(putMembers); boolean removeSingleMember = group1.removeMember(null); //Assert assertFalse(removeSingleMember); } @Test @DisplayName("Test if a member was removed from a Group") void removeMemberFromGroupPersonNotInGroup() { //Arrange Person personAdmin = new Person("Catarina", new DateAndTime(1995, 12, 13), new Address("Lisboa"), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("134@isep.pt")); Person person1 = new Person("João", new DateAndTime(1995, 12, 13), new Address("Paranhos"), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("234@isep.pt")); Person person2 = new Person("Elsa", new DateAndTime(1995, 12, 13), new Address("Porto"), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("123@isep.pt")); Person person3 = new Person("Gabriel", new DateAndTime(1995, 12, 13), new Address("Porto"), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("124@isep.pt")); HashSet<PersonID> putMembers = new HashSet<>(Arrays.asList(person1.getID(), person2.getID())); Group group1 = new Group(new Description("Grupo a ser submetido aos testes"), personAdmin.getID()); group1.addMultipleMembers(putMembers); //Act boolean removeSingleMember = group1.removeMember(person3.getID()); //Assert assertFalse(removeSingleMember); } @Test @DisplayName("Test if a member was removed from a Group - try to remove all members") void removeMemberFromGroupAllMembers() { //Arrange Person person1 = new Person("João", new DateAndTime(1995, 12, 13), new Address("Lisboa"), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("1234@isep.pt")); Person person2 = new Person("Elsa", new DateAndTime(1995, 12, 13), new Address("Porto"), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("123@isep.pt")); Person person3 = new Person("Laurinda", new DateAndTime(1995, 12, 13), new Address("Porto"), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("12@isep.pt")); Group group1 = new Group(new Description("123 são os primeiros três números inteiros"), person1.getID()); HashSet<PersonID> setOfPeopleToAddToGroup = new HashSet<>(Arrays.asList(person3.getID(), person2.getID())); //Act group1.addMultipleMembers(setOfPeopleToAddToGroup); boolean areBothMembersRemoved = (group1.removeMember(person3.getID()) && group1.removeMember(person2.getID())); //Assert assertTrue(areBothMembersRemoved); } /** * Check if a person is directly added to a group as both member and admin * setAdmin method. */ @Test @DisplayName("add 1 person to both group member and group admin") void isPersonAddedAsMemberAndAdmin() { //Arrange: Person person1 = new Person("Francisco", new DateAndTime(1995, 12, 13), new Address("Braga"), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("1234@isep.pt")); Person groupAdmin = new Person("João", new DateAndTime(1995, 12, 13), new Address("Braga"), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("123@isep.pt")); Group group1 = new Group(new Description("Test Group"), person1.getID()); //Act: boolean result = group1.setAdmin(person1.getID()); //Assert: assertFalse(result); } @Test @DisplayName("trying to user method on a null person returns - FALSE") void isNullPersonAddedToGroupAsAdminAndMember() { //Arrange: Person groupAdmin = new Person("Francisco", new DateAndTime(1995, 12, 13), new Address("Braga"), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("1234@isep.pt")); PersonID person1 = null; Group group1 = new Group(new Description("Test Group"), groupAdmin.getID()); //Act: boolean result = group1.setAdmin(person1); //Assert: assertFalse(result); } @Test @DisplayName("setting a person who is already member and admin - FALSE") void setAdminOnAAdmin() { //Arrange: Person person1 = new Person("Francisco", new DateAndTime(1995, 12, 13), new Address("Braga"), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("1234@isep.pt")); Person groupAdmin = new Person("João", new DateAndTime(1995, 12, 13), new Address("Braga"), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("123@isep.pt")); Group group1 = new Group(new Description("Test Group"), groupAdmin.getID()); //Act: group1.setAdmin(person1.getID()); boolean result = group1.setAdmin(person1.getID()); //Assert: assertFalse(result); } @Test @DisplayName("Promote one member to Admin while there are more than one member") void promoteMemberTest2() { //Arrange Person person = new Person("John", new DateAndTime(2000, 12, 4), new Address("London"), new Address("Rua B", "Feira", "4520-233"), new Email("1234@isep.pt")); Person person1 = new Person("Francis", new DateAndTime(1995, 12, 13), new Address("London"), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("1234@isep.pt")); Person person2 = new Person("Jaques", new DateAndTime(1995, 12, 13), new Address("Paris"), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("123@isep.pt")); Person person3 = new Person("Albert", new DateAndTime(1995, 12, 13), new Address("Bristol"), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("12@isep.pt")); Group group1 = new Group(new Description("Francis Group"), person.getID()); //Act group1.addMember(person1.getID()); group1.addMember(person2.getID()); group1.addMember(person3.getID()); boolean wereMembersPromoted = group1.setAdmin(person2.getID()) && group1.setAdmin(person3.getID()); //Assert assertTrue(wereMembersPromoted); } @Test @DisplayName("Promote one member to group admin - false because member is already group admin") void promoteMemberFalseAlreadyAdmin() { //Arrange Person person = new Person("John", new DateAndTime(2000, 12, 4), new Address("London"), new Address("Rua B", "Feira", "4520-233"), new Email("1234@isep.pt")); Person person1 = new Person("Francis", new DateAndTime(1995, 12, 13), new Address("London"), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("1234@isep.pt")); Person person2 = new Person("Jaques", new DateAndTime(1995, 12, 13), new Address("Paris"), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("124@isep.pt")); Group group1 = new Group(new Description("Francis Group"), person.getID()); //Act group1.addMember(person1.getID()); group1.addMember(person2.getID()); boolean isFirstMemberPromotedAgain = group1.setAdmin(person1.getID()); boolean wasPromoted = isFirstMemberPromotedAgain; //Assert assertFalse(wasPromoted); } @Test @DisplayName("Promote one member to group admin - false because member is already group admin") void promoteMemberFalseNotMember() { //Arrange Person person1 = new Person("Francis", new DateAndTime(1995, 12, 13), new Address("London"), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("1234@isep.pt")); Group group1 = new Group(new Description("Francis Group"), person1.getID()); //Act boolean wasPromoted = group1.setAdmin(person1.getID()); //Assert assertFalse(wasPromoted); } /** * Test Equals method for the Group class */ @Test @DisplayName("Two group are the same") void equalsGroupClassJustGroupTrue() { Person person = new Person("John", new DateAndTime(2000, 12, 4), new Address("London"), new Address("Rua B", "Feira", "4520-233"), new Email("1234@isep.pt")); Group group1 = new Group(new Description("Familia"),person.getID()); Group group2 = new Group(new Description("Familia"),person.getID()); //Act boolean result = group1.equals(group2); //Assert assertTrue(result); } /** * Check if member was demoted from group admin */ @Test @DisplayName("Demote one group admin to member") void demoteMemberTest() { //Arrange Person person = new Person("John", new DateAndTime(2000, 12, 4), new Address("London"), new Address("Rua B", "Feira", "4520-233"), new Email("1234@isep.pt")); Person person1 = new Person("Francis", new DateAndTime(1995, 12, 13), new Address("London"), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("1234@isep.pt")); Person person2 = new Person("Jaques", new DateAndTime(1995, 12, 13), new Address("Paris"), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("123@isep.pt")); Group group1 = new Group(new Description("Francis Group"), person.getID()); //Act group1.addMember(person1.getID()); group1.addMember(person2.getID()); group1.setAdmin(person2.getID()); boolean wasDemoted = group1.demoteMemberFromAdmin(person2.getID()); //Assert assertTrue(wasDemoted); } @Test @DisplayName("Demote one group admin to member") void demoteMemberNotAdmin() { //Arrange Person person = new Person("John", new DateAndTime(2000, 12, 4), new Address("London"), new Address("Rua B", "Feira", "4520-233"), new Email("1234@isep.pt")); Person person1 = new Person("Francis", new DateAndTime(1995, 12, 13), new Address("London"), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("1234@isep.pt")); Person person2 = new Person("Jaques", new DateAndTime(1995, 12, 13), new Address("Paris"), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("123@isep.pt")); Group group1 = new Group(new Description("Francis Group"), person.getID()); //Act group1.addMember(person1.getID()); group1.addMember(person2.getID()); boolean wasDemoted = group1.demoteMemberFromAdmin(person2.getID()); //Assert assertFalse(wasDemoted); } @Test @DisplayName("Demote a member who is not an admin - FALSE") void demoteMemberTestFalse() { //Arrange: Person person = new Person("John", new DateAndTime(2000, 12, 4), new Address("London"), new Address("Rua B", "Feira", "4520-233"), new Email("1234@isep.pt")); Person person1 = new Person("Francis", new DateAndTime(1995, 12, 13), new Address("London"), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("1234@isep.pt")); Person person2 = new Person("Jaques", new DateAndTime(1995, 12, 13), new Address("Paris"), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("134@isep.pt")); Group group1 = new Group(new Description("Francis Group"), person.getID()); //Act: group1.addMember(person1.getID()); group1.addMember(person2.getID()); boolean wasDemoted = group1.addMember(person2.getID()); //Assert: assertFalse(wasDemoted); } @Test @DisplayName("Demote multiple group admins to members") void demoteMultipleMembersTest() { //Arrange: Person person = new Person("John", new DateAndTime(2000, 12, 4), new Address("London"), new Address("Rua B", "Feira", "4520-233"), new Email("1234@isep.pt")); Person person1 = new Person("Francis", new DateAndTime(1995, 12, 13), new Address("London"), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("1234@isep.pt")); Person person2 = new Person("Jaques", new DateAndTime(1995, 12, 13), new Address("Paris"), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("123@isep.pt")); Person person3 = new Person("Vladimir", new DateAndTime(1995, 12, 13), new Address("Moscow"), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("12@isep.pt")); Group group1 = new Group(new Description("Francis Group"), person.getID()); //Act: group1.addMember(person1.getID()); // Torna-se admin automaticamente group1.addMember(person2.getID()); group1.addMember(person3.getID()); group1.setAdmin(person2.getID()); group1.setAdmin(person3.getID()); boolean isFirstAdminRemoved = group1.demoteMemberFromAdmin(person2.getID()); boolean isSecondAdminRemoved = group1.demoteMemberFromAdmin(person3.getID()); //Assert: assertTrue(isFirstAdminRemoved && isSecondAdminRemoved); } @Test @DisplayName("Check if the same admin can be demoted from multiple groups") void demoteMemberFromMultipleGroups() { //Arrange: Person person = new Person("John", new DateAndTime(2000, 12, 4), new Address("London"), new Address("Rua B", "Feira", "4520-233"), new Email("1234@isep.pt")); Person person1 = new Person("Francis", new DateAndTime(1995, 12, 13), new Address("London"), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("1234@isep.pt")); Person person2 = new Person("Jaques", new DateAndTime(1995, 12, 13), new Address("Paris"), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("123@isep.pt")); Group group1 = new Group(new Description("Test Group 1"), person.getID()); Group group2 = new Group(new Description("Test Group 2"), person.getID()); Group group3 = new Group(new Description("Test Group 3"), person.getID()); //Act: group1.addMember(person1.getID()); // admin automatically group1.addMember(person2.getID()); group2.addMember(person1.getID()); // admin automatically group2.addMember(person2.getID()); group3.addMember(person1.getID()); // admin automatically group3.addMember(person2.getID()); group1.setAdmin(person2.getID()); group2.setAdmin(person2.getID()); group3.setAdmin(person2.getID()); boolean isRemovedFromGroup1 = group1.demoteMemberFromAdmin(person1.getID()); boolean isRemovedFromGroup2 = group2.demoteMemberFromAdmin(person1.getID()); boolean isRemovedFromGroup3 = group3.demoteMemberFromAdmin(person1.getID()); // Assert assertTrue(isRemovedFromGroup1 && isRemovedFromGroup2 && isRemovedFromGroup3); } @Test @DisplayName("Check if the last admin can be demoted - FALSE expected because group must contain at least 1 admin") void canLastAdminBeDemoted() { //Arrange: Person person = new Person("John", new DateAndTime(2000, 12, 4), new Address("London"), new Address("Rua B", "Feira", "4520-233"), new Email("1234@isep.pt")); Person person1 = new Person("Francis", new DateAndTime(1995, 12, 13), new Address("London"), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("1234@isep.pt")); Person person2 = new Person("Jaques", new DateAndTime(1995, 12, 13), new Address("Paris"), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("123@isep.pt")); Group group1 = new Group(new Description("Test Group"), person.getID()); //Act: group1.addMember(person1.getID()); //Automatically promoted to admin group1.addMember(person2.getID()); boolean isRemovedFromAdminPerson2 = group1.demoteMemberFromAdmin(person2.getID()); boolean isRemovedFromAdminPerson1 = group1.demoteMemberFromAdmin(person1.getID()); //Assert: assertFalse(isRemovedFromAdminPerson2 && isRemovedFromAdminPerson1); } /** * Check if a person was promoted to member and group administrator simultaneously */ @Test @DisplayName("Promote person to group admin - False - person not member") void promoteNotMemberToAdmin() { //Arrange Person person = new Person("John", new DateAndTime(2000, 12, 4), new Address("London"), new Address("Rua B", "Feira", "4520-233"), new Email("1234@isep.pt")); Person person1 = new Person("Francis", new DateAndTime(2000, 12, 12), new Address("London"), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("1234@isep.pt")); Group group1 = new Group(new Description("Francis Group"), person.getID()); //Act boolean isMemberAddedAsAdmin = group1.setAdmin(person1.getID()); //Assert assertFalse(isMemberAddedAsAdmin); } @Test @DisplayName("Promote person to member and group admin simultaneously - false because member is already group admin") void memberAndGroupAdminSimultaneouslyFalse() { //Arrange Person person = new Person("John", new DateAndTime(2000, 12, 4), new Address("London"), new Address("Rua B", "Feira", "4520-233"), new Email("1234@isep.pt")); Person person1 = new Person("Francis", new DateAndTime(2000, 12, 12), new Address("London"), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("1234@isep.pt")); Group group1 = new Group(new Description("Francis Group"), person.getID()); //Act group1.addMember(person1.getID()); boolean isMemberAddedAsAdmin = group1.setAdmin(person1.getID()); //Assert assertFalse(isMemberAddedAsAdmin); } /** * Test if a person is a Group Admin */ @DisplayName("Check if a person is in the Group Admin List") @Test void isGroupAdmin() { //Arrange: Person person1 = new Person("Alexandre", new DateAndTime(2000, 12, 12), new Address("Porto"), new Address("Rua X", "Porto", "4520-266"), new Email("asd@isep.pt")); Person person2 = new Person("Elsa", new DateAndTime(2000, 12, 12), new Address("Porto"), new Address("Rua X", "Porto", "4520-266"), new Email("qwerty@isep.pt")); Person person3 = new Person("Maria", new DateAndTime(2000, 12, 12), new Address("Porto"), new Address("Rua X", "Porto", "4520-266"), person2.getID(), person1.getID(), new Email("321@isep.pt")); Group group1 = new Group(new Description("Maria's Group"), person3.getID()); //Act boolean isAdmin = group1.isGroupAdmin(person3.getID()); //Assert assertTrue(isAdmin); } @DisplayName("Check if a person is not in the Group Admin List") @Test void isGroupAdminFalse() { //Arrange: Person person = new Person("John", new DateAndTime(2000, 12, 4), new Address("London"), new Address("Rua B", "Feira", "4520-233"), new Email("1234@isep.pt")); Person person1 = new Person("Alexandre", new DateAndTime(2000, 12, 12), new Address("Porto"), new Address("Rua X", "Porto", "4520-266"), new Email("1234@isep.pt")); Person person2 = new Person("Elsa", new DateAndTime(2000, 12, 12), new Address("Porto"), new Address("Rua X", "Porto", "4520-266"), new Email("123@isep.pt")); Person person3 = new Person("Maria", new DateAndTime(2000, 12, 12), new Address("Porto"), new Address("Rua X", "Porto", "4520-266"), person2.getID(), person1.getID(), new Email("12@isep.pt")); Person person4 = new Person("João", new DateAndTime(2000, 12, 12), new Address("Porto"), new Address("Rua dos Flores", "Porto", "4450-852"), person2.getID(), person3.getID(), new Email("1@isep.pt")); Group group1 = new Group(new Description("Maria's Group"), person.getID()); group1.addMember(person3.getID()); group1.addMember(person4.getID()); //Act boolean isAdmin = group1.isGroupAdmin(person4.getID()); //Assert assertFalse(isAdmin); } /** * Test if a person is a Group Admin - check PersonID */ @Test @DisplayName("Check if a person is in the Group Admin List - True ") void isGroupAdmin_True() { //Arrange Person person = new Person("John", new DateAndTime(2000, 12, 4), new Address("London"), new Address("Rua B", "Feira", "4520-233"), new Email("1234@isep.pt")); Person person1 = new Person("Alexandre", new DateAndTime(2000, 12, 12), new Address("Porto"), new Address("Rua X", "Porto", "4520-266"), new Email("123@isep.pt")); Person person2 = new Person("Elsa", new DateAndTime(2000, 12, 12), new Address("Porto"), new Address("Rua X", "Porto", "4520-266"), new Email("1234@isep.pt")); Person person3 = new Person("Maria", new DateAndTime(2000, 12, 12), new Address("Porto"), new Address("Rua X", "Porto", "4520-266"), person2.getID(), person1.getID(), new Email("234@isep.pt")); Group oneGroup = new Group(new Description("XPTO"), person.getID()); oneGroup.addMember(person2.getID()); oneGroup.addMember(person3.getID()); //Act boolean isgroupAdmin = oneGroup.isGroupAdmin(person2.getID()); //Assert assertTrue(isgroupAdmin); } @Test @DisplayName("Check if a person is in the Group Admin List - False - Person member but not admin") void isGroupAdmin_False() { //Arrange Person person = new Person("John", new DateAndTime(2000, 12, 4), new Address("London"), new Address("Rua B", "Feira", "4520-233"), new Email("1234@isep.pt")); Person person1 = new Person("Alexandre", new DateAndTime(2000, 12, 12), new Address("Porto"), new Address("Rua X", "Porto", "4520-266"), new Email("123@isep.pt")); Person person2 = new Person("Elsa", new DateAndTime(2000, 12, 12), new Address("Porto"), new Address("Rua X", "Porto", "4520-266"), new Email("ada@isep.pt")); Person person3 = new Person("Maria", new DateAndTime(2000, 12, 12), new Address("Porto"), new Address("Rua X", "Porto", "4520-266"), person2.getID(), person1.getID(), new Email("dasdas@isep.pt")); Group oneGroup = new Group(new Description("XPTO"), person.getID()); oneGroup.addMember(person2.getID()); oneGroup.addMember(person3.getID()); //Act boolean isgroupAdmin = oneGroup.isGroupAdmin(person3.getID()); //Assert assertFalse(isgroupAdmin); } @Test @DisplayName("Check if a person is in the Group Admin List - False - Person not member") void isGroupAdmin_False_PersonNotMember() { //Arrange Person person = new Person("John", new DateAndTime(2000, 12, 4), new Address("London"), new Address("Rua B", "Feira", "4520-233"), new Email("1234@isep.pt")); Person person1 = new Person("Alexandre", new DateAndTime(2000, 12, 12), new Address("Porto"), new Address("Rua X", "Porto", "4520-266"), new Email("alexandre@isep.pt")); Person person2 = new Person("Elsa", new DateAndTime(2000, 12, 12), new Address("Porto"), new Address("Rua X", "Porto", "4520-266"), new Email("elsa@isep.pt")); Person person3 = new Person("Maria", new DateAndTime(2000, 12, 12), new Address("Porto"), new Address("Rua X", "Porto", "4520-266"), person2.getID(), person1.getID(), new Email("sd@isep.pt")); Group oneGroup = new Group(new Description("XPTO"), person.getID()); oneGroup.addMember(person2.getID()); oneGroup.addMember(person3.getID()); //Act boolean isgroupAdmin = oneGroup.isGroupAdmin(person1.getID()); //Assert assertFalse(isgroupAdmin); } @DisplayName("Check if a person null can be a Group Admin") @Test void isGroupAdminNull() { //Arrange Person person = new Person("John", new DateAndTime(2000, 12, 4), new Address("London"), new Address("Rua B", "Feira", "4520-233"), new Email("1234@isep.pt")); PersonID personID = null; Group group1 = new Group(new Description("Group"), person.getID()); //Act boolean isAdmin = group1.isGroupAdmin(personID); //Assert assertFalse(isAdmin); } /** * Test if a person is a Group Member with ID */ @DisplayName("Check if a person is in the Group Member List") @Test void isGroupMemberID() { //Arrange: Person father = new Person("John", new DateAndTime(2000, 12, 4), new Address("London"), new Address("Rua B", "Feira", "4520-233"), new Email("1234@isep.pt")); Person mother = new Person("Alexandre", new DateAndTime(2000, 12, 12), new Address("Porto"), new Address("Rua X", "Porto", "4520-266"), new Email("1234@isep.pt")); Person person2 = new Person("Elsa", new DateAndTime(2000, 12, 12), new Address("Porto"), new Address("Rua X", "Porto", "4520-266"), new Email("134@isep.pt")); Person person3 = new Person("Maria", new DateAndTime(2000, 12, 12), new Address("Porto"), new Address("Rua X", "Porto", "4520-266"), person2.getID(), mother.getID(), new Email("34@isep.pt")); Group group1 = new Group(new Description("Group"), father.getID()); group1.addMember(person3.getID()); group1.addMember(person2.getID()); //Act boolean isMember = group1.isGroupMember(person2.getID()); //Assert assertTrue(isMember); } @DisplayName("Check if a person is not in the Group Member List") @Test void isGroupMemberIDFalse() { //Arrange: Person father = new Person("Alexandre", new DateAndTime(2000, 12, 12), new Address("Porto"), new Address("Rua X", "Porto", "4520-266"), new Email("1234@isep.pt")); Person mother = new Person("Elsa", new DateAndTime(2000, 12, 12), new Address("Porto"), new Address("Rua X", "Porto", "4520-266"), new Email("123@isep.pt")); Person person3 = new Person("Maria", new DateAndTime(2000, 12, 12), new Address("Porto"), new Address("Rua X", "Porto", "4520-266"), mother.getID(), father.getID(), new Email("12@isep.pt")); Person person4 = new Person("João", new DateAndTime(2000, 12, 12), new Address("Porto"), new Address("Rua dos Flores", "Porto", "4450-852"), mother.getID(), person3.getID(), new Email("1@isep.pt")); Group group = new Group(new Description("Group"), father.getID()); group.addMember(person4.getID()); group.addMember(mother.getID()); //Act boolean isMember = group.isGroupMember(person3.getID()); //Assert assertFalse(isMember); } @DisplayName("Check if a person is not in the Group Member List") @Test void isGroupMemberIDNull() { //Arrange: Person admin = new Person("Alexandre", new DateAndTime(2000, 12, 12), new Address("Porto"), new Address("Rua X", "Porto", "4520-266"), new Email("1234@isep.pt")); PersonID personID = null; Group group1 = new Group(new Description("Group"), admin.getID()); //Act boolean isMember = group1.isGroupMember(personID); //Assert assertFalse(isMember); } /** * Get admins and members */ @DisplayName("Get amdins of Group - happy case") @Test public void getAdmins() { //Arrange Person person1 = new Person("Alexandre", new DateAndTime(2000, 12, 12), new Address("Porto"), new Address("Rua X", "Porto", "4520-266"), new Email("1234@isep.pt")); Person person2 = new Person("Elsa", new DateAndTime(2000, 12, 12), new Address("Porto"), new Address("Rua X", "Porto", "4520-266"), new Email("123@isep.pt")); Person person3 = new Person("Joao", new DateAndTime(1995, 12, 13), new Address("Porto"), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("134@isep.pt")); Person person4 = new Person("Manuela", new DateAndTime(1995, 12, 13), new Address("Porto"), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("234@isep.pt")); Group group1 = new Group(new Description("Maria's Group"), person1.getID()); group1.addMember(person2.getID()); group1.setAdmin(person2.getID()); group1.addMember(person3.getID()); group1.addMember(person4.getID()); Set<PersonID> expectedListOfAdmins = new HashSet<>(Arrays.asList(person1.getID(), person2.getID())); //Act Set<PersonID> resultListOfAdmins = group1.getAdmins(); //Assert assertEquals(expectedListOfAdmins, resultListOfAdmins); } @DisplayName("Get members of Group - happy case") @Test public void getMembers() { //Arrange Person person1 = new Person("Alexandre", new DateAndTime(2000, 12, 12), new Address("Porto"), new Address("Rua X", "Porto", "4520-266"), new Email("1234@isep.pt")); Person person2 = new Person("Elsa", new DateAndTime(2000, 12, 12), new Address("Porto"), new Address("Rua X", "Porto", "4520-266"), new Email("123@isep.pt")); Person person3 = new Person("Joao", new DateAndTime(1995, 12, 13), new Address("Porto"), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("134@isep.pt")); Person person4 = new Person("Manuela", new DateAndTime(1995, 12, 13), new Address("Porto"), new Address("Rua dos Flores", "Porto", "4450-852"), new Email("234@isep.pt")); Group group1 = new Group(new Description("Maria's Group"), person1.getID()); group1.addMember(person2.getID()); group1.setAdmin(person2.getID()); group1.addMember(person3.getID()); group1.addMember(person4.getID()); Set<PersonID> expectedListOfAdmins = new HashSet<>(Arrays.asList(person1.getID(), person2.getID(), person3.getID(), person4.getID())); //Act Set<PersonID> resultListOfAdmins = group1.getMembers(); //Assert assertEquals(expectedListOfAdmins, resultListOfAdmins); } /** * Test if two Groups are the same */ @Test @DisplayName("test if two Groups are the same") public void testIfTwoGroupsAreTheSameHashcode() { //Arrange Person person = new Person("John", new DateAndTime(2000, 12, 4), new Address("London"), new Address("Rua B", "Feira", "4520-233"), new Email("1234@isep.pt")); Group group1 = new Group(new Description("Talho do Amadeu"), person.getID()); Group group2 = new Group(new Description("Talho do Amadeu"), person.getID()); //Act int g1 = group1.hashCode(); int g2 = group2.hashCode(); boolean x = group1.equals(group2); //Assert assertEquals(g1, g2); } @Test @DisplayName("test if two Groups are the same") public void testIfTwoGroupsAreTheSameHashcodeFalse() { //Arrange Person person = new Person("John", new DateAndTime(2000, 12, 4), new Address("London"), new Address("Rua B", "Feira", "4520-233"), new Email("1234@isep.pt")); Group group1 = new Group(new Description("Talho do Amadeu"), person.getID()); Group group2 = new Group(new Description("Talho do João"), person.getID()); //Act int g1 = group1.hashCode(); int g2 = group2.hashCode(); //Assert assertNotEquals(g1, g2); } @Test void getGroupDescription() { Person person = new Person("John", new DateAndTime(2000, 12, 4), new Address("London"), new Address("Rua B", "Feira", "4520-233"), new Email("1234@isep.pt")); Group group = new Group(new Description("tarzan"), person.getID()); String expected = "TARZAN"; //Act String result = group.getID().toString(); //Assert assertEquals(expected, result); } @Test @DisplayName("Test method getID from Group ") void getID() { Person person = new Person("John", new DateAndTime(2000, 12, 4), new Address("London"), new Address("Rua B", "Feira", "4520-233"), new Email("1234@isep.pt")); Group group1 = new Group(new Description("Gym Buddies"), person.getID()); GroupID expected = new GroupID(new Description("Gym Buddies")); //Act GroupID result = group1.getID(); //Assert assertEquals(expected, result); } /** * Test to check if converts a group into a String. */ @Test @DisplayName("gruoupToString tested - Success") void testToString() { //Arrange: Person person = new Person("Jose", new DateAndTime(1995, 12, 13), new Address("Lisboa"), new Address("Rua X", "Porto", "4520-266"), new Email("1234@isep.pt")); Group group = new Group(new Description("policias"), person.getID()); //Act: String groupInString = group.toString(); String expected = "POLICIAS"; //Assert: assertEquals(expected, groupInString); } @Test @DisplayName("test the exception of setGroupID method") void setGroupIdExceptionTest() { //Arrange: Person person = new Person("John", new DateAndTime(2000, 12, 4), new Address("London"), new Address("Rua B", "Feira", "4520-233"), new Email("1234@isep.pt")); Group group = new Group(new Description("grupo de rafting"), person.getID()); //Act: try { group.setGroupID(null); } //Assert: catch (IllegalArgumentException nullDescription) { assertEquals("GroupID can't be null", nullDescription.getMessage()); } } }
/* * LumaQQ - Java QQ Client * * Copyright (C) 2004 luma <stubma@163.com> * * 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 2 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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package edu.tsinghua.lumaqq.ui.config.user; import static edu.tsinghua.lumaqq.resource.Messages.*; import edu.tsinghua.lumaqq.models.User; import edu.tsinghua.lumaqq.qq.beans.Card; import edu.tsinghua.lumaqq.qq.packets.BasicOutPacket; import edu.tsinghua.lumaqq.qq.packets.out.ClusterModifyCardPacket; import edu.tsinghua.lumaqq.resource.Colors; import edu.tsinghua.lumaqq.resource.Resources; import edu.tsinghua.lumaqq.ui.config.AbstractPage; import edu.tsinghua.lumaqq.ui.config.IPacketFiller; import edu.tsinghua.lumaqq.ui.helper.UITool; import edu.tsinghua.lumaqq.ui.listener.CenterBorderPaintListener; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CCombo; import org.eclipse.swt.events.PaintListener; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Text; public class CardPage extends AbstractPage implements IPacketFiller { private User model; private PaintListener paintListener; private Text textName, textPhone, textEmail, textRemark; private CCombo comboGender; public CardPage(Composite parent, User model, int style) { super(parent, style); this.model = model; } private boolean isEditable() { return (style & UserInfoWindow.EDITABLE) != 0; } @Override protected void initialVariable() { paintListener = new CenterBorderPaintListener(new Class[] { Text.class, CCombo.class }, 20, Colors.PAGE_CONTROL_BORDER); } @Override protected Control createContent(Composite parent) { Composite content = new Composite(parent, SWT.NONE); content.setBackground(Colors.PAGE_BACKGROUND); content.setLayout(new FormLayout()); // 设置使用缺省背景色 UITool.setDefaultBackground(null); boolean enable = isEditable(); Composite c = new Composite(content, SWT.NONE); FormData fd = new FormData(); fd.top = fd.left = new FormAttachment(0, 0); fd.bottom = fd.right = new FormAttachment(100, -50); c.setLayoutData(fd); GridLayout layout = new GridLayout(2, false); layout.marginHeight = layout.horizontalSpacing = 8; layout.verticalSpacing = 14; layout.marginWidth = 15; c.setLayout(layout); c.setBackground(Colors.PAGE_BACKGROUND); c.addPaintListener(paintListener); // 姓名 UITool.createLabel(c, user_info_card_name); textName = UITool.createSingleText(c, new GridData(GridData.FILL_HORIZONTAL)); textName.setEnabled(enable); if(!enable) textName.setBackground(Colors.PAGE_READONLY_CONTROL_BACKGROUND); // 性别 UITool.createLabel(c, user_info_card_gender); comboGender = UITool.createCCombo(c, new GridData(GridData.FILL_HORIZONTAL)); comboGender.add(gender_gg); comboGender.add(gender_mm); comboGender.add("-"); comboGender.setEnabled(enable); if(!enable) comboGender.setBackground(Colors.PAGE_READONLY_CONTROL_BACKGROUND); // 电话 UITool.createLabel(c, user_info_card_phone); textPhone = UITool.createSingleText(c, new GridData(GridData.FILL_HORIZONTAL)); textPhone.setEnabled(enable); if(!enable) textPhone.setBackground(Colors.PAGE_READONLY_CONTROL_BACKGROUND); // email UITool.createLabel(c, user_info_card_email); textEmail = UITool.createSingleText(c, new GridData(GridData.FILL_HORIZONTAL)); textEmail.setEnabled(enable); if(!enable) textEmail.setBackground(Colors.PAGE_READONLY_CONTROL_BACKGROUND); // 备注 UITool.createLabel(c, user_info_card_remark, new GridData(GridData.VERTICAL_ALIGN_BEGINNING)); textRemark = UITool.createMultiText(c, new GridData(GridData.FILL_BOTH)); textRemark.setEnabled(enable); if(!enable) textRemark.setBackground(Colors.PAGE_READONLY_CONTROL_BACKGROUND); return content; } @Override protected void saveDirtyProperty(int propertyId) { } /* (non-Javadoc) * @see edu.tsinghua.lumaqq.shells.AbstractPage#setModel(java.lang.Object) */ @Override public void setModel(Object model) { if(model instanceof User) this.model = (User)model; } @Override protected void initializeValues() { textName.setText(model.cardName); textPhone.setText(model.cardPhone); textEmail.setText(model.cardEmail); textRemark.setText(model.cardRemark); comboGender.select(model.cardGenderIndex); } @Override protected Image getImage() { if(isEditable()) return Resources.getInstance().getImage(Resources.icoModifyPersonInfo24); else return Resources.getInstance().getImage(Resources.icoViewPersonInfo24); } @Override protected String getTitle(int page) { return user_info_page_card; } /* (non-Javadoc) * @see edu.tsinghua.lumaqq.ui.config.IPacketFiller#fill(edu.tsinghua.lumaqq.qq.packets.BasicOutPacket) */ public void fill(BasicOutPacket p) { if(p instanceof ClusterModifyCardPacket) { ClusterModifyCardPacket packet = (ClusterModifyCardPacket)p; Card card = new Card(); card.name = textName.getText(); card.email = textEmail.getText(); card.phone = textPhone.getText(); card.remark = textRemark.getText(); card.genderIndex = comboGender.getSelectionIndex(); packet.setCard(card); packet.setClusterId(model.cluster.clusterId); } } }
package com.example.foodmenus; import android.content.Context; import android.content.Intent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.squareup.picasso.Picasso; import java.util.ArrayList; public class FoodsAdapter extends RecyclerView.Adapter<FoodsAdapter.FoodViewHolder> { ArrayList<Food> listFoods; IOnItemClickListener itemClickListener; public FoodsAdapter(ArrayList<Food> listFoods,IOnItemClickListener itemClickListener,Context context) { this.listFoods = listFoods; this.itemClickListener =itemClickListener; } @NonNull @Override public FoodViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.food_item, parent, false); return new FoodViewHolder(v,itemClickListener); } @Override public void onBindViewHolder(@NonNull FoodViewHolder holder, int position) { holder.bind(listFoods.get(position)); } @Override public int getItemCount() { if (listFoods != null) return listFoods.size(); return 0; } public class FoodViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { ImageView imageView; TextView textView; IOnItemClickListener itemClickListener; public FoodViewHolder(@NonNull View itemView,IOnItemClickListener itemClickListener ) { super(itemView); textView = itemView.findViewById(R.id.textView); imageView = itemView.findViewById(R.id.imageView); this.itemClickListener =itemClickListener; } void bind(final Food item) { textView.setText(item.getMenuName()); //load image from url โดยใช้ Library Picasso Picasso.get() .load(item.getImageUrl()) .into(imageView); //set onclick แบบง่าย textView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // // ส่งค่าเป็น Object ได้เด้อ // //Context ต้นทาง -> SecondActivity ปลายทาง Intent intent = new Intent(imageView.getContext(),SecondActivity.class); // add param คล้ายๆ dictionary ใน c# intent.putExtra("MY_KEY",listFoods.get(getAdapterPosition()));//ส่งURL รูป //สั่งให้เปิดหน้าใหม่โดนอิงจาก Intent ข้างบน itemView.getContext().startActivity(intent); Toast.makeText(v.getContext(),String.valueOf(item.getMenuId()),Toast.LENGTH_LONG).show(); } }); // setOnclick Item แบบใช้ Interface เขาว่าแบบนี้คือ best practice 555 ถ้าจะใช้ ให้comment set onclick แบบง่าย // itemView.setOnClickListener(this); } @Override public void onClick(View v) { itemClickListener.onItemClick(getAdapterPosition()); } } }
/* The CaseChecker class inheriates the Case class, who basically checks that text file searching for keywords setting up objects for those cases for example if the CaseChecker found a murder keyword then it would create a CrimeAgainstPerson object */ package legaladvisor; import java.io.*; import java.util.logging.Level; import java.util.logging.Logger; import java.util.Scanner; public class caseChecker extends Case{ private String CaseType; private int agePerson; private String [] wordBank; //a bank of key words found in the text file private File caseFile; Scanner input= new Scanner(System.in); public caseChecker(String rem, String jur, File complaint, int age) throws IOException { super(rem, jur); caseFile = complaint; agePerson=age; } String readFile() { String st = null; String s = ""; try { BufferedReader br = new BufferedReader (new FileReader (this.caseFile)); try { while ((st = br.readLine()) != null){ s += st + " "; } return s; } catch (IOException ex) { Logger.getLogger(caseChecker.class.getName()).log(Level.SEVERE, null, ex); } } catch (FileNotFoundException ex) { Logger.getLogger(caseChecker.class.getName()).log(Level.SEVERE, null, ex); } return null; } //methods that cecks if any of the types cases apply to the this complaint //each case type class will call this method to check if any of their clases apply here public Case findKeyWords (caseChecker caseFile){ this.setWordBank(caseFile.readFile().split("\\s")); String jurisdiction=""; String word = ""; Case c1=new Case("",""); for(String w : this.getWordBank()){ word = w; if(super.SearchMechanism(w, super.getJusrisdictions(), 0)){ if(this.getISM()==0){ jurisdiction="Ontario"; } else{ jurisdiction="Canada"; } } if (super.SearchMechanism(w, super.getFraud(), 0)){ super.setType ("Criminal Case"); double amount=0; System.out.println("Please enter the amount of money stolen:"); amount=input.nextDouble(); MoneyCrimes fraud= new MoneyCrimes ("Trial",jurisdiction,"", "", amount, true); for(int i=0;i<wordBank.length;i++){ fraud.setCrimeAndSentence(wordBank[i]); } fraud.setCrime("Money Crime"); c1=fraud; break; } else if (super.SearchMechanism(w, super.getElectronicCrime(), 0)){ super.setType ("Criminal Case"); double amount=0; System.out.println("Please enter the amount of money stolen:"); amount=input.nextDouble(); MoneyCrimes electronicCrime = new MoneyCrimes ("Trial",jurisdiction, "", "", amount, false); for(int i=0;i<wordBank.length;i++){ electronicCrime.setCrimeAndSentence(wordBank[i]); } electronicCrime.setCrime("Money Crime"); c1=electronicCrime; break; } else if (super.SearchMechanism(w, super.getMoneyLaundering(), 0)){ super.setType("Criminal Case"); double amount=0; System.out.println("Please enter the amount of money laundered:"); amount=input.nextDouble(); MoneyCrimes moneyLaundering = new MoneyCrimes ("Trial",jurisdiction, "", "", amount, false); for(int i=0;i<wordBank.length;i++){ moneyLaundering.setCrimeAndSentence(wordBank[i]); } moneyLaundering.setCrime("Money Crime"); c1=moneyLaundering; break; } else if (super.SearchMechanism(w, super.getTheft(), 0)){ super.setType("Criminal Case"); double amount=0; System.out.println("Please enter the amount of money stolen:"); amount=input.nextDouble(); MoneyCrimes theft = new MoneyCrimes ("Trial",jurisdiction, "", "", amount, false); for(int i=0;i<wordBank.length;i++){ theft.setCrimeAndSentence(wordBank[i]); } theft.setCrime("Money Crime"); c1=theft; break; } else if (super.SearchMechanism(w, super.getRobbery(), 0)){ super.setType ("Criminal Case"); double amount=0; System.out.println("Please enter the amount of money stolen:"); amount=input.nextDouble(); MoneyCrimes robbery = new MoneyCrimes ("Trial",jurisdiction, "", "", amount, false); for(int i=0;i<wordBank.length;i++){ robbery.setCrimeAndSentence(wordBank[i]); } robbery.setCrime("Money Crimes"); c1=robbery; break; } if (super.SearchMechanism(w, super.getMurderkeywords(), 0)){ super.setType("Criminal Case"); CrimeAgainstPerson murder = new CrimeAgainstPerson ("Trial", jurisdiction, " ", " ", " "); for(int i=0;i<wordBank.length;i++){ murder.setMensRea(wordBank[i]); } for(int i=0;i<wordBank.length;i++){ murder.setCrimeTypeAndSentence(wordBank[i]); } murder.setCrime("Crimes against the Person"); c1=murder; } else if (super.SearchMechanism(w, super.getAssaultkeywords(), 0)){ super.setType("Criminal Case"); CrimeAgainstPerson assault = new CrimeAgainstPerson ("Trial", jurisdiction, "", "", ""); assault.setCrime("Crimes against the Person"); for(int i=0;i<wordBank.length;i++){ assault.setCrimeTypeAndSentence(wordBank[i]); } c1=assault; break; } if(jurisdiction.equalsIgnoreCase(super.getJusrisdictions()[1])){ //will only be an OHRC case if the jurisdiction is Ontario if (super.SearchMechanism(w, super.getGroundKeywords(), 0)||super.SearchMechanism(w, super.getAreaKeywords(), 0)){ super.setType("Human Rights Case"); OHRC ohrcComplaint = new OHRC ("", "Ontario", "", ""); for(int i=0;i<wordBank.length;i++){ ohrcComplaint.setArea(w); } for(int i=0;i<wordBank.length;i++){ ohrcComplaint.setGrounds(w); } ohrcComplaint.setRemedies(); ohrcComplaint.setCharterOHRC("OHRC Case"); c1=ohrcComplaint; break; } } if(jurisdiction.equalsIgnoreCase("Canada")){ //will only be a Charter case is the jurisdiction is Canada if (super.SearchMechanism(w, super.getIssues(), 0)){ super.setType("Human Rights Case"); Charter charter = new Charter ("No remedies needed", "Canada", ""); for(int i=0;i<wordBank.length;i++){ charter.setRight(w); } charter.setCharterOHRC("Charter Case"); c1=charter; break; } } if (super.SearchMechanism(w, super.getTraffickingTerm(), 0)){ double quantity; super.setType("Criminal Case"); DrugCrime trafficking = new DrugCrime ("Trial", jurisdiction, "", "", true, true, ""); trafficking.setCrime("Drug Crime"); for(int i=0;i<wordBank.length;i++){ trafficking.setTrafficking(wordBank[i]); } System.out.println("Please enter the quanity of drugs in grams:"); quantity=input.nextDouble(); trafficking.setQuantity(quantity); for(int i=0;i<wordBank.length;i++){ trafficking.setTrafficking(wordBank[i]); } for(int i=0;i<wordBank.length;i++){ trafficking.setCrimeTypeAndSentence(wordBank[i]); } for(int i=0;i<wordBank.length;i++){ trafficking.setScheduleType(wordBank[i]); } for(int i=0;i<wordBank.length;i++){ trafficking.setDrugType(wordBank[i]); } c1=trafficking; break; } else if (super.SearchMechanism(w, super.getDrugType(), 0)){ double quantity; super.setType ("Criminal Case"); DrugCrime possession = new DrugCrime ("Trial", jurisdiction, "", "",true, false, ""); possession.setCrime("Drug Crime"); System.out.println("Please enter the quanity of drugs in grams:"); quantity=input.nextDouble(); possession.setQuantity(quantity); for(int i=0;i<wordBank.length;i++){ possession.setCrimeTypeAndSentence(wordBank[i]); } for(int i=0;i<wordBank.length;i++){ possession.setScheduleType(wordBank[i]); } for(int i=0;i<wordBank.length;i++){ possession.setDrugType(wordBank[i]); } c1= possession; break; } else if(super.SearchMechanism(w, super.getFamKeyword(), 0)){ super.setType("Civil Case"); Family fam1= new Family("Court or negotiation, mediation or collaborative settlemnets approaches",jurisdiction,"Family Law",false, false); for(int i=0;i<wordBank.length;i++){ if(wordBank[i].equalsIgnoreCase("child")){ fam1.setChild(true); } else{ fam1.setChild(false); } } for(int i=0;i<wordBank.length;i++){ if(w.equalsIgnoreCase("married")){ fam1.setMarriage(true); } else{ fam1.setMarriage(false); } } int numChildren; System.out.println("How many children do you have?"); numChildren=input.nextInt(); fam1.setNumChild(numChildren); for(int i=0;i<wordBank.length;i++){ fam1.setCustody(w); } for(int i=0;i<wordBank.length;i++){ fam1.setFamilyViolenceType(w); } c1=fam1; break; } else if(super.SearchMechanism(w, super.getContractWord(), 0)){ Contract con1= new Contract("",jurisdiction,"Contract Case","",true,agePerson,false,false,false); super.setType("Civil Case"); for(int i=0;i<wordBank.length;i++){ con1.setLawfulPurpose(wordBank[i]); } for(int i=0;i<wordBank.length;i++){ con1.setDisability(wordBank[i]); } con1.setCapacity(con1.getDisability(), agePerson); for(int i=0;i<wordBank.length;i++){ con1.setFailingToPerform(wordBank[i]); } for(int i=0;i<wordBank.length;i++){ con1.setPurpose(wordBank[i]); } for(int i=0;i<wordBank.length;i++){ con1.setContract(wordBank[i]); } for(int i=0;i<wordBank.length;i++){ con1.setRemedies(wordBank[i]); } c1=con1; break; } } return c1; } public String[] getWordBank() { return wordBank; } public void setWordBank(String[] wordBank) { this.wordBank = wordBank; } public void setCaseType(String CaseType) { this.CaseType = CaseType; } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package tolteco.sigma.view.cliente; import java.util.logging.Level; import tolteco.sigma.model.dao.DatabaseException; import tolteco.sigma.model.entidades.Cliente; import tolteco.sigma.view.MainFrame; import tolteco.sigma.view.Sistema; import tolteco.sigma.view.interfaces.Adicionar; /** * Painel de adição de clientes. * @author Juliano Felipe */ public class AdicionarCliente extends javax.swing.JPanel implements Adicionar<Cliente>{ private final MainCliente MAIN; /** * Creates new form Cliente * @param main */ public AdicionarCliente(MainCliente main) { initComponents(); this.MAIN = main; } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { NomePanel = new javax.swing.JPanel(); NomeField = new javax.swing.JTextField(); TelPanel = new javax.swing.JPanel(); TelFField = new javax.swing.JFormattedTextField(); CPFPanel = new javax.swing.JPanel(); CPFfField = new javax.swing.JFormattedTextField(); EndPanel = new javax.swing.JPanel(); EndBox = new javax.swing.JComboBox(); EndField = new javax.swing.JTextField(); ObsPanel = new javax.swing.JPanel(); jScrollPane2 = new javax.swing.JScrollPane(); ObsPane = new javax.swing.JTextPane(); Salvar = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); jButton1 = new javax.swing.JButton(); NomePanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Nome")); javax.swing.GroupLayout NomePanelLayout = new javax.swing.GroupLayout(NomePanel); NomePanel.setLayout(NomePanelLayout); NomePanelLayout.setHorizontalGroup( NomePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(NomeField) ); NomePanelLayout.setVerticalGroup( NomePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, NomePanelLayout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(NomeField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) ); TelPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Telefone")); try { TelFField.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("(##) #####-####"))); } catch (java.text.ParseException ex) { ex.printStackTrace(); } TelFField.setToolTipText(""); javax.swing.GroupLayout TelPanelLayout = new javax.swing.GroupLayout(TelPanel); TelPanel.setLayout(TelPanelLayout); TelPanelLayout.setHorizontalGroup( TelPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(TelFField, javax.swing.GroupLayout.DEFAULT_SIZE, 107, Short.MAX_VALUE) ); TelPanelLayout.setVerticalGroup( TelPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(TelFField, javax.swing.GroupLayout.Alignment.TRAILING) ); CPFPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("CPF")); try { CPFfField.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("###.###.###-##"))); } catch (java.text.ParseException ex) { ex.printStackTrace(); } javax.swing.GroupLayout CPFPanelLayout = new javax.swing.GroupLayout(CPFPanel); CPFPanel.setLayout(CPFPanelLayout); CPFPanelLayout.setHorizontalGroup( CPFPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(CPFfField) ); CPFPanelLayout.setVerticalGroup( CPFPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, CPFPanelLayout.createSequentialGroup() .addComponent(CPFfField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) ); EndPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Endereço")); EndBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Alameda", "Avenida", "Estrada", "Rodovia", "Rua", "Travessa" })); EndBox.setSelectedIndex(4); EndBox.setToolTipText("Selecione o tipo do logradouro"); EndField.setToolTipText(""); javax.swing.GroupLayout EndPanelLayout = new javax.swing.GroupLayout(EndPanel); EndPanel.setLayout(EndPanelLayout); EndPanelLayout.setHorizontalGroup( EndPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(EndPanelLayout.createSequentialGroup() .addComponent(EndBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(EndField, javax.swing.GroupLayout.DEFAULT_SIZE, 254, Short.MAX_VALUE)) ); EndPanelLayout.setVerticalGroup( EndPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(EndPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(EndBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(EndField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) ); ObsPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Observações")); ObsPane.setToolTipText("Qualquer observação adicional sobre o cliente"); jScrollPane2.setViewportView(ObsPane); javax.swing.GroupLayout ObsPanelLayout = new javax.swing.GroupLayout(ObsPanel); ObsPanel.setLayout(ObsPanelLayout); ObsPanelLayout.setHorizontalGroup( ObsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane2) ); ObsPanelLayout.setVerticalGroup( ObsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 261, Short.MAX_VALUE) ); Salvar.setText("Salvar"); Salvar.setMaximumSize(new java.awt.Dimension(75, 23)); Salvar.setMinimumSize(new java.awt.Dimension(75, 23)); Salvar.setPreferredSize(new java.awt.Dimension(75, 23)); Salvar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { SalvarActionPerformed(evt); } }); jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/tolteco/sigma/view/images/General/Internal/Add.png"))); // NOI18N jButton1.setText("Limpar Campos"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(ObsPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(EndPanel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(NomePanel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(CPFPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(TelPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 193, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(jButton1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(Salvar, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(NomePanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(CPFPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(EndPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(TelPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(ObsPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(Salvar, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton1)) .addContainerGap()) ); }// </editor-fold>//GEN-END:initComponents private void SalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SalvarActionPerformed try { MAIN.getController().insert(getInstance()); } catch (DatabaseException ex) { MainFrame.LOG.log(Level.SEVERE, null, ex); MAIN.displayDatabaseException(ex); } }//GEN-LAST:event_SalvarActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed cleanAllFields(); }//GEN-LAST:event_jButton1ActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel CPFPanel; private javax.swing.JFormattedTextField CPFfField; private javax.swing.JComboBox EndBox; private javax.swing.JTextField EndField; private javax.swing.JPanel EndPanel; private javax.swing.JTextField NomeField; private javax.swing.JPanel NomePanel; private javax.swing.JTextPane ObsPane; private javax.swing.JPanel ObsPanel; private javax.swing.JButton Salvar; private javax.swing.JFormattedTextField TelFField; private javax.swing.JPanel TelPanel; private javax.swing.JButton jButton1; private javax.swing.JLabel jLabel1; private javax.swing.JScrollPane jScrollPane2; // End of variables declaration//GEN-END:variables private static final String EMPTY=""; @Override public void cleanAllFields() { NomeField.setText(EMPTY); CPFfField.setText(EMPTY); TelFField.setText(EMPTY); ObsPane.setText(EMPTY); EndBox.setSelectedItem("Rua"); EndField.setText(EMPTY); } @Override public void fillAllFields(Cliente object) { NomeField.setText(object.getNome() + object.getSobrenome()); CPFfField.setText(object.getCpf()); TelFField.setText(object.getTel()); ObsPane.setText(object.getObs()); String end = object.getEnd(); EndBox.setSelectedItem(end.substring(0,end.indexOf(' '))); EndField.setText(end.substring(end.indexOf(' ')+1)); } @Override public Cliente getInstance() { String nome = NomeField.getText(); String priNome=""; String segundoNome=""; if(nome.contains(" ")){ priNome = nome.substring(0,nome.indexOf(' ')); segundoNome = nome.substring(nome.indexOf(' ')+1); } else { priNome=nome; } String cpf = CPFfField.getText(); String tel = TelFField.getText(); String obs = ObsPane.getText(); String end = (String) EndBox.getSelectedItem() + " " + EndField.getText(); return new Cliente(priNome, segundoNome, obs, end, tel, cpf, Sistema.getUserID()); } }
package com.jayqqaa12.abase.exception; public class DaoException extends AbaseException { private static final long serialVersionUID = 1L; public DaoException() {} public DaoException(String msg) { super(msg); } public DaoException(Throwable ex) { super(ex); } public DaoException(String msg,Throwable ex) { super(msg,ex); } }
package org.buaa.ly.MyCar.http.dto; import com.alibaba.fastjson.annotation.JSONField; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; import lombok.EqualsAndHashCode; import org.buaa.ly.MyCar.entity.VehicleInfo; import java.sql.Timestamp; import java.util.Collection; import java.util.List; import java.util.Map; @Data @EqualsAndHashCode(callSuper = false) @JsonInclude(JsonInclude.Include.NON_NULL) public class VehicleInfoDTO extends DTOBase { Integer id; String name; String displacement; String gearbox; String boxes; String manned; String oil; Integer spare; String description; String type; String picture; VehicleInfoCostDTO cost; Integer status; @JsonProperty(value = "create_time") @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone="GMT+8") Timestamp createTime; Integer vehicleCount; Boolean can_rent; public static VehicleInfoDTO build(VehicleInfo vehicleInfo) { return build(vehicleInfo, VehicleInfoDTO.class); } public static <K> Map<K, VehicleInfoDTO> build(Map<K, VehicleInfo> vehicleInfoMap) { return build(vehicleInfoMap, VehicleInfoDTO.class); } public static List<VehicleInfoDTO> build(Collection<VehicleInfo> vehicleInfoCollection) { return build(vehicleInfoCollection, VehicleInfoDTO.class); } public VehicleInfo build() { return build(this, VehicleInfo.class); } }
/** * OpenKM, Open Document Management System (http://www.openkm.com) * Copyright (c) 2006-2015 Paco Avila & Josep Llort * * No bytes were intentionally harmed during the development of this application. * * 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 2 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, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package com.openkm.openmeetings; import com.openkm.bean.openmeetings.Room; import com.openkm.core.Config; import com.openkm.frontend.client.bean.extension.GWTRoom; /** * OpenMeetingsUtils * * @author jllort * */ public class OpenMeetingsUtils { /** * GWTRoom * * @param room * @return */ public static GWTRoom copy(Room room) { GWTRoom gWTRoom = new GWTRoom(); gWTRoom.setId(room.getId()); gWTRoom.setName(room.getName()); gWTRoom.setPub(room.isPub()); gWTRoom.setType(room.getType()); gWTRoom.setStart(room.getStart()); return gWTRoom; } /** * getOpenMeetingServerURL */ public static String getOpenMeetingServerURL() { if (!Config.OPENMEETINGS_URL.startsWith("http")) { return "http://" + Config.OPENMEETINGS_URL + ":" + Config.OPENMEETINGS_PORT + "/openmeetings"; } else { return Config.OPENMEETINGS_URL + ":" + Config.OPENMEETINGS_PORT + "/openmeetings"; } } /** * getOpenMeetingsLang * * @param lang * @return */ public static int getOpenMeetingsLang(String lang) { int language = 1; // By default english // 3 deutsch (studIP) // 13 korean // 19 ukranian // 21 persian // 24 finish // 28 hebrew if (lang.startsWith("en")) { language = 1; } else if (lang.equals("de-DE")) { language = 2; } else if (lang.startsWith("fr")) { language = 4; } else if (lang.startsWith("it")) { language = 5; } else if (lang.equals("pt-BR")) { language = 7; } else if (lang.startsWith("pt")) { language = 6; } else if (lang.startsWith("es")) { language = 8; } else if (lang.startsWith("ru")) { language = 9; } else if (lang.startsWith("sv")) { language = 10; } else if (lang.equals("zh-CN")) { language = 11; } else if (lang.equals("zh-TW")) { language = 12; } else if (lang.startsWith("ar")) { language = 14; } else if (lang.startsWith("jp")) { language = 15; } else if (lang.startsWith("id")) { language = 16; } else if (lang.startsWith("hu")) { language = 17; } else if (lang.startsWith("tr")) { language = 18; } else if (lang.startsWith("th")) { language = 20; } else if (lang.startsWith("tr")) { language = 18; } else if (lang.startsWith("cs")) { language = 22; } else if (lang.startsWith("gl")) { language = 23; } else if (lang.startsWith("pl")) { language = 25; } else if (lang.startsWith("el")) { language = 26; } else if (lang.startsWith("nl")) { language = 27; } else if (lang.startsWith("ca")) { language = 29; } else if (lang.startsWith("bg")) { language = 30; } else if (lang.startsWith("da")) { language = 31; } else if (lang.startsWith("sk")) { language = 27; } return language; } }
//This is client.Client.java file package client; import handlers.Dictionary; import java.awt.EventQueue; import java.net.URL; import java.util.Arrays; import java.util.Enumeration; import java.util.Hashtable; import java.util.Locale; import java.util.Vector; import org.apache.xmlrpc.client.XmlRpcClient; import org.apache.xmlrpc.client.XmlRpcClientConfigImpl; import org.apache.xmlrpc.client.util.ClientFactory; public class Client { private static XmlRpcClientConfigImpl config; private static XmlRpcClient client; public static void main(String[] args) { try { config = new XmlRpcClientConfigImpl(); config.setServerURL(new URL( "http://localhost:8080/AssignV_Srv/auth_xmlrpc")); config.setEnabledForExtensions(true); config.setEnabledForExceptions(true); } catch (Exception e) { System.out.println("Exception: " + e.getMessage()); } EventQueue.invokeLater(new Runnable() { public void run() { try { Login frame = new Login(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } public static void auth(String user, String password) { config.setBasicUserName(user); config.setBasicPassword(password); client = new XmlRpcClient(); client.setConfig(config); EventQueue.invokeLater(new Runnable() { public void run() { try { MainFrom frame = new MainFrom(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } private static String getTranslation(String words, Locale locale){ ClientFactory factory = new ClientFactory(client); Dictionary myDictionary = (Dictionary) factory .newInstance(Dictionary.class); Hashtable<String, String> listTranslation = myDictionary.getWords(new Vector<String>(Arrays.asList(words.split(","))), locale); String output = ""; Enumeration<String> keys = listTranslation.keys(); while(keys.hasMoreElements()){ String key = keys.nextElement(); output += key + ": " + listTranslation.get(key) + "\n"; } return output; } public static String fiToEn(String words) { Locale locale = new Locale("en", "GB"); return getTranslation(words, locale); } public static String enToFi(String words) { Locale locale = new Locale("fi", "FI"); return getTranslation(words, locale); } }
package com.libedi.demo.util; import java.util.List; import org.springframework.data.domain.Page; import lombok.AccessLevel; import lombok.Getter; /** * PageHelper class * * @author Sang-jun, Park * @param <T> * @since 2019. 01. 08 */ @Getter public class PageHelper<T> { /** 페이지 그룹 사이즈 */ private final int groupSize; /** 현재 페이지 (one-based) */ private final int currentPage; /** 현재 페이지 그룹의 시작 페이지 */ private final int startPage; /** 현재 페이지 그룹의 마지막 페이지 */ @Getter(value = AccessLevel.NONE) private final int lastPage; /** 총 페이지 */ @Getter(value = AccessLevel.NONE) private final int totalPage; /** 현재 페이지 데이터 건수 */ private final int currentCount; /** 전체 데이터 건수 */ private final long totalCount; /** 조회된 데이터 */ private final List<T> content; /** * PageHelper 생성자 - groupSize: 10 * @param page */ private PageHelper(final Page<T> page) { this(page, 10); } /** * PageHelper 생성자 * @param page * @param groupSize */ private PageHelper(final Page<T> page, final int groupSize) { this.groupSize = groupSize; this.currentPage = page.getNumber() + 1; this.startPage = (currentPage - 1) / groupSize + 1; this.lastPage = startPage + groupSize - 1; this.totalPage = page.getTotalPages(); this.currentCount = page.getNumberOfElements(); this.totalCount = page.getTotalElements(); this.content = page.getContent(); } public static <T> PageHelper<T> of(final Page<T> page) { return new PageHelper<T>(page); } public static <T> PageHelper<T> of(final Page<T> page, final int groupSize) { return new PageHelper<T>(page, groupSize); } public int getLastPage() { return lastPage > totalPage ? totalPage : lastPage; } public boolean hasPrevGroup() { return this.startPage > 1; } public boolean hasNextGroup() { return this.getLastPage() < this.totalPage; } }
package tw.org.iii.myclass; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Timer; import java.util.TimerTask; import javax.swing.JLabel; public class MyClock extends JLabel { private Timer timer; public MyClock() { timer = new Timer(); timer.schedule(new MyTask(), 0, 1000); } private class MyTask extends TimerTask { @Override public void run() { SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); Calendar now = Calendar.getInstance(); setText(sdf.format(now.getTime())); } } }
package com.tencent.mm.ui.chatting; import android.view.View; import com.tencent.mm.R; import com.tencent.mm.storage.bd; import com.tencent.mm.ui.base.h; import com.tencent.mm.ui.chatting.c.a; import com.tencent.mm.ui.chatting.t.d; public class t$l extends d { public t$l(a aVar) { super(aVar); } public final void a(View view, a aVar, bd bdVar) { h.a(aVar.tTq.getContext(), aVar.tTq.getMMResources().getString(R.l.emoji_chatting_reward_tips_disable_msg), "", aVar.tTq.getMMResources().getString(R.l.emoji_chatting_reward_tips_enable), aVar.tTq.getMMResources().getString(R.l.emoji_chatting_reward_tips_disable), new 1(this), new 2(this)); } }
package stream.file.test; /* * 파일에 입력된 내용을 읽어서 * 또 다른 으로 출력하는 로직을 작성 * :: * 스트림 * 입력 2개 -- FileReader (node), BufferedReader (filter) * 출력 2개 -- FileWriter (node), BufferedWriter (filter) */ import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; public class FileReadingAndWritingTest3 { public static void main(String[] args) throws IOException { //1. 스트림생성 -- 4개 생성 //2. while문에서 file의 내용을 읽고 //3. 또다른 파일로 출력하기 (Sink)... BufferedReader br = new BufferedReader(new FileReader("src\\hope.txt")); PrintWriter pw = new PrintWriter(new FileWriter("src\\hope2.txt", true));//이어쓰기 기능 //PrintWriter pw = new PrintWriter("src\\hope2.txt");//node도되고 filter도 된다. Node-> 바로 파일을 만들수 있다. try{ String line = null; while((line = br.readLine()) != null) { pw.println(line); } //bw.flush();//auto flushing 기능... 데이터를 모아두지 말고 입력될 떄마다 바로 출력한다. }finally { br.close(); pw.close(); } } }
package HelperObjects; import Objects.FacilityRegisterInformation; import Objects.FacilityVisitLog; import java.io.*; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Scanner; public class FacilityVisitLogger { private String logFileName; private FacilityRegisterInformation currentFacilityRegisterInformation; private LocalDateTime entryTime; private LocalDateTime leaveTime; private static final String logFileBasePath = "Resources/userLogs/facilityVisitLogs/"; private static final int purgeLogsTimeInDays = 30; private static LocalDate purgeDate; public FacilityVisitLogger() { purgeDate = LocalDate.now().minusDays(purgeLogsTimeInDays); } public void startVisit(FacilityRegisterInformation currentFacilityRegisterInformation) { this.currentFacilityRegisterInformation = currentFacilityRegisterInformation; entryTime = LocalDateTime.now(); leaveTime = null; } public void stopVisit() throws IOException { if (this.currentFacilityRegisterInformation == null | entryTime == null) throw new IllegalArgumentException("Can't execute leave facility logic: visit not initialized"); else { leaveTime = LocalDateTime.now(); //Refresh the log file writeLogs(); //Reset the visit logger for a new visit resetLogger(); } } private void writeLogs() throws IOException { //Create the log file File facilityVisitLogFile = new File(logFileBasePath + logFileName + ".txt"); facilityVisitLogFile.createNewFile(); //Read all previous logs ArrayList<FacilityVisitLog> facilityVisitLogEntries = readFacilityVisitLogsFromFile(facilityVisitLogFile); //Purge the expired logs facilityVisitLogEntries.removeIf(facilityVisitLog -> facilityVisitLog.getEntryTime().toLocalDate().isBefore(purgeDate)); //Add the new facility entry facilityVisitLogEntries.add(new FacilityVisitLog(entryTime, leaveTime, currentFacilityRegisterInformation)); //write all logs to the file FileWriter fw = new FileWriter(facilityVisitLogFile); BufferedWriter out = new BufferedWriter(fw); for (FacilityVisitLog facilityVisitLog : facilityVisitLogEntries) { out.write(facilityVisitLog.toBase64String()); out.newLine(); } out.close(); } private void resetLogger() { currentFacilityRegisterInformation = null; entryTime = null; leaveTime = null; } public ArrayList<FacilityVisitLog> readFacilityVisitLogsFromFile(File facilityVisitLogFile) throws FileNotFoundException { ArrayList<FacilityVisitLog> facilityVisitLogs = new ArrayList<>(); Scanner sc = new Scanner(facilityVisitLogFile); while (sc.hasNextLine()) { facilityVisitLogs.add(FacilityVisitLog.fromBase64String(sc.nextLine())); } sc.close(); return facilityVisitLogs; } public void setLogFileName(String logFileName) { this.logFileName = logFileName; } }
package micro.usuarios.administradores.controllers; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import dto.main.Respuesta; import dto.usuarios.FiltroUsuarioAdminDTO; import interfaces.abstracts.ACrudEndPoints; import micro.usuarios.administradores.interfaces.IUsuarioAdminService; import model.auth.usuarios.administradores.UsuarioAdministrador; import model.auth.usuarios.fingerprint.FingerPrintAuthentication; import model.validations.interfaces.OnCreate; import model.validations.interfaces.OnUpdate; @RestController @RequestMapping(path = "/usuarios/admin") public class UsuarioAdminController extends ACrudEndPoints<UsuarioAdminController> { Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired IUsuarioAdminService usuarioService; @PostMapping(value = "/filtro", consumes = { MediaType.APPLICATION_JSON_VALUE }, produces = { MediaType.APPLICATION_JSON_VALUE }) public ResponseEntity<Respuesta<Page<UsuarioAdministrador>>> filtrar(Pageable pageable, @RequestBody FiltroUsuarioAdminDTO filtroUsuarioDTO) { // size=10 page=1 Respuesta<Page<UsuarioAdministrador>> respuesta = usuarioService.filtrar(pageable, filtroUsuarioDTO); return ResponseEntity.status(respuesta.getCodigoHttp()).body(respuesta); } @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE, produces = { MediaType.APPLICATION_JSON_VALUE }) public ResponseEntity<Respuesta<UsuarioAdministrador>> crear( @Validated(OnCreate.class) @RequestBody UsuarioAdministrador usuario) { Respuesta<UsuarioAdministrador> respuesta = usuarioService.crear(usuario); return ResponseEntity.status(respuesta.getCodigoHttp()).body(respuesta); } @PutMapping(value = "/{id}", consumes = MediaType.APPLICATION_JSON_VALUE, produces = { MediaType.APPLICATION_JSON_VALUE }) public ResponseEntity<Respuesta<UsuarioAdministrador>> actualizar(@PathVariable("id") Long id, @Validated(OnUpdate.class) @RequestBody UsuarioAdministrador usuario) { Respuesta<UsuarioAdministrador> respuesta = usuarioService.actualizar(id, usuario); return ResponseEntity.status(respuesta.getCodigoHttp()).body(respuesta); } @DeleteMapping(value = "/{id}", produces = { MediaType.APPLICATION_JSON_VALUE }) public ResponseEntity<Respuesta<Boolean>> borrar(@PathVariable("id") Long id) { Respuesta<Boolean> respuesta = usuarioService.borrar(id); return ResponseEntity.status(respuesta.getCodigoHttp()).body(respuesta); } // PUBLICO @PostMapping(value = "/update/externo/huellas", consumes = MediaType.APPLICATION_JSON_VALUE, produces = { MediaType.APPLICATION_JSON_VALUE }) public ResponseEntity<Respuesta<Boolean>> actualizarHuellas( @RequestBody FingerPrintAuthentication fingerPrintAuthentication) { Respuesta<Boolean> respuesta = usuarioService.actualizarHuellas(fingerPrintAuthentication); return ResponseEntity.status(respuesta.getCodigoHttp()).body(respuesta); } }
package demo.dao.impl; import org.springframework.stereotype.Component; import demo.dao.AbstractDao; import demo.dao.UserDao; import demo.model.User; @Component public class UserDaoImpl extends AbstractDao implements UserDao { public int save(User u) { return (Integer) this.getHibernateTemplate().save(u); } @Override public void delete(int id) { this.getHibernateTemplate().delete(this.load(id)); } @Override public void update(User u) { this.getHibernateTemplate().update(u); } @Override public User load(int id) { return this.getHibernateTemplate().load(User.class, id); } }
package com.cxjd.nvwabao.bean; import java.io.Serializable; /** * 项目名: NvWaBao2 * 包名: com.cxjd.nvwabao.bean * 文件名: Circles * 创建者: LC * 创建时间: 2018/3/26 14:10 * 描述: 圈子的圈子实体类 */ public class Circles implements Serializable{ private int id; private int headId; private String title; private String gengXin; private String chengYuan; private String tieZi; public Circles(int headId,String title, String gengXin, String chengYuan, String tieZi,int id) { this.id = id; this.headId = headId; this.title = title; this.gengXin = gengXin; this.chengYuan = chengYuan; this.tieZi = tieZi; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getHeadId() { return headId; } public void setHeadId(int headId) { this.headId = headId; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getGengXin() { return gengXin; } public void setGengXin(String gengXin) { this.gengXin = gengXin; } public String getChengYuan() { return chengYuan; } public void setChengYuan(String chengYuan) { this.chengYuan = chengYuan; } public String getTieZi() { return tieZi; } public void setTieZi(String tieZi) { this.tieZi = tieZi; } }
package Types; import java.util.List; import java.util.Scanner; public class In { List<String> tokens; Variables vars; int depth; String id; public In(List tokens,Variables vars, int depth) { this.tokens = tokens; this.depth = depth; this.vars = vars; } public void Parse() { if (Print.printTree) Print.tree(this.getClass().getName(), tokens, depth); id = tokens.get(1); } public void Exec() { System.out.print(": "); Scanner scanner = new Scanner(System.in); String input = scanner.nextLine(); int value = Integer.parseInt(input); if (value < 0) { Print.error(this.getClass().getName() + " ERROR: Negative input"); } vars.AssignVariable(id, value); } public void Exec(Variables vars2) { // TODO Auto-generated method stub } }
package at.porscheinformatik.sonarqube.licensecheck; import java.util.Set; import java.util.TreeSet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.api.batch.Sensor; import org.sonar.api.batch.SensorContext; import org.sonar.api.batch.fs.FileSystem; import org.sonar.api.config.Settings; import org.sonar.api.measures.Measure; import org.sonar.api.resources.Project; import at.porscheinformatik.sonarqube.licensecheck.interfaces.Scanner; import at.porscheinformatik.sonarqube.licensecheck.license.License; import at.porscheinformatik.sonarqube.licensecheck.maven.MavenDependencyScanner; import at.porscheinformatik.sonarqube.licensecheck.mavendependency.MavenDependencyService; import at.porscheinformatik.sonarqube.licensecheck.mavenlicense.MavenLicenseService; import at.porscheinformatik.sonarqube.licensecheck.npm.PackageJsonDependencyScanner; public class LicenseCheckSensor implements Sensor { private static final Logger LOGGER = LoggerFactory.getLogger(LicenseCheckSensor.class); private final FileSystem fs; private final Settings settings; private final ValidateLicenses validateLicenses; private final Scanner[] scanners; public LicenseCheckSensor(FileSystem fs, Settings settings, ValidateLicenses validateLicenses, MavenLicenseService mavenLicenseService, MavenDependencyService mavenDependencyService) { this.fs = fs; this.settings = settings; this.validateLicenses = validateLicenses; this.scanners = new Scanner[]{ new PackageJsonDependencyScanner(), new MavenDependencyScanner(mavenLicenseService, mavenDependencyService)}; } @Override public boolean shouldExecuteOnProject(Project project) { return true; } @Override public void analyse(Project module, SensorContext context) { if (settings.getBoolean(LicenseCheckPropertyKeys.ACTIVATION_KEY)) { String mavenProjectDependencies = settings.getString("sonar.maven.projectDependencies"); Set<Dependency> dependencies = new TreeSet<>(); for (Scanner scanner : scanners) { dependencies.addAll(scanner.scan(fs.baseDir(), mavenProjectDependencies)); } Set<Dependency> validatedDependencies = validateLicenses.validateLicenses(dependencies, module, context); Set<License> usedLicenses = validateLicenses.getUsedLicenses(validatedDependencies, module); saveDependencies(context, validatedDependencies); saveLicenses(context, usedLicenses); } else { LOGGER.info("Scanner is set to inactive. No scan possible."); } } private static void saveDependencies(SensorContext sensorContext, Set<Dependency> dependencies) { if (!dependencies.isEmpty()) { sensorContext.saveMeasure( new Measure<String>(LicenseCheckMetrics.INPUTDEPENDENCY, Dependency.createString(dependencies))); } } private static void saveLicenses(SensorContext sensorContext, Set<License> licenses) { if (!licenses.isEmpty()) { sensorContext .saveMeasure(new Measure<String>(LicenseCheckMetrics.INPUTLICENSE, License.createString(licenses))); } } }
package cloudscript.lang.nodes; import cloudscript.lang.*; import java.util.ArrayList; /** Collection of nodes. */ public class Nodes extends Node { private ArrayList<Node> nodes; public Nodes() { nodes = new ArrayList<Node>(); } public void add(Node n) { nodes.add(n); } /** Eval all the nodes and return the last returned value. */ public CloudScriptObject eval(Context context) throws CloudScriptException { CloudScriptObject lastEval = CloudScriptRuntime.getNil(); for (Node n : nodes) { lastEval = n.eval(context); } return lastEval; } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Bocharov.com; import Bocharov.com.sorts.*; import Bocharov.threads.SortThread; /** * * @author Дмитрий */ public class Start { public void start() { int[] mas={4,5,1,2,5,67,100}; SortThread thread1=new SortThread(new BubbleSort(mas.clone())); SortThread thread2=new SortThread(new InsertionSort(mas.clone())); SortThread thread3=new SortThread(new SelectionSort(mas.clone())); SortThread thread4=new SortThread(new ShellSort(mas.clone())); thread1.run(); thread2.run(); thread3.run(); thread4.run(); } }
package com.tencent.mm.plugin.account.ui; class MobileInputUI$11 implements Runnable { final /* synthetic */ int aEe; final /* synthetic */ MobileInputUI eTe; MobileInputUI$11(MobileInputUI mobileInputUI, int i) { this.eTe = mobileInputUI; this.aEe = i; } public final void run() { MobileInputUI.h(this.eTe).smoothScrollBy(0, this.aEe); } }
package programmers.lv1; public class PhoneNum_Test { //뒤에 숫자 4개 뽑아내고 앞에 숫자 전부 *로 replaceAll 이용해서 바꿔준뒤 합쳤다. //참고로 replaceAll은 앞에 파라미터를 정규식으로도 받아서 저런식이 가능함 public String solution(String phone_number) { String answer = ""; int length = phone_number.length(); String num = phone_number.substring(length - 4, length); answer = phone_number.substring(0, length - 4).replaceAll(".","*") + num; return answer; } }
package jneiva.hexbattle.estado; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import com.badlogic.gdx.graphics.Color; import jneiva.hexbattle.Constantes; import jneiva.hexbattle.ControladorBatalha; import jneiva.hexbattle.ControladorEstrutura; import jneiva.hexbattle.ControladorTurnos; import jneiva.hexbattle.PlanoDeAcao; import jneiva.hexbattle.Time; import jneiva.hexbattle.eventos.EventoCelula; import jneiva.hexbattle.tiles.Celula; import jneiva.hexbattle.unidade.Unidade; public class EstadoEscolherAcao extends EstadoBatalha { private Unidade unidadeAtual; private List<Celula> celulasMovimento; private List<Celula> celulasAtaque; ControladorTurnos controladorTurnos; public EstadoEscolherAcao(ControladorBatalha d) { super(d); // TODO Auto-generated constructor stub } @Override public void entrar() { super.entrar(); System.out.println("Entrou Escolher Acao!"); controladorTurnos = this.dono.controladorTurnos; unidadeAtual = controladorTurnos.getUnidadeAtual(); celulasMovimento = getMapa().buscaEmArea(unidadeAtual.getCelula(), unidadeAtual.getMovimentos(), true); buscarAtaquesPossiveis(); selecionarAlcance(); if (!checarAcoes()) return; if (controladorTurnos.getRoundAtual() == Time.Computador) { escolherAcaoComputador(); } } @Override public void sair() { super.sair(); getMapa().selecionarTodas(false); } private void buscarAtaquesPossiveis() { celulasAtaque = new ArrayList<Celula>(); List<Celula> celulasNoAlcance = getMapa().buscaEmArea(unidadeAtual.getCelula(), unidadeAtual.ataque.getAlcance(), false); for(Celula cel : celulasNoAlcance) { if (cel.unidade != null ) { if (cel.unidade.equipe.getTime() != unidadeAtual.equipe.getTime()) { celulasAtaque.add(cel); } } else if(cel.estrutura != null) { if (cel.estrutura.equipe.getTime() != unidadeAtual.equipe.getTime()) { celulasAtaque.add(cel); } } } } private boolean checarAcoes() { if ((celulasMovimento.isEmpty() && celulasAtaque.isEmpty()) || unidadeAtual.turno.unidadeAtacou) { controladorTurnos.removerUnidadeRound(unidadeAtual); this.dono.mudarEstado(new EstadoEscolherUnidade(this.dono)); return false; } return true; } @Override public boolean onCelulaSelecionada(String topico, Object dado) { if(!super.onCelulaSelecionada(topico, dado)) return false; EventoCelula evento = (EventoCelula) dado; selecionarAlcance(); if (evento.celula == null) return false; if (celulasMovimento.contains(evento.celula)) { List<Celula> caminho = getMapa().buscaCaminho(unidadeAtual.getCelula(), evento.celula, unidadeAtual.equipe.getTime(), true); getMapa().selecionarCelulas(true, caminho, Constantes.corCaminho); } else if (celulasAtaque.contains(evento.celula)) { getMapa().selecionarCelula(true, evento.celula, Constantes.corAtaqueAlvo); } return true; } @Override public boolean onCelulaClicada(String topico, Object dado) { if(!super.onCelulaClicada(topico, dado)) return false; EventoCelula evento = (EventoCelula) dado; if (evento.celula == null) return false; if (celulasMovimento.contains(evento.celula)) { this.dono.mudarEstado(new EstadoMovimento(this.dono, evento.celula)); } else if (celulasAtaque.contains(evento.celula)) { if (evento.celula.unidade != null) this.dono.mudarEstado(new EstadoAtaque(this.dono, evento.celula.unidade)); else if (evento.celula.estrutura != null) this.dono.mudarEstado(new EstadoAtaque(this.dono, evento.celula.estrutura)); } return true; } private void escolherAcaoComputador() { if (dono.controladorAI.planoDeAcao == null) { dono.controladorAI.calcularPlanoDeAcao(); } PlanoDeAcao plano = dono.controladorAI.planoDeAcao; if (unidadeAtual.getMovimentos() > 0 && plano.alvoMovimento != unidadeAtual.getCelula()) { List<Celula> caminho = getMapa().buscaCaminho(unidadeAtual.getCelula(), plano.alvoMovimento, unidadeAtual.equipe.getTime(), true); getMapa().selecionarCelulas(true, caminho, Constantes.corCaminho); esperar(); this.dono.mudarEstado(new EstadoMovimento(this.dono, plano.alvoMovimento)); } else { if (plano.alvoAtaque.unidade != null) { getMapa().selecionarCelula(true, plano.alvoAtaque, Constantes.corAtaqueAlvo); esperar(); this.dono.mudarEstado(new EstadoAtaque(this.dono, plano.alvoAtaque.unidade)); } else if (plano.alvoAtaque.estrutura != null) { getMapa().selecionarCelula(true, plano.alvoAtaque, Constantes.corAtaqueAlvo); esperar(); this.dono.mudarEstado(new EstadoAtaque(this.dono, plano.alvoAtaque.estrutura)); } } } private void esperar() { try { TimeUnit.MILLISECONDS.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public boolean onAcaoCancelada(String topico, Object dado) { if(!super.onAcaoCancelada(topico, dado)) return false; this.dono.mudarEstado(new EstadoEscolherUnidade(this.dono)); return true; } private void selecionarAlcance() { getMapa().selecionarTodas(false); getMapa().selecionarCelulas(true, celulasMovimento, Constantes.corMovimento); getMapa().selecionarCelulas(true, celulasAtaque, Constantes.corAtaque); } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.neu.controller; import com.neu.Bean.MessageBean; import com.neu.Bean.UsersBean; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.sql.DataSource; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.ResultSetHandler; import org.apache.commons.dbutils.handlers.BeanHandler; import org.apache.commons.dbutils.handlers.BeanListHandler; import org.apache.commons.mail.DefaultAuthenticator; import org.apache.commons.mail.Email; import org.apache.commons.mail.SimpleEmail; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.AbstractController; /** * * @author Rajat */ public class LoginController extends AbstractController { public LoginController() { } protected ModelAndView handleRequestInternal( HttpServletRequest request, HttpServletResponse response) throws Exception { DataSource ds = (DataSource) this.getApplicationContext().getBean("myDataSource"); String action = request.getParameter("action"); ModelAndView mv = new ModelAndView(); HttpSession session = request.getSession(); if (action.equalsIgnoreCase("login")) { try { String userName = request.getParameter("user"); String password = request.getParameter("password"); QueryRunner run = new QueryRunner(ds); ResultSetHandler<UsersBean> user = new BeanHandler<UsersBean>(UsersBean.class); Object[] params = new Object[2]; params[0] = userName; params[1] = password; UsersBean ub = run.query("select * from userstable where userName =? and userPassword=?", user, params); if (ub != null) { ResultSetHandler<List<MessageBean>> messages = new BeanListHandler<MessageBean>(MessageBean.class); List<MessageBean> msg = run.query("select * from messages where userName =?", messages, userName); session.setAttribute("userName", userName); session.setAttribute("messageList", msg); mv.setViewName("userhome"); } else { mv.addObject("error", "true"); mv.setViewName("index"); } } catch (Exception ex) { System.out.println("Error Message" + ex.getMessage()); } } else if (action.equalsIgnoreCase("logout")) { session.invalidate(); mv.setViewName("index"); } else if (action.equalsIgnoreCase("signup")) { System.out.println("sign up"); // // String userName = request.getParameter("user"); // String password = request.getParameter("password"); // String emailObj = request.getParameter("emailObj"); // // System.out.println("printing details: " + userName + " " +password + " "+emailObj); mv.setViewName("signup"); } else if (action.equalsIgnoreCase("signupsubmit")) { System.out.println("sign up submit"); String userName = request.getParameter("user"); String password = request.getParameter("password"); String email = request.getParameter("email"); System.out.println("printing details: " + userName + " " +password + " "+email); if(userName.equals("")||(password.equals(""))||(email.equals(""))) { System.out.println("empty values"); mv.addObject("error", "true"); } else{ ResultSetHandler<UsersBean> user = new BeanHandler<UsersBean>(UsersBean.class); Object[] params = new Object[3]; params[0] = userName; params[1] = password; params[2] = email; QueryRunner run = new QueryRunner(ds); int inserts = run.update("insert into userstable (UserName,UserPassword,UserEmail) values (?,?,?)", params);//Logic to insert into table System.out.println("inserts value " + inserts ); if(inserts>0) { mv.addObject("success", "true"); Email emailObj = new SimpleEmail(); emailObj.setHostName("smtp.googlemail.com");//If a server is capable of sending emailObj, then you don't need the authentication. In this case, an emailObj server needs to be running on that machine. Since we are running this application on the localhost and we don't have a emailObj server, we are simply asking gmail to relay this emailObj. emailObj.setSmtpPort(465); emailObj.setAuthenticator(new DefaultAuthenticator("contactapplication2017@gmail.com", "springmvc")); emailObj.setSSLOnConnect(true); emailObj.setFrom("webtools@hello.com");//This emailObj will appear in the from field of the sending emailObj. It doesn't have to be a real emailObj address.This could be used for phishing/spoofing! emailObj.setSubject("TestMail"); emailObj.setMsg("This is spring MVC Contact Application sending you the email"); emailObj.addTo(email);//Will come from the sign up details emailObj.send(); } } mv.setViewName("signup"); } return mv; } }
package com.lxy.basic; import java.util.Scanner; /** * @author menglanyingfei * @date 2017-2-20 * 时间:19:24-19:33 * 9 * 提交次数:1 */ public class Main13_ArraySorting { /** * @param args */ public static void main(String[] args) { Scanner sc = new Scanner(System.in); int num = sc.nextInt(); int[] arr = new int[num]; for (int i = 0; i < num; i++) { arr[i] = sc.nextInt(); } sc.close(); // 冒泡排序 for (int i = arr.length - 1; i > 0; i--) { for (int j = 0; j < i; j++) { if (arr[j] > arr[j + 1]) { int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } } }
package io.bega.kduino.api; import com.google.gson.JsonObject; import com.squareup.okhttp.Call; import org.json.JSONObject; import java.util.List; import io.bega.kduino.datamodel.BuoyDefinition; import io.bega.kduino.datamodel.BuoyPostDefinition; import io.bega.kduino.datamodel.CapturesDefinition; import io.bega.kduino.datamodel.GeoLocationServiceResponse; import io.bega.kduino.datamodel.LastId; import io.bega.kduino.datamodel.MeasurementPostData; import io.bega.kduino.datamodel.Measurements; import io.bega.kduino.datamodel.RecoveryPassword; import io.bega.kduino.datamodel.User; import io.bega.kduino.datamodel.UserDefinition; import io.bega.kduino.datamodel.UserRecievedDefinition; import retrofit.Callback; import retrofit.client.Response; import retrofit.http.Body; import retrofit.http.Field; import retrofit.http.FormUrlEncoded; import retrofit.http.GET; import retrofit.http.POST; import retrofit.http.PUT; import retrofit.http.Path; import retrofit.http.Query; /** * Created by usuario on 30/07/15. */ public interface KdUINOApiServer { public static final String API_GET_COUNTRY = "http://ip-api.com"; public static final String API_URL = "http://52.28.184.220"; @GET("/buoy?format=json") void getBuoy(Callback<List<BuoyDefinition>> buoys); @GET("/buoy/user") void getBuoyUser(Callback<List<BuoyDefinition>> buoys); @GET("/buoy/user") List<BuoyPostDefinition> getBuoyUser(); @GET("/user/all") void getAllUser(Callback<String> cb); @GET("/user/all") String getAllUserSynchro(); @GET("/user/lastid") void getLastId(Callback<String> cb); @GET("/user/lastid") String getLastIdSynchro(); @POST("/user/recover") void recoverPassword(@Body RecoveryPassword password, Callback<String> cb); @POST("/user/recover") String recoverPasswordSynchro(@Body RecoveryPassword password); @GET("/json") GeoLocationServiceResponse getLocationSynchro(); @GET("/json") void getLocation(Callback<GeoLocationServiceResponse> callback); @POST("/buoy/") void createBuoy(@Body BuoyPostDefinition buoy, Callback<String> cb); @POST("/buoy/") JsonObject createBuoySynchro(@Body BuoyPostDefinition buoy); @PUT("/user/") void createUser(@Body UserDefinition user, Callback<String> cb); @PUT("/user/") String createUserSynchro(@Body UserDefinition user); @POST("/measurements/") void addMeasurement(@Body MeasurementPostData measurements, Callback<JsonObject> callback); @POST("/measurements/") JsonObject addMeasurementSynchro(@Body MeasurementPostData measurements); @FormUrlEncoded @POST("/oauth2/access_token") void login(@Field("username") String username, @Field("password") String password, @Field("grant_type") String grant_type, @Field("client_id") String clientID, @Field("callback") Callback<JSONObject> callback); @FormUrlEncoded @POST("/oauth2/access_token") Response loginSinchro(@Field("username") String username, @Field("password") String password, @Field("grant_type") String grant_type, @Field("client_id") String clientID ); }
package exercise_chpater10; public class stack { public static void main(String[] args) { intStack mytest= new intStack(); for(int i = 0; i < 5; i++) { mytest.push(i); } System.out.println("the peek is " + mytest.peek()); while (mytest.getSize() != 0) { System.out.print(mytest.pop() + " "); } } } class intStack { private int[] elements; private int size; public static final int DEFAULT_CAPACITY = 16; public intStack() { this(DEFAULT_CAPACITY); } public intStack(int capacity) { elements = new int[capacity]; } public boolean empty() { return size == 0; } public void push(int number) { if(size >= elements.length) { int[] temp = new int[elements.length * 2]; System.arraycopy(elements, 0, temp, 0, elements.length); elements = temp; } elements[size++] = number; } public int pop() { return elements[--size]; } public int getSize() { return size; } public int peek() { return elements[size - 1]; } }
/* * Created by Jakub Sabuda * Copyright (c) 2020 . * Last modified 6/5/20 10:19 AM * */ package com.jakubsabuda.notpeadapp20022020; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.lifecycle.Observer; import androidx.recyclerview.widget.ItemTouchHelper; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.LinearLayout; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.jakubsabuda.notpeadapp20022020.adapters.RecyclerViewAdapter; import com.jakubsabuda.notpeadapp20022020.data.NoteRepository; import com.jakubsabuda.notpeadapp20022020.model.Note; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity implements RecyclerViewAdapter.OnNoteListener, View.OnClickListener { //UI private RecyclerView mRecyclerView; private FloatingActionButton floatingActionButton; //Variables private ArrayList<Note> mNotes = new ArrayList<>(); private RecyclerViewAdapter mNoteRecyclerAdapter; private NoteRepository mNoteRepository; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mRecyclerView = findViewById(R.id.recycler_view); floatingActionButton = findViewById(R.id.fab_button); floatingActionButton.setOnClickListener(this); mNoteRepository = new NoteRepository(this); initRecyclerView(); retrieveNotes(); //Toolbar setSupportActionBar((Toolbar) findViewById(R.id.toolbar_main_activity)); setTitle("Notepad"); } //Setting up RecyclerView private void initRecyclerView() { LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this); mRecyclerView.setLayoutManager(linearLayoutManager); mNoteRecyclerAdapter = new RecyclerViewAdapter(mNotes, this); mRecyclerView.setAdapter(mNoteRecyclerAdapter); new ItemTouchHelper(itemTouchHelper).attachToRecyclerView(mRecyclerView); } //Implementation of clickListener created in RecyclerViewAdapter @Override public void onNoteClick(int position) { Log.d("onNote CLICKED: ", "Item clicled : " + String.valueOf(position)); Intent intent = new Intent(this, NoteActivity.class); intent.putExtra("selected_note", mNotes.get(position)); startActivity(intent); } @Override public void onClick(View v) { Intent intent = new Intent(this, NoteActivity.class); startActivity(intent); } private void deleteNote(Note note){ mNotes.remove(note); mNoteRecyclerAdapter.notifyDataSetChanged(); mNoteRepository.deleteNote(note); } private ItemTouchHelper.SimpleCallback itemTouchHelper = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT) { @Override public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) { return false; } @Override public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) { deleteNote(mNotes.get(viewHolder.getAdapterPosition())); } }; private void retrieveNotes(){ mNoteRepository.retriveNote().observe(this, new Observer<List<Note>>() { @Override public void onChanged(List<Note> notes) { if(mNotes.size()>0){ mNotes.clear(); } if(notes != null){ mNotes.addAll(notes); } mNoteRecyclerAdapter.notifyDataSetChanged(); } }); } }
package net.julisapp.riesenkrabbe.background.networking; import android.accounts.Account; import android.accounts.AccountManager; import android.app.Service; import android.content.AbstractThreadedSyncAdapter; import android.content.ContentProviderClient; import android.content.Context; import android.content.Intent; import android.content.SyncResult; import android.os.Bundle; import android.os.IBinder; import android.util.Log; import java.io.IOException; import static android.util.Log.v; public class SyncService extends Service { public static final String KEY_EXTRAS_SYNC_TYPE = "sync-type"; public static final String KEY_EXTRAS_EVENT_ID = "event-id"; public static final String KEY_EXTRAS_USER_ID = "user-id"; private static final Object sSyncAdapterLock = new Object(); private SyncAdapter sSyncAdapter = null; public SyncService() { } @Override public void onCreate() { synchronized (sSyncAdapterLock) { if (sSyncAdapter == null) { sSyncAdapter = new SyncAdapter(getApplicationContext(), true); } } } @Override public IBinder onBind(Intent intent) { return sSyncAdapter.getSyncAdapterBinder(); } private class SyncAdapter extends AbstractThreadedSyncAdapter { private final String LOG_TAG = SyncAdapter.class.getSimpleName(); private final AccountManager mAccountManager; private final Context mContext; SyncAdapter(Context context, boolean autoInitialize) { super(context, autoInitialize); mContext = context; mAccountManager = AccountManager.get(context); } /** * Perform a sync for this account. SyncAdapter-specific parameters may * be specified in extras, which is guaranteed to not be null. Invocations * of this method are guaranteed to be serialized. * * @param account the account that should be synced * @param extras SyncAdapter-specific parameters * @param authority the authority of this sync request * @param provider a ContentProviderClient that points to the ContentProvider for this * authority * @param syncResult SyncAdapter-specific parameters */ @Override public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) { if (Thread.interrupted()) { return; } int syncType = extras.getInt(KEY_EXTRAS_SYNC_TYPE, -1); if (syncType == -1) { // No Bundle was given to us. boolean uploadThings = extras.getBoolean("upload"); if (uploadThings) { syncType = ServerInteractions.SYNC_UP_ALL; } else { // This could be a third party requesting sync. Let's give them a general one. syncType = ServerInteractions.SYNC_DOWN_GENERAL_SYNC; } } v(LOG_TAG, "The app is syncing"); Log.v(LOG_TAG, "Requested sync has type " + syncType); // ContentResolver.SYNC_EXTRAS_UPLOAD is auto-argument given in extras if the contentProvider was changed. try { // Get the authtoken String authToken = mAccountManager.blockingGetAuthToken(account, AccountService.AUTHTOKEN_TYPE, true); int successes = 0; switch (syncType) { case ServerInteractions.SYNC_DOWN_GENERAL_SYNC: // We want to download all of the starred messages, and update our events. SyncMethods.getEvents(authToken, mContext); SyncMethods.getStarredMessages(authToken, mContext); SyncMethods.getEventTypes(authToken, mContext); SyncMethods.getDeletedsAndDelete(authToken, mContext); break; case ServerInteractions.SYNC_DOWN_MESSAGE: long eventId = extras.getLong(KEY_EXTRAS_EVENT_ID, -1L); SyncMethods.getSingleMessage(authToken, eventId, mContext); break; case ServerInteractions.SYNC_DOWN_USER: long userId = extras.getLong(KEY_EXTRAS_USER_ID); SyncMethods.getSingleUser(authToken, userId, mContext); break; case ServerInteractions.SYNC_DOWN_STARRED: SyncMethods.getStarredEvents(authToken, mContext); break; case ServerInteractions.SYNC_UP_ALL: successes = SyncMethods.postAllSavedThings(authToken, mContext); // Not entirely sure about this, but JIC syncResult.stats.numInserts = syncResult.stats.numInserts + successes; break; case ServerInteractions.SYNC_UP_MESSAGES: syncResult.stats.numInserts = syncResult.stats.numInserts + SyncMethods.postSavedMessages(authToken, mContext); break; case ServerInteractions.SYNC_UP_EVENTS: successes += SyncMethods.postNewEvent(authToken, mContext); successes += SyncMethods.postUpdatedEvent(authToken, mContext); syncResult.stats.numInserts = syncResult.stats.numInserts + successes; case ServerInteractions.SYNC_UP_STARRED: successes += SyncMethods.postSavedStarrings(authToken, mContext); syncResult.stats.numInserts = syncResult.stats.numInserts + successes; break; } } catch (IOException e) { syncResult.stats.numIoExceptions++; } catch (Exception e) { e.printStackTrace(); } } } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.pipoware.jpstviewer; import com.google.common.io.BaseEncoding; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javafx.beans.property.SimpleStringProperty; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.scene.Scene; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.layout.Priority; import javafx.scene.layout.VBox; import javafx.stage.Stage; import org.pipoware.pst.exp.NID; import org.pipoware.pst.exp.PC; import org.pipoware.pst.exp.PCItem; import org.pipoware.pst.exp.PSTFile; import org.pipoware.pst.exp.PropertyDataType; import org.pipoware.pst.exp.PropertyIdentifier; import org.pipoware.pst.exp.PropertyTag; import static org.pipoware.pst.exp.PropertyTag.getPropertyTagFromIdentifier; import org.pipoware.pst.exp.pages.NBTENTRY; /** * * @author Franck Arnulfo */ class NDBItemNBTENTRY extends NDBItem { private final NBTENTRY nbtentry; private final PSTFile pstFile; public NDBItemNBTENTRY(NBTENTRY nbtentry, PSTFile pstFile) { this.nbtentry = nbtentry; this.pstFile = pstFile; } @Override public boolean isLeaf() { return true; } @Override public Iterable<NDBItem> getNDBItems() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void display() { if (nbtentry.nid.nidType == NID.NID_TYPE_NORMAL_FOLDER || nbtentry.nid.nidType == NID.NID_TYPE_NORMAL_MESSAGE) { try { PC pc = pstFile.ndb.getPCFromNBTENTRY(nbtentry); displayPC(pc); System.out.println(pc); } catch (IOException ex) { Logger.getLogger(NDBItemNBTENTRY.class.getName()).log(Level.SEVERE, null, ex); } } } @Override public String toString() { return nbtentry.toString(); } private void displayPC(PC pc) { Stage stage = new Stage(); stage.setTitle("PC Inspector:"); VBox root = new VBox(); TableView<PCItem> table = new TableView(); TableColumn<PCItem, String> propIdCol = new TableColumn("Prop. Id"); TableColumn<PCItem, String> propIdNameCol = new TableColumn("Prop. Name"); TableColumn<PCItem, String> propData = new TableColumn("Data"); TableColumn<PCItem, String> propType = new TableColumn("Type"); table.getColumns().addAll(propIdCol, propType, propIdNameCol, propData); ObservableList<PCItem> data = FXCollections.observableList(pc.items); propIdCol.setCellValueFactory(param -> { final PCItem pcItem = param.getValue(); return new SimpleStringProperty(String.format("0x%04X", pcItem.propertyIdentifier)); }); propIdNameCol.setCellValueFactory((TableColumn.CellDataFeatures<PCItem, String> param) -> { final PCItem pcItem = param.getValue(); PropertyTag propertyTag = getPropertyTagFromIdentifier(pcItem.propertyIdentifier, pcItem.getPropertyDataType()); return new SimpleStringProperty(propertyTag == null ? "" : propertyTag.toString()); }); propType.setCellValueFactory((TableColumn.CellDataFeatures<PCItem, String> param) -> { final PCItem pcItem = param.getValue(); return new SimpleStringProperty(pcItem.getPropertyDataType().toString()); }); propData.setCellValueFactory((TableColumn.CellDataFeatures<PCItem, String> param) -> { final PCItem pcItem = param.getValue(); String s; if (pcItem.getPropertyDataType() == PropertyDataType.PtypString) { s = pcItem.getString(); } else if (pcItem.getPropertyDataType() == PropertyDataType.PtypBoolean) { s = pcItem.getBoolean() ? "true" : "false"; } else if (pcItem.dataValue == null) { s = ""; } else { final int MAX_BYTES = 128; StringBuilder sb = new StringBuilder(); sb.append("["); sb.append(BaseEncoding.base16().withSeparator(",", 2).encode(pcItem.dataValue, 0, Math.min(pcItem.dataValue.length, MAX_BYTES))); sb.append("]"); s = sb.toString(); } return new SimpleStringProperty(s); }); table.setItems(data); VBox.setVgrow(table, Priority.ALWAYS); root.getChildren().add(table); stage.setScene(new Scene(root, 380, 250)); stage.show(); } }
package com.gtfs.dto; import java.io.Serializable; public class PrintRcptMstDto implements Serializable{ private Long insCompyId; private Long branchId; private Long tieupCompyId; private String prefix; private long receiptFrom; private Long receiptTo; public Long getInsCompyId() { return insCompyId; } public void setInsCompyId(Long insCompyId) { this.insCompyId = insCompyId; } public Long getBranchId() { return branchId; } public void setBranchId(Long branchId) { this.branchId = branchId; } public Long getTieupCompyId() { return tieupCompyId; } public void setTieupCompyId(Long tieupCompyId) { this.tieupCompyId = tieupCompyId; } public String getPrefix() { return prefix; } public void setPrefix(String prefix) { this.prefix = prefix; } public long getReceiptFrom() { return receiptFrom; } public void setReceiptFrom(long receiptFrom) { this.receiptFrom = receiptFrom; } public Long getReceiptTo() { return receiptTo; } public void setReceiptTo(Long receiptTo) { this.receiptTo = receiptTo; } }
package exercise_chpater10; public class testBuffer { public static void main(String[] args) { StringBuilder s = new StringBuilder(); s.append("Welcome to java"); s.insert(7, "a"); System.out.println(s); s.delete(7, 8); System.out.println(s); s.reverse(); System.out.println(s); s.setCharAt(4, 't'); System.out.println(s); } }
/** * Copyright 2013 Cloudera Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kitesdk.data.hbase.impl; import org.kitesdk.data.SchemaValidationException; import java.io.UnsupportedEncodingException; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * An EntitySchema is the parsed schema that contains the properties of an HBase * Common entity schema. */ public class EntitySchema { private final Collection<String> tables; private final Map<String, FieldMapping> fieldMappings = new HashMap<String, FieldMapping>(); private final String rawSchema; private final String name; /** * Constructs the EntitySchema * * @param tables * The tables this EntitySchema can be persisted to * @param name * The name of the entity schema * @param rawSchema * The raw schema type that underlies the EntitySchema implementation * @param fieldMappings * The list of FieldMappings that specify how each field maps to an * HBase row */ public EntitySchema(Collection<String> tables, String name, String rawSchema, Collection<FieldMapping> fieldMappings) { this.tables = tables; this.name = name; this.rawSchema = rawSchema; validateFieldMappings(fieldMappings); for (FieldMapping fieldMapping : fieldMappings) { this.fieldMappings.put(fieldMapping.getFieldName(), fieldMapping); } } /** * Get the tables this EntitySchema can be persisted to. * * @return The list of tables. */ public Collection<String> getTables() { return tables; } /** * Get the name of this EntitySchema * * @return The name */ public String getName() { return name; } /** * Get the FieldMapping for the specified fieldName. Returns null if one * doesn't exist. * * @param fieldName * The field name to get the FieldMapping for * @return The FieldMapping, or null if one doesn't exist fo rthe fieldName. */ public FieldMapping getFieldMapping(String fieldName) { return fieldMappings.get(fieldName); } /** * Get the FieldMappings for this schema. * * @return The collection of FieldMappings */ public Collection<FieldMapping> getFieldMappings() { return fieldMappings.values(); } /** * Get the raw schema that was parsed to create this schema. * * @return The raw scheam. */ public String getRawSchema() { return rawSchema; } /** * Get the HBase columns required by this schema. * * @return The set of columns */ public Set<String> getRequiredColumns() { Set<String> set = new HashSet<String>(); for (FieldMapping fieldMapping : fieldMappings.values()) { if (MappingType.COLUMN == fieldMapping.getMappingType() || MappingType.COUNTER == fieldMapping.getMappingType()) { set.add(fieldMapping.getMappingValue()); } else if (MappingType.KEY_AS_COLUMN == fieldMapping.getMappingType()) { String family = fieldMapping.getMappingValue().split(":", 1)[0]; family = family + ":"; set.add(family); } else if (MappingType.OCC_VERSION == fieldMapping.getMappingType()) { set.add(new String(Constants.SYS_COL_FAMILY) + ":" + new String(Constants.VERSION_CHECK_COL_QUALIFIER)); } } return set; } /** * Get the HBase column families required by this schema. * * @return The set of column families. */ public Set<String> getRequiredColumnFamilies() { Set<String> set = new HashSet<String>(); Set<String> columnSet = getRequiredColumns(); for (String column : columnSet) { set.add(column.split(":")[0]); } return set; } /** * Method meant to determine if two EntitySchemas are compatible with each * other for schema migration purposes. Classes that inherit EntitySchema * should override this implementation, since this implemetnation isn't able * to make that determination. * * TODO: Figure out a base set of properties that all entity schema * implementations should share in their implementation of determining * compatibility and execute that here. * * @param entitySchema * The other EntitySchema to determine compatible with * @return */ public boolean compatible(EntitySchema entitySchema) { // throw an exception if anyone calls this directly, as this should be // overridden in derived classes. throw new UnsupportedOperationException( "EntityScheam class can't determine if two entity schemas are compatible."); } /** * Validate that the field mappings provided for this schema are compatible * with a valid schema. The rules are: * * <pre> * 1. An entity schema can't contain multiple occVersion mapping fields * 2. An entity schema can't contain both an occVersion field and a counter * field. * </pre> * * This method will throw a SchemaValidationException if any of these * rules are violated. Otherwise, no exception is thrown. * * @param fieldMappings The collection of FieldMappings to validate */ private void validateFieldMappings(Collection<FieldMapping> fieldMappings) { boolean hasOCCVersion = false; boolean hasCounter = false; for (FieldMapping fieldMapping : fieldMappings) { if (fieldMapping.getMappingType() == MappingType.OCC_VERSION) { if (hasOCCVersion) { throw new SchemaValidationException( "Schema can't contain multiple occVersion fields."); } if (hasCounter) { throw new SchemaValidationException( "Schema can't contain both an occVersion field and a counter field."); } hasOCCVersion = true; } else if (fieldMapping.getMappingType() == MappingType.COUNTER) { if (hasOCCVersion) { throw new SchemaValidationException( "Schema can't contain both an occVersion field and a counter field."); } hasCounter = true; } } } /** * A field mapping represents a type that specifies how a schema field maps to * a column in HBase. */ public static class FieldMapping { private final String fieldName; private final MappingType mappingType; private final String mappingValue; private final Object defaultValue; private final String prefix; private final byte[] family; private final byte[] qualifier; public FieldMapping(String fieldName, MappingType mappingType, String mappingValue, Object defaultValue, String prefix) { this.fieldName = fieldName; this.mappingType = mappingType; this.mappingValue = mappingValue; this.defaultValue = defaultValue; this.prefix = prefix; this.family = getFamilyFromMappingValue(mappingValue); this.qualifier = getQualifierFromMappingValue(mappingValue); } public String getFieldName() { return fieldName; } public MappingType getMappingType() { return mappingType; } public String getMappingValue() { return mappingValue; } public Object getDefaultValue() { return defaultValue; } public String getPrefix() { return prefix; } public byte[] getFamily() { return family; } public byte[] getQualifier() { return qualifier; } private byte[] getFamilyFromMappingValue(String mappingValue) { if (mappingType == MappingType.KEY) { return null; } else if (mappingType == MappingType.OCC_VERSION) { return Constants.SYS_COL_FAMILY; } else { String[] familyQualifier = mappingValue.split(":", 2); byte[] family; try { family = familyQualifier[0].getBytes("UTF-8"); } catch (UnsupportedEncodingException exc) { throw new SchemaValidationException( "fieldType Must support UTF-8 encoding", exc); } return family; } } private byte[] getQualifierFromMappingValue(String mappingValue) { if (mappingType == MappingType.KEY) { return null; } else if (mappingType == MappingType.OCC_VERSION) { return Constants.VERSION_CHECK_COL_QUALIFIER; } else { String[] familyQualifier = mappingValue.split(":", 2); byte[] qualifier; try { qualifier = familyQualifier.length == 1 ? new byte[0] : familyQualifier[1].getBytes("UTF-8"); } catch (UnsupportedEncodingException exc) { throw new SchemaValidationException( "fieldType Must support UTF-8 encoding", exc); } return qualifier; } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((defaultValue == null) ? 0 : defaultValue.hashCode()); result = prime * result + Arrays.hashCode(family); result = prime * result + ((fieldName == null) ? 0 : fieldName.hashCode()); result = prime * result + ((mappingType == null) ? 0 : mappingType.hashCode()); result = prime * result + ((mappingValue == null) ? 0 : mappingValue.hashCode()); result = prime * result + ((prefix == null) ? 0 : prefix.hashCode()); result = prime * result + Arrays.hashCode(qualifier); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; FieldMapping other = (FieldMapping) obj; if (defaultValue == null) { if (other.defaultValue != null) return false; } else if (!defaultValue.equals(other.defaultValue)) return false; if (!Arrays.equals(family, other.family)) return false; if (fieldName == null) { if (other.fieldName != null) return false; } else if (!fieldName.equals(other.fieldName)) return false; if (mappingType != other.mappingType) return false; if (mappingValue == null) { if (other.mappingValue != null) return false; } else if (!mappingValue.equals(other.mappingValue)) return false; if (prefix == null) { if (other.prefix != null) return false; } else if (!prefix.equals(other.prefix)) return false; if (!Arrays.equals(qualifier, other.qualifier)) return false; return true; } } }
package api.longpoll.bots.methods.impl.messages; import api.longpoll.bots.http.params.BoolInt; import api.longpoll.bots.methods.AuthorizedVkApiMethod; import api.longpoll.bots.methods.VkApiProperties; import api.longpoll.bots.model.objects.basic.Conversation; import api.longpoll.bots.model.objects.basic.Message; import api.longpoll.bots.model.response.ExtendedVkList; import api.longpoll.bots.model.response.GenericResponse; import com.google.gson.annotations.SerializedName; import java.util.Arrays; import java.util.List; /** * Implements <b>messages.getConversationsById</b> method. * <p> * Returns conversations by their IDs. * * @see <a href="https://vk.com/dev/messages.getConversationsById">https://vk.com/dev/messages.getConversationsById</a> */ public class GetConversationsById extends AuthorizedVkApiMethod<GetConversationsById.Response> { public GetConversationsById(String accessToken) { super(accessToken); } @Override protected String getUrl() { return VkApiProperties.get("messages.getConversationsById"); } @Override protected Class<Response> getResponseType() { return Response.class; } public GetConversationsById setPeerIds(Integer... peerIds) { return setPeerIds(Arrays.asList(peerIds)); } public GetConversationsById setPeerIds(List<Integer> peerIds) { return addParam("peer_ids", peerIds); } public GetConversationsById setExtended(boolean extended) { return addParam("extended", new BoolInt(extended)); } public GetConversationsById setFields(String... fields) { return setFields(Arrays.asList(fields)); } public GetConversationsById setFields(List<String> fields) { return addParam("fields", fields); } public GetConversationsById setGroupId(int groupId) { return addParam("group_id", groupId); } @Override public GetConversationsById addParam(String key, Object value) { return (GetConversationsById) super.addParam(key, value); } /** * Response to <b>messages.getConversationsById</b> request. */ public static class Response extends GenericResponse<ExtendedVkList<Response.ResponseObject.Item>> { /** * Response object. */ public static class ResponseObject extends ExtendedVkList<ResponseObject.Item> { /** * Number of unread conversations. */ @SerializedName("unread_count") private Integer unreadCount; /** * Describes VkList item. */ public static class Item { /** * Conversation object. */ @SerializedName("conversation") private Conversation conversation; /** * Last message in conversation. */ @SerializedName("last_message") private Message message; public Conversation getConversation() { return conversation; } public void setConversation(Conversation conversation) { this.conversation = conversation; } public Message getMessage() { return message; } public void setMessage(Message message) { this.message = message; } @Override public String toString() { return "Item{" + "conversation=" + conversation + ", message=" + message + '}'; } } public Integer getUnreadCount() { return unreadCount; } public void setUnreadCount(Integer unreadCount) { this.unreadCount = unreadCount; } @Override public String toString() { return "ResponseObject{" + "unreadCount=" + unreadCount + "} " + super.toString(); } } } }
package com.ido.zcsd.config; import com.ido.zcsd.exception.CustomException; import com.rainful.domain.ResponseDTO; import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; /** * 异常返回格式 {code:1000,msg:参数不正确} * * @author liliang * @description: * @datetime 18/2/1 下午1:09 */ @ControllerAdvice @Slf4j public class ControllerExceptionHandler { @ExceptionHandler(Exception.class) @ResponseBody @ResponseStatus(HttpStatus.OK) public ResponseDTO handlerServiceOpException(RuntimeException ex) { return ResponseDTO.fail(null,ex.getMessage()); } @ExceptionHandler(CustomException.class) @ResponseBody @ResponseStatus(HttpStatus.OK) public ResponseDTO handlerCustompException(CustomException ex) { ResponseDTO responseDTO = ResponseDTO.fail(null,ex.getMessage()); responseDTO.setCode(ex.getCode()); return responseDTO; } }
package com.VO; public class positionVO { private double latitude;//À§µµ private double longitude;//°æµµ public positionVO(double latitude, double longitude) { super(); this.latitude = latitude; this.longitude = longitude; } public double getLatitude() { return latitude; } public double getLongitude() { return longitude; } }
package cas.se3xa3.bitsplease.model.generator; import cas.se3xa3.bitsplease.model.Board; import cas.se3xa3.bitsplease.model.checker.BoardChecker; import cas.se3xa3.bitsplease.model.checker.Result; import cas.se3xa3.bitsplease.model.solver.BoardSolver; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.util.Collection; import java.util.stream.Collectors; import java.util.stream.IntStream; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** * Created on 16/11/2015. */ @RunWith(Parameterized.class) public class BoardGeneratorFunctionalTest { private int size; private BoardGenerator generator; public BoardGeneratorFunctionalTest(int size) { this.size = size; generator = new BoardGenerator(); } @Parameterized.Parameters public static Collection<Integer[]> getTestData() { return IntStream.range(4, 13) .filter(size -> size % 2 == 0) .boxed() .map(size -> new Integer[]{size}) .collect(Collectors.toList()); } @Test public void testGenerate() throws Exception { System.out.printf("Testing size %d\n", size); Board board = generator.generate(size); assertEquals("Generated board should be of size "+size+" but was "+board.getSize(), size, board.getSize()); BoardChecker checker = new BoardChecker(board); assertEquals("Generated board is not valid.", checker.isValid().getResultState(), Result.State.SATISFIES); BoardSolver solver = new BoardSolver(board); assertTrue("Solver could not solve the generated board.", solver.tryToSolve()); } }
package com.aslansari.rxjavastatemng.ui; import com.aslansari.rxjavastatemng.network.models.User; public final class SubmitResult { public boolean inProgress; public boolean success; public boolean error; public String errorMessage; public User user; public static final int IN_FLIGHT = 1; public static final int SUCCESS = 2; private SubmitResult(boolean inProgress, boolean success, boolean error,String errorMessage) { this.inProgress = inProgress; this.success = success; this.error = error; this.errorMessage = errorMessage; } private SubmitResult(boolean inProgress, boolean success, boolean error,String errorMessage,User user) { this.inProgress = inProgress; this.success = success; this.error = error; this.errorMessage = errorMessage; this.user = user; } public static SubmitResult idle(){ return new SubmitResult(false,false,false,""); } public static SubmitResult inProgress(){ return new SubmitResult(true,false, false,""); } public static SubmitResult success(User user){ return new SubmitResult(false,true, false,"",user); } public static SubmitResult failure(String errorMessage){ return new SubmitResult(false,false, true, errorMessage); } }
package io.bega.kduino.fragments; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import io.bega.kduino.R; import io.bega.kduino.fragments.intro.PlaceSlideFragment; import io.bega.kduino.fragments.intro.PlaceTextSlideFragment; public class IntroductionTextFragmentPageAdapter extends FragmentPagerAdapter { private int count; /** * Constructor * * @param fm * interface for interacting with Fragment objects inside of an * Activity */ public IntroductionTextFragmentPageAdapter(FragmentManager fm, int max) { super(fm); count = max; } @Override public Fragment getItem(int arg0) { return PlaceTextSlideFragment.newInstance(arg0); } @Override public int getCount() { return count; } }
package com.travel.services; import com.travel.models.Location; import java.util.Date; import java.util.List; import java.util.Optional; import java.util.Set; public interface LocationService { void save(Location location); List<Location> findAll(); Optional<Location> findById(Long id); Set<Location> findByCity(String city); Set<Location> findByCountry(String country); Set<Location> findByIsDevBridge(boolean isDevBridge); Integer isAvailable(Long locationId, Date from, Date to); }
public class GenericStack<I> extends GenericList<I> { //constructor for the class GenericStack(I data) { super(data); //because of the constructor it inherited //also to create initialize the list } @Override void add(I data) { //create a new node for the queue GenericList<I>.Node<I> newNode = new GenericList<I>.Node<I>(data); if(getLength() == 0) { setHead(newNode); } //adds on to the stack else if(getLength() > 0) { newNode.next = getHead(); //moves the original head to be after the new node in place setHead(newNode); //creates the new head of the list } setLength(getLength() + 1); //increments the length of the stack } //pushes data onto the stack public void push(I data) { add(data); } //pops data off the stack public I pop() { return delete(); } }
package workshop1.dao; import static org.junit.jupiter.api.Assertions.*; import java.util.List; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import workshop1.domain.Address; import workshop1.domain.AddressType; import workshop1.domain.Customer; import workshop1.util.Database; class AddressDaoTest { AddressDao addressDao; CustomerDao customerDao; @BeforeEach void setUp() throws Exception { addressDao = new AddressDao(); customerDao = new CustomerDao(); Database.prepareForUnitTest(); } @AfterEach void tearDown() throws Exception { } @Test void testGetAddress() { Customer customer = customerDao.getCustomer(1); Address expectedAddress = new Address("Dorpsstraat", 20, "rood", "1234GH", "Het Dorp", customer, AddressType.POSTADRES); Address resultingAddress = addressDao.getAddress(1); assertEquals(expectedAddress, resultingAddress); } @Test void testGetAllAddresses() { Customer customer = customerDao.getCustomer(1); Address expectedAddress = new Address("Dorpsstraat", 20, "rood", "1234GH", "Het Dorp", customer, AddressType.POSTADRES); List<Address> addresses = addressDao.getAllAddresses(); assertEquals(3, addresses.size()); assertEquals(expectedAddress, addresses.get(0)); } @Test void testGetAllAddressesFromCustomer() { Customer customer = customerDao.getCustomer(1); List<Address> addressesCustomer = addressDao.getAllAddressesFromCustomer(1); List<Address> addresses = addressDao.getAllAddresses(); assertEquals(2, addressesCustomer.size()); assertEquals(3, addresses.size()); } @Test void testCreateAddress() { Customer customer = customerDao.getCustomer(1); Address address = new Address("Teststraat", 50, "blauw", "7623GH", "Het Dorp", customer, AddressType.BEZORGADRES); int insertedId = addressDao.createAddress(address); Address resultingAddress = addressDao.getAddress(insertedId); assertEquals(address, resultingAddress); } @Test void testUpdateAddress() { Address address = addressDao.getAddress(1); address.setPostalCode("9999YY"); Boolean result = addressDao.updateAddress(address); assertEquals(true, result); Address resultingAddress = addressDao.getAddress(1); assertEquals(address, resultingAddress); } @Test void testDeleteAddressInteger() { List<Address> addresses = addressDao.getAllAddresses(); int count = addresses.size(); Boolean result = addressDao.deleteAddress(1); assertEquals(true, result); addresses = addressDao.getAllAddresses(); assertEquals(count - 1, addresses.size()); } }
import processing.core.PApplet; import javax.swing.*; public class Main extends PApplet { static int n; float x[]; float y[]; float dx[]; float dy[]; float r; float vis[]; public void settings() { fullScreen(); } public void setup() { noStroke(); x = new float[n]; y = new float[n]; dx = new float[n]; dy = new float[n]; r = 40; vis = new float[n]; for(int i = 0; i < x.length; i ++) { x[i] = r * (i+1) / (float)Math.sqrt(2.0); y[i] = r * (i+1) / (float)Math.sqrt(2.0); dx[i] = 3; dy[i] = 3; vis[i] += (i+1) * 255.0/x.length; } } public void draw() { background(0); for (int i = 0; i < x.length; i++) { drawing(x[i],y[i],r, 0, 0, 255, vis[i]); x[i] += dx[i]; y[i] += dy[i]; } for (int i = 0; i < x.length; ++i) { if (x[i] < 0) { x[i] = -x[i]; dx[i] = -dx[i]; } if (x[i] > width) { x[i] = width * 2 - x[i]; dx[i] = -dx[i]; } if (y[i] < 0) { y[i] = -y[i]; dy[i] = -dy[i]; } if (y[i] > height) { y[i] = height * 2 - y[i]; dy[i] = -dy[i]; } } } public void drawing(float x,float y, float r, int red, int g, int b, float vis) { fill(red, g, b, vis); ellipse(x, y, r, r); } public static void main(String... args) { n = Integer.parseInt(JOptionPane.showInputDialog("N: ")); PApplet.main("Main"); } }
package com.tencent.mm.modelstat.a; import android.os.Bundle; public interface a { void k(Bundle bundle); }
package com.game.kafka; import com.game.entity.Player; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.kafka.core.KafkaTemplate; import org.springframework.stereotype.Service; import java.util.concurrent.ExecutionException; @Service public final class ProducerService { private static final Logger logger = LoggerFactory.getLogger(ProducerService.class); private final KafkaTemplate<String, Long> kafkaTemplate; @Value("${kafka.produce.topic}") private String topic; public ProducerService(KafkaTemplate<String, Long> kafkaTemplate) { this.kafkaTemplate = kafkaTemplate; } public void sendMessage(Long message) throws ExecutionException { try { this.kafkaTemplate.send(topic, message).get(); } catch (InterruptedException e) { Player.STATUS="IDLE"; } } }
package com.forsrc.cxf.server.demo; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebService; /** * The interface Hello world. */ @WebService public interface HelloWorld { /** * Echo string. * * @param text the text * @return the string */ @WebMethod public String echo(@WebParam(name = "text") String text); }
package eventi; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import eccezioni.ParametroIllegaleException; @WebServlet("/MostraUltimoEventoInserito") public class MostraUltimoEventoInserito extends HttpServlet{ private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req,resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { Evento ultimoEventoInserito= new EventoDAO().mostraUltimoEventoInserito(); req.setAttribute("ultimoEventoInserito", ultimoEventoInserito); req.getRequestDispatcher("ultimoEventoInseritoHomePage.jsp").forward(req,resp); return; } catch (ParametroIllegaleException e) { req.setAttribute("ultimoEventoInserito", null); req.getRequestDispatcher("ultimoEventoInseritoHomePage.jsp").forward(req,resp); return; } } }
package com.zjc.netty.buf; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; /** * @author : zoujianchao * @version : 1.0 * @date : 2021/7/10 * @description : */ public class NettyByteBuf01 { public static void main(String[] args) { //创建一个ByteBuf /** * 1.创建一个对象,该对象包含一个数组arr.是一个byte[10] * 2.在netty的buffer中,不需要使用flip进行反转,底层维护了 readerIndex和writerIndex * 3.通过 readerIndex和writerIndex和capacity ,将buffer分为三个区域 * 0-readerIndex:已经读取的区域 * readerIndex-writerIndex:可读区域 * writerIndex-capacity:可写区域 */ ByteBuf buffer = Unpooled.buffer(10); for (int i = 0; i < 10; i++) { buffer.writeByte(i); } // for (int i = 0; i < buffer.capacity(); i++) { // System.out.println(buffer.getByte(i)); // } for (int i = 0; i < buffer.capacity(); i++) { System.out.println(buffer.readByte()); } } }
package com.example.demo.domain.po; import com.example.demo.domain.Vendor; import org.springframework.stereotype.Service; @Service public interface DateBaseMapper { Vendor getOne(String vendor1); }
package com.jack.rookietest.controller; import com.alibaba.fastjson.JSONObject; import com.jack.common.rest.Result; import com.jack.common.util.ResultUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * @author jack * @Classname TestController * Create by jack 2019/11/29 * @date: 2019/11/29 22:35 * @Description: */ @RestController @RequestMapping("test") public class TestController { @RequestMapping("test1") public Result test1(){ JSONObject json = new JSONObject(); json.put("name","jack"); json.put("age","18"); return ResultUtils.success(json); } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ejb.session.stateless; import entity.Employee; import javax.ejb.Local; import util.exception.EmployeeExistException; import util.exception.EmployeeNotFoundException; import util.exception.GeneralException; import util.exception.InvalidLoginCredentialException; /** * * @author Administrator */ @Local public interface EmployeeSessionBeanLocal { public Employee createNewEmployee(Employee employee) throws EmployeeExistException, GeneralException; public Employee employeeLogin(String username, String password) throws EmployeeNotFoundException, InvalidLoginCredentialException; public Employee retrieveEmployeeByUsername(String username) throws EmployeeNotFoundException; }
package swexpert; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; public class SWEA_1221_D3_GNS { public static String[] number = {"ZRO", "ONE", "TWO", "THR", "FOR", "FIV", "SIX", "SVN", "EGT", "NIN"}; public static ArrayList<String> num = new ArrayList<>(Arrays.asList(number)); public static void main(String[] args) throws IOException { // TODO Auto-generated method stub BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb = new StringBuilder(); StringTokenizer st; int TC = Integer.parseInt(br.readLine()); for (int i = 1; i <= TC; i++) { sb.append("#").append(i).append(" "); st = new StringTokenizer(br.readLine()); String N = st.nextToken(); int M = Integer.parseInt(st.nextToken()); int[] arr = new int[M]; st = new StringTokenizer(br.readLine()); for (int j = 0; j < M; j++) { String tmp = st.nextToken(); arr[j] = num.indexOf(tmp); } Arrays.sort(arr); for (int j = 0; j < M; j++) { sb.append(num.get(arr[j])).append(" "); } sb.append("\n"); } System.out.println(sb); } }
package net.minecraft.item; import net.minecraft.block.Block; public class ItemMultiTexture extends ItemBlock { protected final Block theBlock; protected final Mapper nameFunction; public ItemMultiTexture(Block p_i47262_1_, Block p_i47262_2_, Mapper p_i47262_3_) { super(p_i47262_1_); this.theBlock = p_i47262_2_; this.nameFunction = p_i47262_3_; setMaxDamage(0); setHasSubtypes(true); } public ItemMultiTexture(Block block, Block block2, String[] namesByMeta) { this(block, block2, new Mapper(namesByMeta) { public String apply(ItemStack p_apply_1_) { int i = p_apply_1_.getMetadata(); if (i < 0 || i >= namesByMeta.length) i = 0; return namesByMeta[i]; } }); } public int getMetadata(int damage) { return damage; } public String getUnlocalizedName(ItemStack stack) { return String.valueOf(getUnlocalizedName()) + "." + this.nameFunction.apply(stack); } public static interface Mapper { String apply(ItemStack param1ItemStack); } } /* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\net\minecraft\item\ItemMultiTexture.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
package com.hqhcn.android.entity; public class Ksxm { private String code; private String name; private String upCode; private String kfz; private String kskm; private Short zdpdx; private String code61; private Integer zt; public String getCode() { return code; } public void setCode(String code) { this.code = code == null ? null : code.trim(); } public String getName() { return name; } public void setName(String name) { this.name = name == null ? null : name.trim(); } public String getUpCode() { return upCode; } public void setUpCode(String upCode) { this.upCode = upCode == null ? null : upCode.trim(); } public String getKfz() { return kfz; } public void setKfz(String kfz) { this.kfz = kfz == null ? null : kfz.trim(); } public String getKskm() { return kskm; } public void setKskm(String kskm) { this.kskm = kskm == null ? null : kskm.trim(); } public Short getZdpdx() { return zdpdx; } public void setZdpdx(Short zdpdx) { this.zdpdx = zdpdx; } public String getCode61() { return code61; } public void setCode61(String code61) { this.code61 = code61 == null ? null : code61.trim(); } public Integer getZt() { return zt; } public void setZt(Integer zt) { this.zt = zt; } }
package com.example.dell.sixlive.View.Fragment; import android.annotation.SuppressLint; import android.os.Build; import android.os.Handler; import android.support.annotation.RequiresApi; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import com.example.dell.sixlive.Adater.SpecialAdapter; import com.example.dell.sixlive.Bean.ChoicenessBean; import com.example.dell.sixlive.Bean.LoadurlBean; import com.example.dell.sixlive.Bean.WelfareBean; import com.example.dell.sixlive.Persenter.SpecialPresenter; import com.example.dell.sixlive.R; import com.example.dell.sixlive.View.IView; import com.example.dell.sixlive.rewrite.GridSpacingItemDecoration; import java.util.List; import butterknife.Unbinder; /** * Created by DELL on 2018/7/6. */ public class Special extends BaseHot<SpecialPresenter> implements IView { Unbinder unbinder; private RecyclerView rc; int spanCount = 2; int spacing = 15; boolean includeEdge = true; private SwipeRefreshLayout sw; private SpecialAdapter specialAdapter; @Override protected void initView(View inflate) { rc = inflate.findViewById(R.id.special_rec); sw = inflate.findViewById(R.id.special_swipe); //下拉加载 sw.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override public void onRefresh() { new Handler().postDelayed(new Runnable() { @Override public void run() { presenter.specials(); specialAdapter.notifyDataSetChanged(); sw.setRefreshing(false); } },1200); } }); } @Override protected int bindLayout() { return R.layout.special; } @SuppressLint("NewApi") @Override protected void initData() { //P层交互 presenter.specials(); } @Override protected void bindEvent() { } @Override protected SpecialPresenter setPresenter() { return new SpecialPresenter(); } @Override public void onDestroyView() { super.onDestroyView(); unbinder.unbind(); } @Override public void getPecial(ChoicenessBean bean) { List<ChoicenessBean.RetBean.ListBean> list = bean.getRet().getList(); specialAdapter = new SpecialAdapter(list, getActivity()); rc.addItemDecoration(new GridSpacingItemDecoration(spanCount, spacing, includeEdge)); GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 2); rc.setLayoutManager(gridLayoutManager); rc.setAdapter(specialAdapter); } @Override public void fail(String s) { } @Override public void chenggong(ChoicenessBean bean) { } @Override public void shibai(String msg) { } @Override public void chenggongurl(LoadurlBean bean) { } @Override public void shibaiurl(String msg) { } @Override public void chenggongwelf(WelfareBean bean) { } @Override public void shibaiwelf(String msg) { } }
package com.lc.exstreetseller.activity; import android.os.Bundle; import android.view.View; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import com.lc.exstreetseller.R; import com.lc.exstreetseller.adapter.SettleAdapter; import com.lc.exstreetseller.base.BaseActivity; import com.lc.exstreetseller.bean.SettleBean; import com.lc.exstreetseller.util.HeightUtil; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.OnClick; public class SettleActivity extends BaseActivity { @BindView(R.id.lv_settle) ListView lv; @BindView(R.id.tv_settle_total_amount) TextView totalAmountTv; @BindView(R.id.iv_settle_normal_choice) ImageView normalChoiceIv; @BindView(R.id.tv_settle_normal_price) TextView normalPriceTv; @BindView(R.id.iv_settle_vip_choice) ImageView vipChoiceIv; @BindView(R.id.tv_settle_vip_price) TextView vipPriceTv; private int curPosition = -1; private List<SettleBean> list; private SettleAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_settle); initView(); } private void initView() { setETitle("结算"); loadData(); } private void loadData() { list = new ArrayList<>(); adapter = new SettleAdapter(this, list); adapter.setOnSettleListener(new SettleAdapter.OnSettleListener() { @Override public void onAdd(SettleBean bean) { showToast("+"); } @Override public void onReduce(SettleBean bean) { showToast("-"); } }); lv.setAdapter(adapter); for (int i = 0; i < 10; i++) { list.add(new SettleBean()); } adapter.notifyDataSetChanged(); HeightUtil.setLvHeight(lv); totalAmountTv.setText("共40件商品"); normalPriceTv.setText("¥400.00"); vipPriceTv.setText("¥360.00"); select(0); } private void select(int tarPosition) { if (tarPosition != curPosition) { switch (tarPosition) { case 0: normalChoiceIv.setImageResource(R.mipmap.xz_2); vipChoiceIv.setImageResource(R.mipmap.xz_01); break; case 1: normalChoiceIv.setImageResource(R.mipmap.xz_01); vipChoiceIv.setImageResource(R.mipmap.xz_2); break; default: break; } curPosition = tarPosition; } } @OnClick({R.id.rl_settle_normal, R.id.rl_settle_vip}) public void click(View v) { switch (v.getId()) { case R.id.rl_settle_normal: select(0); break; case R.id.rl_settle_vip: select(1); break; default: break; } } }
package org.alienideology.jcord.handle.client.call; import org.alienideology.jcord.handle.client.IClientObject; import org.alienideology.jcord.handle.user.IUser; /** * ICallUser - A temporary instance representing an user in a call. * * @author AlienIdeology */ public interface ICallUser extends IClientObject { default IUser getUser() { return getVoiceState().getUser(); } ICall getCall(); ICallVoiceState getVoiceState(); }
package animatronics.utils.helper; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.tileentity.TileEntity; public class NBTHelper{ /** * Used for null-safety * * @param stack */ public static NBTTagCompound checkNBT(ItemStack stack){ if(stack.stackTagCompound == null){ stack.stackTagCompound = new NBTTagCompound(); } return stack.stackTagCompound; } /** * Shortcut for NBTTagCompound.hasKey() */ public static boolean verifyKey(ItemStack stack, String name){ return stack.stackTagCompound.hasKey(name); } public static void setInteger(ItemStack stack, String name, int value){ stack.stackTagCompound.setInteger(name, value); } public static int getInteger(ItemStack stack, String name){ return stack.stackTagCompound.getInteger(name); } public static void decreaseInteger(ItemStack stack, String name, int value){ if(getInteger(stack, name) > 0){ setInteger(stack, name, getInteger(stack, name) - value); } } public static void decreaseIntegerIgnoreZero(ItemStack stack, String name, int value){ setInteger(stack, name, getInteger(stack, name) - value); } public static void setString(ItemStack stack, String name, String value){ stack.stackTagCompound.setString(name, value); } public static String getString(ItemStack stack, String name){ return stack.stackTagCompound.getString(name); } public static void setBoolean(ItemStack stack, String name, boolean value){ stack.stackTagCompound.setBoolean(name, value); } public static boolean getBoolean(ItemStack stack, String name){ return stack.stackTagCompound.getBoolean(name); } public static void invertBoolean(ItemStack stack, String name){ setBoolean(stack, name, !getBoolean(stack, name)); } public static void setByte(ItemStack stack, String name, byte value){ stack.stackTagCompound.setByte(name, value); } public static byte getByte(ItemStack stack, String name){ if(!verifyKey(stack, name)){ setByte(stack, name, (byte)0); } return stack.stackTagCompound.getByte(name); } /*-----------------------------------------------------------------------------------*/ /** * @param stack - the ItemStack to work with. */ public static void createNBTTag(ItemStack stack) { if(stack.hasTagCompound()) { return; } NBTTagCompound itemTag = new NBTTagCompound(); stack.setTagCompound(itemTag); } /** * @param stack - the ItemStack to work with. * @return NBTTagCompound of the ItemStack */ public static NBTTagCompound getStackTag(ItemStack stack) { createNBTTag(stack); return stack.getTagCompound(); } /** * @param t - the TileEntity * @param saveTag - the tag */ public static void saveInventory(TileEntity t, NBTTagCompound saveTag) { if(t instanceof IInventory) { IInventory tile = (IInventory) t; NBTTagList nbttaglist = new NBTTagList(); for (int i = 0; i < tile.getSizeInventory(); ++i) { if (tile.getStackInSlot(i) != null) { NBTTagCompound nbttagcompound1 = new NBTTagCompound(); nbttagcompound1.setByte("Slot", (byte)i); tile.getStackInSlot(i).writeToNBT(nbttagcompound1); nbttaglist.appendTag(nbttagcompound1); } } saveTag.setTag("Items", nbttaglist); } } /** * @param t - the TileEntity * @param loadTag - the tag */ public static void loadInventory(TileEntity t, NBTTagCompound loadTag) { if(t instanceof IInventory) { IInventory tile = (IInventory) t; for(int i = 0; i < tile.getSizeInventory(); ++i) { tile.setInventorySlotContents(i, null); } NBTTagList nbttaglist = loadTag.getTagList("Items", 10); for (int i = 0; i < nbttaglist.tagCount(); ++i) { NBTTagCompound nbttagcompound1 = nbttaglist.getCompoundTagAt(i); byte b0 = nbttagcompound1.getByte("Slot"); if (b0 >= 0 && b0 < tile.getSizeInventory()) { tile.setInventorySlotContents(b0, ItemStack.loadItemStackFromNBT(nbttagcompound1)); } } } } }
import java.util.*; class Flight { String from, to, daySum; LinkedList<String> days = new LinkedList<String>(); LinkedList<String> flightNum = new LinkedList<String>(); LinkedList<String> depTime = new LinkedList<String>(); LinkedList<String> arrTime = new LinkedList<String>(); Flight(String f, String t, LinkedList<String> fn, LinkedList<String> dt, LinkedList<String> at, LinkedList<String> d, String ds){ from = f; to = t; flightNum = fn; depTime = dt; arrTime = at; days = d; daySum = ds; } } public class Trab3{ public static boolean vis[] = new boolean[5], graph[][] = new boolean[5][5], first = true, AllFlightsAdded; public static HashMap<String, Integer> index = new HashMap<>(); public static HashMap<Integer, String> stringIndex = new HashMap<>(); public static LinkedList<String> FlightNumbers = new LinkedList<String>(); public static LinkedList<String> DepTimes = new LinkedList<String>(); public static Flight flights[] = new Flight[12]; public static int k = 1, previousFlight; public static int[] path = {-1,-1,-1,-1,-1,-1,-1,-1,-1}; public static HashSet<String> s1CharSet = new HashSet<String>(), s2CharSet = new HashSet<String>(); public static String daysAvailable = ""; static boolean transferTime(String t1, String t2){ int h1, h2, min1, min2, diffMins; String[] temp1, temp2; temp1 = t1.split(":"); temp2 = t2.split(":"); h1 = Integer.parseInt(temp1[0]); min1 = Integer.parseInt(temp1[1]); h2 = Integer.parseInt(temp2[0]); min2 = Integer.parseInt(temp2[1]); if(h1 < h2){ diffMins = (h2-h1) * 60 + (min2 - min1); } else { diffMins = ((h2+24) - h1) * 60 + (min2 - min1); } if(diffMins >= 40) return true; return false; } static void dfs(int from, int to){ int targetDest, flightFound = -1; vis[from] = true; for(int i = 0; i < 5; i++){ if(graph[from][i] && !vis[i]){ if(graph[from][to]) targetDest = to; else targetDest = i; for(int j = 0; j < flights.length; j++){ if(flights[j].from.equals(stringIndex.get(from)) && flights[j].to.equals(stringIndex.get(targetDest))) { flightFound = j; break; } } // If a flight was found if(flightFound != -1){ int indexOfList = -1; // Check for intersecting days if(!AllFlightsAdded && !first){ String string1 = flights[flightFound].daySum; String string2 = flights[previousFlight].daySum; String[] s1 = string1.split(","); String[] s2 = string2.split(","); for(String day: s1) s1CharSet.add(day); for(String day: s2) s2CharSet.add(day); s1CharSet.retainAll(s2CharSet); } if(!first) daysAvailable = Arrays.toString(s1CharSet.toArray(new String[s1CharSet.size()])); else daysAvailable = flights[flightFound].daySum; // Find index of flight number for(int k = 0; k < flights[flightFound].flightNum.size(); k++) { for(String day: flights[flightFound].days.get(k).split(",")){ if(daysAvailable.contains(day)){ indexOfList = k; break; } } } // If there are intersecting days if(s1CharSet.size() != 0 || first){ if(graph[from][to]) { path[k++] = to; if(!AllFlightsAdded) { FlightNumbers.add(flights[flightFound].flightNum.get(indexOfList)); if(first || transferTime(DepTimes.getLast(), flights[flightFound].depTime.get(indexOfList))){ DepTimes.add(flights[flightFound].depTime.get(indexOfList)); } } AllFlightsAdded = true; return; } if(indexOfList != -1){ previousFlight = flightFound; if(!AllFlightsAdded) { FlightNumbers.add(flights[flightFound].flightNum.get(indexOfList)); if(first || transferTime(DepTimes.getLast(), flights[flightFound].depTime.get(indexOfList))){ DepTimes.add(flights[flightFound].depTime.get(indexOfList)); } } first = false; path[k++] = i; if(i == to) return; dfs(i, to); } } } } } } static void CreateFlights(){ LinkedList<String> flightNum = new LinkedList<String>(); LinkedList<String> arrTime = new LinkedList<String>(); LinkedList<String> depTime = new LinkedList<String>(); LinkedList<String> days = new LinkedList<String>(); String daySum; flightNum.add("ba4733"); flightNum.add("ba4733"); flightNum.add("ba4833"); depTime.add("9:40"); depTime.add("13:40"); depTime.add("19:40"); arrTime.add("10:50"); arrTime.add("14:50"); arrTime.add("20:50"); days.add("mo"); days.add("tu"); days.add("mo,tu"); daySum = "mo,tu,we,th,fr,sa,su"; flights[0] = new Flight("edinburgh", "london", flightNum, depTime, arrTime, days, daySum); flightNum = new LinkedList<String>(); arrTime = new LinkedList<String>(); depTime = new LinkedList<String>(); days = new LinkedList<String>(); flightNum.add("ju201"); flightNum.add("ju213"); depTime.add("13:20"); depTime.add("13:20"); arrTime.add("16:20"); arrTime.add("16:20"); days.add("fr"); days.add("su"); daySum = "fr,su"; flights[1] = new Flight("london", "ljubljana", flightNum, depTime, arrTime, days, daySum); flightNum = new LinkedList<String>(); arrTime = new LinkedList<String>(); depTime = new LinkedList<String>(); days = new LinkedList<String>(); flightNum.add("az458"); flightNum.add("ba511"); depTime.add("9:10"); depTime.add("12:20"); arrTime.add("10:00"); arrTime.add("13:10"); days.add("mo,tu,we,th,fr,sa,su"); days.add("mo,tu,we,th,fr,sa,su"); daySum = "mo,tu,we,th,fr,sa,su"; flights[2] = new Flight("milan", "london", flightNum, depTime, arrTime, days, daySum); flightNum = new LinkedList<String>(); arrTime = new LinkedList<String>(); depTime = new LinkedList<String>(); days = new LinkedList<String>(); flightNum.add("sr621"); flightNum.add("sr623"); depTime.add("9:25"); depTime.add("12:45"); arrTime.add("10:15"); arrTime.add("13:35"); days.add("mo,tu,we,th,fr,sa,su"); days.add("mo,tu,we,th,fr,sa,su"); daySum = "mo,tu,we,th,fr,sa,su"; flights[3] = new Flight("milan", "zurich", flightNum, depTime, arrTime, days, daySum); flightNum = new LinkedList<String>(); arrTime = new LinkedList<String>(); depTime = new LinkedList<String>(); days = new LinkedList<String>(); flightNum.add("ba613"); flightNum.add("sr806"); depTime.add("9:00"); depTime.add("16:10"); arrTime.add("9:40"); arrTime.add("16:55"); days.add("mo,tu,we,th,fr,sa"); days.add("mo,tu,we,th,fr,su"); daySum = "mo,tu,we,th,fr,sa,su"; flights[4] = new Flight("zurich", "london", flightNum, depTime, arrTime, days, daySum); flightNum = new LinkedList<String>(); arrTime = new LinkedList<String>(); depTime = new LinkedList<String>(); days = new LinkedList<String>(); flightNum.add("ba4732"); flightNum.add("ba4752"); flightNum.add("ba4822"); depTime.add("9:40"); depTime.add("11:40"); depTime.add("18:40"); arrTime.add("10:50"); arrTime.add("12:50"); arrTime.add("19:50"); days.add("mo,tu,we,th,fr,sa,su"); days.add("mo,tu,we,th,fr,sa,su"); days.add("mo,tu,we,th,fr"); daySum = "mo,tu,we,th,fr,sa,su"; flights[5] = new Flight("london", "edinburgh", flightNum, depTime, arrTime, days, daySum); flightNum = new LinkedList<String>(); arrTime = new LinkedList<String>(); depTime = new LinkedList<String>(); days = new LinkedList<String>(); flightNum.add("ba614"); flightNum.add("sr805"); depTime.add("9:10"); depTime.add("14:45"); arrTime.add("11:45"); arrTime.add("17:20"); days.add("mo,tu,we,th,fr,sa,su"); days.add("mo,tu,we,th,fr,sa,su"); daySum = "mo,tu,we,th,fr,sa,su"; flights[6] = new Flight("london", "zurich", flightNum, depTime, arrTime, days, daySum); flightNum = new LinkedList<String>(); arrTime = new LinkedList<String>(); depTime = new LinkedList<String>(); days = new LinkedList<String>(); flightNum.add("ba510"); flightNum.add("az459"); depTime.add("8:30"); depTime.add("11:00"); arrTime.add("11:20"); arrTime.add("13:50"); days.add("mo,tu,we,th,fr,sa,su"); days.add("mo,tu,we,th,fr,sa,su"); daySum = "mo,tu,we,th,fr,sa,su"; flights[7] = new Flight("london", "milan", flightNum, depTime, arrTime, days, daySum); flightNum = new LinkedList<String>(); arrTime = new LinkedList<String>(); depTime = new LinkedList<String>(); days = new LinkedList<String>(); flightNum.add("ju322"); depTime.add("11:30"); arrTime.add("12:40"); days.add("tu,th"); daySum = "tu,th"; flights[8] = new Flight("ljubljana", "zurich", flightNum, depTime, arrTime, days, daySum); flightNum = new LinkedList<String>(); arrTime = new LinkedList<String>(); depTime = new LinkedList<String>(); days = new LinkedList<String>(); flightNum.add("yu200"); flightNum.add("yu212"); depTime.add("11:10"); depTime.add("11:25"); arrTime.add("12:20"); arrTime.add("12:20"); days.add("fr"); days.add("su"); daySum = "fr,su"; flights[9] = new Flight("ljubljana", "london", flightNum, depTime, arrTime, days, daySum); flightNum = new LinkedList<String>(); arrTime = new LinkedList<String>(); depTime = new LinkedList<String>(); days = new LinkedList<String>(); flightNum.add("yu323"); depTime.add("13:30"); arrTime.add("14:40"); days.add("tu,th"); daySum = "tu,th"; flights[10] = new Flight("zurich", "ljubljana", flightNum, depTime, arrTime, days, daySum); flightNum = new LinkedList<String>(); arrTime = new LinkedList<String>(); depTime = new LinkedList<String>(); days = new LinkedList<String>(); flightNum.add("sr620"); depTime.add("7:55"); arrTime.add("8:45"); days.add("mo,tu,we,th,fr,sa,su"); daySum = "mo,tu,we,th,fr,sa,su"; flights[11] = new Flight("zurich", "milan", flightNum, depTime, arrTime, days, daySum); flightNum = new LinkedList<String>(); arrTime = new LinkedList<String>(); depTime = new LinkedList<String>(); days = new LinkedList<String>(); } public static void main(String[] args){ Scanner sc = new Scanner(System.in); // Creating hashmap and "reverse" hashmap index.put("edinburgh", 0); index.put("london", 1); index.put("ljubljana", 2); index.put("milan", 3); index.put("zurich", 4); stringIndex.put(0, "edinburgh"); stringIndex.put(1, "london"); stringIndex.put(2, "ljubljana"); stringIndex.put(3, "milan"); stringIndex.put(4, "zurich"); // Direct flights graph graph[index.get("edinburgh")][index.get("london")] = true; graph[index.get("london")][index.get("edinburgh")] = true; graph[index.get("london")][index.get("ljubljana")] = true; graph[index.get("london")][index.get("zurich")] = true; graph[index.get("london")][index.get("milan")] = true; graph[index.get("ljubljana")][index.get("zurich")] = true; graph[index.get("ljubljana")][index.get("london")] = true; graph[index.get("milan")][index.get("london")] = true; graph[index.get("milan")][index.get("zurich")] = true; graph[index.get("zurich")][index.get("ljubljana")] = true; graph[index.get("zurich")][index.get("london")] = true; graph[index.get("zurich")][index.get("milan")] = true; // Creating array of flights database CreateFlights(); String from, to; from = sc.nextLine(); to = sc.nextLine(); System.out.println("From: " + from); System.out.println("To: " + to); path[0] = index.get(from); dfs(index.get(from), index.get(to)); System.out.println("Days available: " + daysAvailable); System.out.print("Example Route: "); for(int k = 0; k < FlightNumbers.size()+1; k++){ if(FlightNumbers.isEmpty()){ System.out.println(); break; } System.out.print(stringIndex.get(path[k]) + "-" + stringIndex.get(path[k+1]) + ":" + FlightNumbers.removeFirst() + ":" + DepTimes.removeFirst() + " "); } System.out.println(); } }
package cd.com.a.bo; public interface PrdOrderDao { }
package com.ramiromadriaga.viewpagerlistviewactivity; import android.os.Bundle; import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBarActivity; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; public class ListarUnCircuito extends ActionBarActivity { private ImageView imgImagen; private TextView txtTitulo, txtContenido; String[] titulo; String[] contenido; private int[] imagenCircuitoChico = { R.drawable.circuitochico_plaza, R.drawable.circuitochico_iglesiacatedral, R.drawable.circuitochico_casanatalsarmiento, R.drawable.circuitochico_celdahistoriasanmartin, R.drawable.circuitochico_parque, R.drawable.circuitochico_auditorio, R.drawable.circuitochico_cienciasnaturales, R.drawable.circuitochico_museograffigna }; private int[] imagenCircuitoLunar = { R.drawable.circuitolunar_caucete, R.drawable.circuitolunar_difunta, R.drawable.circuitolunar_vallefertil, R.drawable.circuitolunar_ischigualasto }; private int[] imagenRutaDelVino = { R.drawable.rutadelvino_bodegaslaguarda, R.drawable.rutadelvino_champaneramiguelmas, R.drawable.rutadelvino_bodegasyvinedosfabril, R.drawable.rutadelvino_lasmarianasbodegafamliar, R.drawable.rutadelvino_vinassegisa }; private int[] imagenCircuitoDelSol = { R.drawable.circuitodelsol_parquefaunistico, R.drawable.circuitodelsol_diquedeullum, R.drawable.circuitodelsol_quebradazonda, R.drawable.circuitodelsol_jardindelospoetas, R.drawable.circuitodelsol_autodromodezonda, R.drawable.circuitodelsol_cavasdezonda }; private int[] imagenCircuitoVerde = { R.drawable.circuitoverde_iglesia, R.drawable.circuitoverde_pismanta, R.drawable.circuitoverde_rodeo, R.drawable.circuitoverde_tudcum, R.drawable.circuitoverde_cuestadelviento, R.drawable.circuitoverde_jachal, R.drawable.circuitoverde_huaco }; private int[] imagenCircuitoDelRio = { R.drawable.circuitodelrio_calingasta, R.drawable.circuitodelrio_barreal, R.drawable.circuitodelrio_pampa, R.drawable.circuitodelrio_obsevatorio }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.listar_un_circuito); ActionBar actionBar = getSupportActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); Bundle extras = getIntent().getExtras(); int idcircuito = extras.getInt("idcircuito"); final int position = extras.getInt("position"); String nombreCircuito = extras.getString("nombreCircuito"); String nombreSubCircuito = extras.getString("nombreSubCircuito"); //Log.i("ramiro", "listar un circuito idcircuito" + idcircuito); //Log.i("ramiro", "listar un circuito position " + position); /**INDICAR TITULO Y SUBTITULO**/ actionBar.setTitle(nombreCircuito); actionBar.setSubtitle(nombreSubCircuito); txtTitulo = (TextView) findViewById(R.id.tv_titulo_listaruncircuito); txtContenido = (TextView) findViewById(R.id.tv_contenido_listaruncircuito); imgImagen = (ImageView) findViewById(R.id.iv_imagen_listaruncircuito); switch (idcircuito){ case 0: //circuito chico titulo = getResources().getStringArray(R.array.circuitochico_titulo); contenido = getResources().getStringArray(R.array.circuitochico_contenido_completo); imgImagen.setImageResource(imagenCircuitoChico[position]); break; case 1: //circuito lunar titulo = getResources().getStringArray(R.array.circuitolunar_titulo); contenido = getResources().getStringArray(R.array.circuitolunar_contenido_completo); imgImagen.setImageResource(imagenCircuitoLunar[position]); break; case 2: //ruta del vino titulo = getResources().getStringArray(R.array.rutadelvino_titulo); contenido = getResources().getStringArray(R.array.rutadelvino_contenido_completo); imgImagen.setImageResource(imagenRutaDelVino[position]); break; case 3: //circuito del sol titulo = getResources().getStringArray(R.array.circuitodelsol_titulo); contenido = getResources().getStringArray(R.array.circuitodelsol_contenido_completo); imgImagen.setImageResource(imagenCircuitoDelSol[position]); break; case 4: //circuito verde titulo = getResources().getStringArray(R.array.circuitoverde_titulo); contenido = getResources().getStringArray(R.array.circuitoverde_contenido_completo); imgImagen.setImageResource(imagenCircuitoVerde[position]); break; case 5: //circuito del río titulo = getResources().getStringArray(R.array.circuitodelrio_titulo); contenido = getResources().getStringArray(R.array.circuitodelrio_contenido_completo); imgImagen.setImageResource(imagenCircuitoDelRio[position]); break; default: Toast.makeText(getApplicationContext(), "no esta cargado, pronto lo estará", Toast.LENGTH_SHORT).show(); } txtTitulo.setText(titulo[position]); txtContenido.setText(contenido[position]); } }
package uta.cloud.email.service; public interface EmailService { void SendSimpleEmail(String toEmailAdr, String subject, String text); }
package servlet; import java.io.IOException; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Date; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import controlers.CtrlABMCuenta; import controlers.CtrlABMMoneda; import entity.Cuenta; import entity.Moneda; import entity.Usuario; import util.Componentes; /** * Servlet implementation class Cuentas */ @WebServlet({ "/cuentas/*", "/Cuentas/*", "/CUENTAS/*", "/Cuentas" }) public class Cuentas extends HttpServlet { private static final long serialVersionUID = 1L; private Usuario user; /** * @see HttpServlet#HttpServlet() */ public Cuentas() { super(); } /** * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response) */ protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { if(!Componentes.estaLogeado(request, response)) { throw new Exception("No es un usuario activo. Por favor, vuelva a ingresar."); } this.user = (Usuario) request.getSession().getAttribute("usuario"); String method = request.getMethod(); if (method.equals("GET")) { doGet(request, response); } else if (method.equals("POST")) { doPost(request, response); } } catch (Exception e) { System.out.println(e.getMessage()); request.getSession().setAttribute("mensaje", e.getMessage()); response.sendRedirect("../login"); } } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { if(request.getPathInfo().equals("/alta")) { //Armo un ArrayList para el select CtrlABMMoneda ctrlMoneda = new CtrlABMMoneda(); ArrayList<Moneda> monedas = ctrlMoneda.getAll(); request.setAttribute("monedas", monedas); request.getRequestDispatcher("/accounts/alta.jsp").forward(request, response); }else { //Usuario user = (Usuario) request.getSession().getAttribute("usuario"); CtrlABMCuenta ctrlCuentas = new CtrlABMCuenta(); ArrayList<Cuenta> cuentas = ctrlCuentas.getAll(this.user); request.setAttribute("cuentas", cuentas); request.getRequestDispatcher("/accounts/index.jsp").forward(request, response); } } catch (Exception e) { System.out.println(e.getMessage()); request.getSession().setAttribute("mensaje", e.getMessage()); } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { switch (request.getPathInfo()) { case "/alta": try { this.alta(request, response); response.sendRedirect("../cuentas/"); } catch (Exception e) { System.out.println(e.getMessage()); request.getSession().setAttribute("mensaje", e.getMessage()); request.getRequestDispatcher("/accounts/index.jsp").forward(request, response); } break; case "/baja": try { this.baja(request, response); response.sendRedirect("../cuentas/"); } catch (Exception e) { System.out.println(e.getMessage()); request.getSession().setAttribute("mensaje", e.getMessage()); request.getRequestDispatcher("/accounts/index.jsp").forward(request, response); } break; case "/modificacion": try { this.modificacion(request, response); request.getRequestDispatcher("/accounts/modificacion.jsp").forward(request, response); } catch (Exception e) { System.out.println(e.getMessage()); request.getSession().setAttribute("mensaje", e.getMessage()); request.getRequestDispatcher("/accounts/index.jsp").forward(request, response); } break; case "/modificar": try { this.modificar(request, response); response.sendRedirect("../cuentas/"); } catch (Exception e) { System.out.println(e.getMessage()); request.getSession().setAttribute("mensaje", e.getMessage()); request.getRequestDispatcher("/accounts/index.jsp").forward(request, response); } break; } } private void alta(HttpServletRequest request, HttpServletResponse response) throws Exception { Cuenta cuenta = new Cuenta(); cuenta.setUsuario(this.user); cuenta.setNombre(request.getParameter("nombre")); cuenta.setValorInicial(Float.parseFloat(request.getParameter("valor_inicial"))); cuenta.setColor(request.getParameter("color")); cuenta.setTipo(request.getParameter("tipo")); cuenta.setDescripcion(request.getParameter("descripcion")); Date date = new Date(); cuenta.setCreado(new Timestamp(date.getTime())); Moneda moneda = new Moneda(); moneda.setId(Integer.parseInt(request.getParameter("moneda_id"))); cuenta.setMoneda(moneda); CtrlABMCuenta ctrlCuenta = new CtrlABMCuenta(); ctrlCuenta.add(cuenta); } private void modificacion(HttpServletRequest request, HttpServletResponse response) throws Exception { Cuenta cuenta = new Cuenta(); cuenta.setId(Integer.parseInt(request.getParameter("id"))); CtrlABMCuenta ctrlcuenta = new CtrlABMCuenta(); request.setAttribute("cuenta", ctrlcuenta.getById(cuenta)); //Armo un Array comun para le select CtrlABMMoneda ctrlMoneda = new CtrlABMMoneda(); ArrayList<Moneda> monedas = ctrlMoneda.getAll(); request.setAttribute("monedas", monedas); } private void modificar(HttpServletRequest request, HttpServletResponse response) throws Exception { Cuenta cuenta = new Cuenta(); cuenta.setId(Integer.parseInt(request.getParameter("id"))); cuenta.setNombre(request.getParameter("nombre")); cuenta.setValorInicial(Float.parseFloat(request.getParameter("valor_inicial"))); cuenta.setColor(request.getParameter("color")); cuenta.setTipo(request.getParameter("tipo")); cuenta.setDescripcion(request.getParameter("descripcion")); Moneda moneda = new Moneda(); moneda.setId(Integer.parseInt(request.getParameter("moneda_id"))); cuenta.setMoneda(moneda); CtrlABMCuenta ctrlCuenta = new CtrlABMCuenta(); ctrlCuenta.update(cuenta); } private void baja(HttpServletRequest request, HttpServletResponse response) throws ServletException, Exception { try { Cuenta cuenta = new Cuenta(); cuenta.setId(Integer.parseInt(request.getParameter("id"))); CtrlABMCuenta ctrlCuenta = new CtrlABMCuenta(); ctrlCuenta.delete(cuenta); } catch (Exception e) { throw e; } } }
package jp.smartcompany.job.modules.quartz.task; /** * @author Xiao Wenpeng */ public interface ITask { /** * 执行定时任务接口 * * @param params 参数,多参数使用JSON数据 */ void run(String params); }
package com.sporsimdi.action.home; import java.util.Map; import javax.ejb.EJB; import javax.faces.bean.ManagedBean; import javax.faces.bean.ManagedProperty; import javax.faces.bean.ViewScoped; import javax.faces.context.FacesContext; import com.sporsimdi.action.facade.YasGrubuFacade; import com.sporsimdi.action.service.SessionObject; import com.sporsimdi.model.entity.YasGrubu; @ManagedBean(name = "yasGrubuHome") @ViewScoped public class YasGrubuHome extends HomeBean<YasGrubu>{ private static final long serialVersionUID = 5528752636982509999L; @EJB YasGrubuFacade yasGrubuFacade; @ManagedProperty(value = "#{sessionObject}") private SessionObject sessionObject; public void sayfaLoad() { super.sayfaLoad(); FacesContext fc = FacesContext.getCurrentInstance(); String pyasGrubuId = getYasGrubuIdParam(fc); if (pyasGrubuId != null && !pyasGrubuId.isEmpty()) { setInstance(yasGrubuFacade.findById(Long.valueOf(pyasGrubuId))); } } public String getYasGrubuIdParam(FacesContext fc) { Map<String, String> params = fc.getExternalContext() .getRequestParameterMap(); return params.get("yasGrubuId"); } @Override public String save() { getInstance().setIsletme(sessionObject.getSelectedIsletme()); return super.save(); } public SessionObject getSessionObject() { return sessionObject; } public void setSessionObject(SessionObject sessionObject) { this.sessionObject = sessionObject; } }
package com.tencent.mm.plugin.wallet.pay.ui; import com.tencent.mm.g.a.sz; import com.tencent.mm.g.a.tk; import com.tencent.mm.sdk.b.a; import com.tencent.mm.sdk.b.b; import com.tencent.mm.sdk.b.c; import com.tencent.mm.sdk.platformtools.x; class WalletChangeBankcardUI$1 extends c<tk> { final /* synthetic */ WalletChangeBankcardUI pfC; WalletChangeBankcardUI$1(WalletChangeBankcardUI walletChangeBankcardUI) { this.pfC = walletChangeBankcardUI; this.sFo = tk.class.getName().hashCode(); } public final /* synthetic */ boolean a(b bVar) { tk tkVar = (tk) bVar; x.i("MicroMsg.WalletChangeBankcardUI", "realnameNotifyListener %s", new Object[]{Integer.valueOf(tkVar.ceX.result)}); sz szVar = new sz(); if (tkVar.ceX.result == -1) { szVar.cdR.scene = 17; } else if (tkVar.ceX.result == 0) { szVar.cdR.scene = 18; } else { szVar.cdR.scene = 0; } szVar.cdS.cdN = new 1(this, tkVar); a.sFg.m(szVar); return false; } }
package com.tencent.mm.plugin.location.model; import com.tencent.mm.ab.d; import com.tencent.mm.model.bv.a; class l$6 implements a { final /* synthetic */ l kDB; l$6(l lVar) { this.kDB = lVar; } public final void a(d.a aVar) { new n().b(aVar); } }
package cn.lawwing.jisporttactics.widget; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.RectF; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.view.View; import java.util.ArrayList; import cn.lawwing.jisporttactics.paint.BitmapCtl; import cn.lawwing.jisporttactics.paint.Circlectl; import cn.lawwing.jisporttactics.paint.EraserCtl; import cn.lawwing.jisporttactics.paint.ISketchpadDraw; import cn.lawwing.jisporttactics.paint.IUndoRedoCommand; import cn.lawwing.jisporttactics.paint.PenuCtl; import cn.lawwing.jisporttactics.paint.RectuCtl; import cn.lawwing.jisporttactics.paint.Triangle; import cn.lawwing.jisporttactics.utils.BitmapUtils; /** * Created by lawwing on 2018/1/19. */ public class SportNormalTacticsView extends View implements IUndoRedoCommand { private static final String TAG = "SportNormalTacticsView"; //画笔常量 public static final int STROKE_PEN = 1; //画笔1 public static final int STROKE_ERASER = 2; //橡皮擦2 public static final int STROKE_PLYGON = 3; //多边形3 public static final int STROKE_RECT = 4; //矩形 4 public static final int STROKE_TRIANGLE = 5; //三角形5 public static final int STROKE_CIRCLE = 6; //圆 6 public static final int STROKE_OVAL = 7; //椭圆 7 public static final int STROKE_LINE = 8; //直线8 public static final int STROKE_SPRAYGUN = 9; //喷枪9 public static final int STROKE_PAINTPOT = 10; //油漆桶10 public static final int UNDO_SIZE = 20; //撤销栈的大小 public static final int BITMAP_WIDTH = 650; //画布高 public static final int BITMAP_HEIGHT = 400; //画布宽 private int m_strokeType = STROKE_PEN; //画笔风格 public static int flag = 0; //油漆桶参数 private static int m_strokeColor = Color.RED; //画笔颜色 private static int m_penSize = 10; //画笔大小 private static int m_eraserSize = 30; //橡皮擦大小 //实例新画布 private boolean m_isEnableDraw = true; //标记是否可以画 private boolean m_isDirty = false; //标记 private boolean m_isTouchUp = false; //标记是否鼠标弹起 private boolean m_isSetForeBmp = false; //标记是否设置了前bitmap private int m_bkColor = Color.TRANSPARENT; //背景色 private int m_boundColor = Color.TRANSPARENT; //边框颜色 private int m_canvasWidth = 100; //画布宽 private int m_canvasHeight = 100; //画布高 private boolean m_canClear = true; //标记是否可清除 //控件的宽度 private int width; //控件的高度 private int height; private Bitmap m_foreBitmap = null; //用于显示的bitmap private Bitmap m_tempForeBitmap = null; //用于缓冲的bitmap private Bitmap m_bkBitmap = null; //用于背后画的bitmap private Canvas m_canvas; //画布 private Paint m_bitmapPaint = null; //画笔 private SketchPadUndoStack m_undoStack = null;//栈存放执行的操作 private ISketchpadDraw m_curTool = null; //记录操作的对象画笔类 int antiontemp = 0;//获取鼠标点击画布的event boolean myLoop = false;// 喷枪结束标识符 //这是画板边距以内paintPaddingWidth可画(x轴),默认为20 private int paintPaddingWidth = 20; //这是画板边距以内paintPaddingWidth可画(y轴),默认为20 private int paintPaddingHeight = 20; public SportNormalTacticsView(Context context) { super(context); initialize(); } public SportNormalTacticsView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); initialize(); } public SportNormalTacticsView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initialize(); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (null != m_bkBitmap) { //如果背景图不为空那就绘制背景 drawBackoundBitmap(canvas); } else { //如果为空就是绘制背景色 canvas.drawColor(m_bkColor); } if (null != m_foreBitmap) { canvas.drawBitmap(m_foreBitmap, 0, 0, m_bitmapPaint); } if (null != m_curTool) { if (STROKE_ERASER != m_strokeType) { if (!m_isTouchUp) { //调用绘图功能 m_curTool.draw(canvas); } } } drawBound(canvas); if (hasScale) { canvas.scale(0.5f, 1f); hasScale = false; } else { canvas.scale(2.0f, 2.0f); hasScale = false; } } /** * 初始化 */ private void initialize() { m_canvas = new Canvas();//实例画布用于整个绘图操作 m_bitmapPaint = new Paint(Paint.ANTI_ALIAS_FLAG); //实例化画笔用于bitmap设置画布canvas m_undoStack = new SketchPadUndoStack(this, UNDO_SIZE);//实例化队列 } /** * 画背景 * * @param canvas */ private void drawBackoundBitmap(Canvas canvas) { //画背景色 canvas.drawColor(m_bkColor); float ratio = (m_bkBitmap.getWidth() * 1.0f) / (m_bkBitmap.getHeight() * 1.0f); int tempheight = (int) (width / ratio); int paddingTop = (height - tempheight) / 2; //判断比例是否不符合,负数的时候则不需要padding paddingTop = paddingTop > 0 ? paddingTop : 0; RectF dst = new RectF(getLeft(), getTop() + paddingTop, getRight(), getBottom() - paddingTop); Rect rst = new Rect(0, 0, m_bkBitmap.getWidth(), m_bkBitmap.getHeight()); canvas.drawBitmap(m_bkBitmap, rst, dst, m_bitmapPaint); } /** * 画边框 * * @param canvas */ private void drawBound(Canvas canvas) { Paint mHorPaint = new Paint(); mHorPaint.setAntiAlias(true); mHorPaint.setStrokeWidth(paintPaddingHeight * 2); mHorPaint.setStyle(Paint.Style.FILL); mHorPaint.setColor(m_boundColor); Paint mVerPaint = new Paint(); mVerPaint.setAntiAlias(true); mVerPaint.setStrokeWidth(paintPaddingWidth * 2); mVerPaint.setStyle(Paint.Style.FILL); mVerPaint.setColor(m_boundColor); canvas.drawLine(0, 0, width, 0, mHorPaint); canvas.drawLine(0, 0, 0, height, mVerPaint); canvas.drawLine(width, height, width, 0, mVerPaint); canvas.drawLine(width, height, 0, height, mHorPaint); } /** * 外部调用刷新画板的接口 */ public void refresh() { invalidate(); } @Override public void undo() { if (null != m_undoStack) { m_undoStack.undo(); } } @Override public void redo() { if (null != m_undoStack) { m_undoStack.redo(); } } @Override public boolean canRedo() { if (null != m_undoStack) { return m_undoStack.canRedo(); } return false; } @Override public boolean canUndo() { if (null != m_undoStack) { return m_undoStack.canUndo(); } return false; } @Override public void onDeleteFromUndoStack() { } @Override public void onDeleteFromRedoStack() { } public boolean isDirty() { return m_isDirty; } public void setDrawStrokeEnable(boolean isEnable) { //确定是否可绘图 m_isEnableDraw = isEnable; } /** * 设置边框颜色 * * @param m_boundColor * @return */ public SportNormalTacticsView setM_boundColor(int m_boundColor) { this.m_boundColor = m_boundColor; return this; } /** * 设置背景色 * * @param color */ public SportNormalTacticsView setBkColor(int color) { if (m_bkColor != color) { m_bkColor = color; invalidate(); } return this; } /** * 设置画笔的大小和橡皮擦大小 * * @param size * @param type */ public void setStrokeSize(int size, int type) { switch (type) { case STROKE_PEN: m_penSize = size; break; case STROKE_ERASER: m_eraserSize = size; break; } } /** * 获取画笔大小 * * @return */ public int getStrokeSize() { //得到画笔的大小 return m_penSize; } /** * 设置画笔颜色 * * @param color */ public void setStrokeColor(int color) { //设置画笔颜色 m_strokeColor = color; } /** * 获取画笔颜色 * * @return */ public int getStrokeColor() { //得到画笔的大小 return m_strokeColor; } public static int getEraser() { //得到橡皮擦的大小 return m_eraserSize; } /** * 清空全部画笔 */ public void clearAllStrokes() { //清空设置 if (m_canClear) { // 清空撤销栈 m_undoStack.clearAll(); // 设置当前的bitmap对象为空 if (null != m_tempForeBitmap) { m_tempForeBitmap.recycle(); m_tempForeBitmap = null; } // Create a new fore bitmap and set to canvas. createStrokeBitmap(m_canvasWidth, m_canvasHeight); invalidate(); m_isDirty = true; m_canClear = false; } } /** * 保存时对当前绘图板的图片进行快照 */ public Bitmap getCanvasSnapshot() { setDrawingCacheEnabled(true); buildDrawingCache(true); Bitmap bmp = getDrawingCache(true); if (null == bmp) { Log.d(TAG, "getCanvasSnapshot getDrawingCache == null"); } return BitmapUtils.duplicateBitmap(bmp, BITMAP_WIDTH, BITMAP_HEIGHT); } /** * 打开图像文件时,设置当前视图为foreBitmap */ public void setForeBitmap(Bitmap foreBitmap) { if (foreBitmap != m_foreBitmap && null != foreBitmap) { // Recycle the bitmap. if (null != m_foreBitmap) { m_foreBitmap.recycle(); } m_foreBitmap = BitmapUtils.duplicateBitmap(foreBitmap, BITMAP_WIDTH, BITMAP_HEIGHT); if (null != m_foreBitmap && null != m_canvas) { m_canvas.setBitmap(m_foreBitmap); } invalidate(); } } /** * 获取前景 * * @return */ public Bitmap getForeBitmap() { return m_foreBitmap; } /** * 设置背景bitmap * * @param bmp */ public void setBkBitmap(Bitmap bmp) { if (m_bkBitmap != bmp) { m_bkBitmap = bmp; // m_bkBitmap = BitmapUtils.duplicateBitmap(bmp, BITMAP_WIDTH, BITMAP_HEIGHT); invalidate(); } } /** * 获取背景bitmap * * @return */ public Bitmap getBkBitmap() { return m_bkBitmap; } protected void createStrokeBitmap(int w, int h) { m_canvasWidth = w; m_canvasHeight = h; Bitmap bitmap = Bitmap.createBitmap(m_canvasWidth, m_canvasHeight, Bitmap.Config.ARGB_8888); if (null != bitmap) { m_foreBitmap = bitmap; // Set the fore bitmap to m_canvas to be as canvas of strokes. m_canvas.setBitmap(m_foreBitmap); } } protected void setTempForeBitmap(Bitmap tempForeBitmap) { if (null != tempForeBitmap) { if (null != m_foreBitmap) { m_foreBitmap.recycle(); } m_foreBitmap = BitmapCtl.duplicateBitmap(tempForeBitmap); if (null != m_foreBitmap && null != m_canvas) { m_canvas.setBitmap(m_foreBitmap); invalidate(); } } } /** * 设置画笔大小 * * @param width * @param height */ protected void setCanvasSize(int width, int height) {//设置画布大小 if (width > 0 && height > 0) { if (m_canvasWidth != width || m_canvasHeight != height) { m_canvasWidth = width; m_canvasHeight = height; createStrokeBitmap(m_canvasWidth, m_canvasHeight); } } } /** * 启动设置画笔的颜色和大小 调用修改 */ public void setStrokeType(int type) { m_strokeColor = getStrokeColor(); m_penSize = getStrokeSize(); switch (type) { case STROKE_PEN: m_curTool = new PenuCtl(m_penSize, m_strokeColor); Log.i(TAG, "pen实例化"); break; case STROKE_ERASER: m_curTool = new EraserCtl(m_eraserSize); break; case STROKE_RECT: m_curTool = new RectuCtl(m_penSize, m_strokeColor); Log.i(TAG, "Rect实例化!"); break; case STROKE_CIRCLE: m_curTool = new Circlectl(m_penSize, m_strokeColor); Log.i(TAG, "Circle实例化!"); break; case STROKE_TRIANGLE: m_curTool = new Triangle(m_penSize, m_strokeColor); break; } //用于记录操作动作名称 m_strokeType = type; } private boolean hasScale = false; /** * 重新加载路劲 */ public SportNormalTacticsView reloadPaths(boolean hasScale) { for (ISketchpadDraw draw : m_undoStack.getM_undoStack()) { draw.draw(m_canvas); } if (hasScale) { m_canvas.scale(0.5f, 1f); } else { m_canvas.scale(2f, 1f); } return this; } public class SketchPadUndoStack { private int m_stackSize = 0; //栈大小 private SportNormalTacticsView m_sketchPad = null; //视图对象 private ArrayList<ISketchpadDraw> m_undoStack = new ArrayList<ISketchpadDraw>(); private ArrayList<ISketchpadDraw> m_redoStack = new ArrayList<ISketchpadDraw>(); private ArrayList<ISketchpadDraw> m_removedStack = new ArrayList<ISketchpadDraw>(); public ArrayList<ISketchpadDraw> getM_redoStack() { return m_redoStack; } public ArrayList<ISketchpadDraw> getM_undoStack() { return m_undoStack; } public ArrayList<ISketchpadDraw> getM_removedStack() { return m_removedStack; } public SketchPadUndoStack(SportNormalTacticsView sketchPad, int stackSize) { m_sketchPad = sketchPad; m_stackSize = stackSize; } public void push(ISketchpadDraw sketchPadTool) { if (null != sketchPadTool) { if (m_undoStack.size() == m_stackSize && m_stackSize > 0) { ISketchpadDraw removedTool = m_undoStack.get(0); m_removedStack.add(removedTool); m_undoStack.remove(0); } m_undoStack.add(sketchPadTool); if (null != listener) { listener.addCount(); } } } //清空栈 public void clearAll() { m_redoStack.clear(); m_undoStack.clear(); m_removedStack.clear(); if (null != listener) { listener.clearCount(); } } public void undo() { if (canUndo() && null != m_sketchPad) { Log.i(TAG, "undo点击"); ISketchpadDraw removedTool = m_undoStack.get(m_undoStack.size() - 1); m_redoStack.add(removedTool); m_undoStack.remove(m_undoStack.size() - 1); if (null != listener) { listener.minusCount(); } if (null != m_tempForeBitmap) { // Set the temporary fore bitmap to canvas. m_sketchPad.setTempForeBitmap(m_sketchPad.m_tempForeBitmap); } else { // Create a new bitmap and set to canvas. m_sketchPad.createStrokeBitmap(m_sketchPad.m_canvasWidth, m_sketchPad.m_canvasHeight); } Canvas canvas = m_sketchPad.m_canvas; // First draw the removed tools from undo stack. for (ISketchpadDraw sketchPadTool : m_removedStack) { sketchPadTool.draw(canvas); } for (ISketchpadDraw sketchPadTool : m_undoStack) { sketchPadTool.draw(canvas); } m_sketchPad.invalidate(); } } public void redo() { if (canRedo() && null != m_sketchPad) { ISketchpadDraw removedTool = m_redoStack.get(m_redoStack.size() - 1); m_undoStack.add(removedTool); m_redoStack.remove(m_redoStack.size() - 1); if (null != listener) { listener.addCount(); } if (null != m_tempForeBitmap) { // Set the temporary fore bitmap to canvas. m_sketchPad.setTempForeBitmap(m_sketchPad.m_tempForeBitmap); } else { // Create a new bitmap and set to canvas. m_sketchPad.createStrokeBitmap(m_sketchPad.m_canvasWidth, m_sketchPad.m_canvasHeight); } Canvas canvas = m_sketchPad.m_canvas; // First draw the removed tools from undo stack. for (ISketchpadDraw sketchPadTool : m_removedStack) { sketchPadTool.draw(canvas); } for (ISketchpadDraw sketchPadTool : m_undoStack) { sketchPadTool.draw(canvas); } m_sketchPad.invalidate(); } } public boolean canUndo() {// return (m_undoStack.size() > 0); } public boolean canRedo() {//判断栈的大小 return (m_redoStack.size() > 0); } } private ICountChangeListener listener; public void setListener(ICountChangeListener listener) { this.listener = listener; } /** * 用于计算当前有多少条画痕的监听 */ public interface ICountChangeListener { void addCount(); void minusCount(); void clearCount(); } protected void onSizeChanged(int w, int h, int oldw, int oldh) { // TODO Auto-generated method stub super.onSizeChanged(w, h, oldw, oldh); if (!m_isSetForeBmp) { setCanvasSize(w, h); } Log.i(TAG, "Canvas"); m_canvasWidth = w; m_canvasHeight = h; m_isSetForeBmp = false; } /** * 设置可画范围的边距padding,x轴 * * @param paintPaddingWidth * @return */ public SportNormalTacticsView setPaintPaddingWidth(int paintPaddingWidth) { this.paintPaddingWidth = paintPaddingWidth; return this; } /** * 设置可画范围的边距padding,y轴 * * @param paintPaddingHeight * @return */ public SportNormalTacticsView setPaintPaddingHeight(int paintPaddingHeight) { this.paintPaddingHeight = paintPaddingHeight; return this; } public boolean onTouchEvent(MotionEvent event) { // TODO Auto-generated method stub //实例新画布 //标记是否可以画 if (m_isEnableDraw) //判断是否可绘图 { //触摸点的坐标,相对于控件内 float yx = event.getX(); float yy = event.getY(); //防止纵横坐标超出自身view的宽高 float width = this.getWidth(); float height = this.getHeight(); //获取点击事件距离控件左边的距离,即视图坐标,,控制着左边的距离 float xLeftTop = this.getX() + paintPaddingWidth; //获取点击事件距离控件顶边的距离,即视图坐标 float yLeftTop = this.getY() + paintPaddingHeight; //控制着右边 float xRightBottom = xLeftTop + width - paintPaddingWidth * 2; float yRighBottom = yLeftTop + height - paintPaddingHeight * 2; if (yx < xLeftTop) { //左边边界 yx = xLeftTop + m_penSize * 0.5f; } if (yx > xRightBottom) { //右边边界 yx = xRightBottom - m_penSize * 0.5f; } if (yy < yLeftTop) { //上边边界 yy = yLeftTop + m_penSize * 0.5f; } if (yy > yRighBottom) { //下边边界 yy = yRighBottom - m_penSize * 0.5f; } m_isTouchUp = false; switch (event.getAction()) { case MotionEvent.ACTION_DOWN: //根据m_strokeType进行重新生成对象且记录下操作对象 setStrokeType(m_strokeType); m_curTool.touchDown(yx, yy); invalidate(); break; case MotionEvent.ACTION_MOVE: m_curTool.touchMove(yx, yy); //若果当前操作为橡皮擦则调用绘图操作 if (STROKE_ERASER == m_strokeType) { m_curTool.draw(m_canvas); } invalidate(); m_isDirty = true; m_canClear = true; break; case MotionEvent.ACTION_UP: m_isTouchUp = true; if (m_curTool.hasDraw()) { // Add to undo stack. m_undoStack.push(m_curTool); } m_curTool.touchUp(yx, yy); // Draw strokes on bitmap which is hold by m_canvas. m_curTool.draw(m_canvas); invalidate(); m_isDirty = true; m_canClear = true; myLoop = false; break; } return true; } else { return false; } } public int getStrokeType() { return m_strokeType; } //喷枪的线程操作 修改7/26 public void spraygunRun() {// 匿名内部内,鼠标按下不放时的操作,启动一个线程监控 new Thread(new Runnable() { public void run() { while (myLoop) { m_curTool.draw(m_canvas); try { Thread.sleep(50); if (antiontemp == MotionEvent.ACTION_UP) { myLoop = false; } } catch (InterruptedException e) { e.printStackTrace(); } postInvalidate(); //在线程中更新界面 } } }).start(); } //队列实现种子递归,用于油漆桶工具 7/28 public void seed_fill(int x, int y, int t_color, int r_color) { Log.i(TAG, "执行!02"); int MAX_ROW = 400; int MAX_COL = 650; int row_size = 400; int col_size = 650; if (x < 0 || x >= col_size || y < 0 || y >= row_size || m_foreBitmap.getPixel(x, y) == r_color) { return; } int queue[][] = new int[MAX_ROW * MAX_COL + 1][2]; int head = 0, end = 0; int tx, ty; /* Add node to the end of queue. */ queue[end][0] = x; queue[end][1] = y; end++; while (head < end) { tx = queue[head][0]; ty = queue[head][1]; if (m_foreBitmap.getPixel(tx, ty) == t_color) { m_foreBitmap.setPixel(tx, ty, r_color); } /* Remove the first element from queue. */ head++; /* West */ if (tx - 1 >= 0 && m_foreBitmap.getPixel(tx - 1, ty) == t_color) { m_foreBitmap.setPixel(tx - 1, ty, r_color); queue[end][0] = tx - 1; queue[end][1] = ty; end++; } else if (tx - 1 >= 0 && m_foreBitmap.getPixel(tx - 1, ty) != t_color) { m_foreBitmap.setPixel(tx - 1, ty, r_color); } /* East */ if (tx + 1 < col_size && m_foreBitmap.getPixel(tx + 1, ty) == t_color) { m_foreBitmap.setPixel(tx + 1, ty, r_color); queue[end][0] = tx + 1; queue[end][1] = ty; end++; } else if (tx + 1 < col_size && m_foreBitmap.getPixel(tx + 1, ty) != t_color) { m_foreBitmap.setPixel(tx + 1, ty, r_color); } /* North */ if (ty - 1 >= 0 && m_foreBitmap.getPixel(tx, ty - 1) == t_color) { m_foreBitmap.setPixel(tx, ty - 1, r_color); queue[end][0] = tx; queue[end][1] = ty - 1; end++; } else if (ty - 1 >= 0 && m_foreBitmap.getPixel(tx, ty - 1) != t_color) { m_foreBitmap.setPixel(tx, ty - 1, r_color); } /* South */ if (ty + 1 < row_size && m_foreBitmap.getPixel(tx, ty + 1) == t_color) { m_foreBitmap.setPixel(tx, ty + 1, r_color); queue[end][0] = tx; queue[end][1] = ty + 1; end++; } else if (ty + 1 < row_size && m_foreBitmap.getPixel(tx, ty + 1) != t_color) { m_foreBitmap.setPixel(tx, ty + 1, r_color); } } return; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); width = MeasureSpec.getSize(widthMeasureSpec); height = MeasureSpec.getSize(heightMeasureSpec); } }
package com.github.ezauton.recorder.serializers; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.ser.std.StdSerializer; import com.github.ezauton.core.pathplanning.Path; import com.github.ezauton.core.pathplanning.PathSegment; import java.io.IOException; import java.util.List; public class PathSerializer extends StdSerializer<Path> { public PathSerializer() { this(null); } public PathSerializer(Class<Path> t) { super(t); } @Override public void serialize(Path value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException { try { List<PathSegment> pathSegments = value.getPathSegments(); double length = value.getLength(); jgen.writeStartObject(); jgen.writeFieldName("pathSegments"); jgen.writeObject(pathSegments); jgen.writeFieldName("length"); jgen.writeNumber(length); jgen.writeEndObject(); } catch (Exception e) { throw new JsonGenerationException("Could not serialize Path", e); } } }
package com.devinchen.library.common.base.activity; import android.support.v7.app.AppCompatActivity; /** * Created by Chris Chen on 2017/6/17. * MVP下的activity模版,封装presenter的引用 */ public abstract class BaseMvpActivity extends AppCompatActivity { }
package uk.gov.digital.ho.hocs.search.application.queue; import org.apache.camel.LoggingLevel; import org.apache.camel.Processor; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.aws.sqs.SqsConstants; import org.apache.camel.model.dataformat.JsonLibrary; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import uk.gov.digital.ho.hocs.search.api.CaseDataService; import uk.gov.digital.ho.hocs.search.api.dto.*; import static uk.gov.digital.ho.hocs.search.application.RequestData.transferHeadersToMDC; @Component public class SearchConsumer extends RouteBuilder { private static final String CREATE_CASE_QUEUE = "direct:createCaseQueue"; private static final String UPDATE_CASE_QUEUE = "direct:updateCaseQueue"; private static final String DELETE_CASE_QUEUE = "direct:deleteCaseQueue"; private static final String COMPLETE_CASE_QUEUE = "direct:completeCaseQueue"; private static final String CREATE_CORRESPONDENT_QUEUE = "direct:createCorrespondentQueue"; private static final String DELETE_CORRESPONDENT_QUEUE = "direct:deleteCorrespondentQueue"; private static final String UPDATE_CORRESPONDENT_QUEUE = "direct:updateCorrespondentQueue"; private static final String CREATE_TOPIC_QUEUE = "direct:createTopicQueue"; private static final String DELETE_TOPIC_QUEUE = "direct:deleteTopicQueue"; private static final String CREATE_SOMU_ITEM_QUEUE = "direct:createSomuItemQueue"; private static final String DELETE_SOMU_ITEM_QUEUE = "direct:deleteSomuItemQueue"; private static final String UPDATE_SOMU_ITEM_QUEUE = "direct:updateSomuItemQueue"; private final CaseDataService caseDataService; private final String searchQueue; private final String dlq; private final int maximumRedeliveries; private final int redeliveryDelay; private final int backOffMultiplier; @Autowired public SearchConsumer(CaseDataService caseDataService, @Value("${search.queue}") String searchQueue, @Value("${search.queue.dlq}") String dlq, @Value("${search.queue.maximumRedeliveries}") int maximumRedeliveries, @Value("${search.queue.redeliveryDelay}") int redeliveryDelay, @Value("${search.queue.backOffMultiplier}") int backOffMultiplier) { this.caseDataService = caseDataService; this.searchQueue = searchQueue; this.dlq = dlq; this.maximumRedeliveries = maximumRedeliveries; this.redeliveryDelay = redeliveryDelay; this.backOffMultiplier = backOffMultiplier; } @Override public void configure() { errorHandler(deadLetterChannel(dlq) .loggingLevel(LoggingLevel.ERROR) .log("Failed to add audit after configured back-off. ${body}") .useOriginalMessage() .retryAttemptedLogLevel(LoggingLevel.WARN) .maximumRedeliveries(maximumRedeliveries) .redeliveryDelay(redeliveryDelay) .backOffMultiplier(backOffMultiplier) .asyncDelayedRedelivery() .logRetryStackTrace(true)); from(searchQueue).routeId("searchCommandRoute") .setProperty(SqsConstants.RECEIPT_HANDLE, header(SqsConstants.RECEIPT_HANDLE)) .process(transferHeadersToMDC()) .log(LoggingLevel.INFO, "Audit message received") .unmarshal().json(JsonLibrary.Jackson, CreateAuditDto.class) .setProperty("type", simple("${body.type}")) .log(LoggingLevel.INFO, "type: ${body.type}") .setProperty("caseUUID", simple("${body.caseUUID}")) .log(LoggingLevel.INFO, "caseUUID: ${body.caseUUID}") .setProperty("payLoad", simple("${body.data}")) .log(LoggingLevel.DEBUG, "payLoad: ${body}") .process(createPayload()) .choice() .when(simple("${property.type} == '" + EventType.CASE_CREATED + "'")) .to(CREATE_CASE_QUEUE) .endChoice() .when(simple("${property.type} == '" + EventType.CASE_UPDATED + "'")) .to(UPDATE_CASE_QUEUE) .endChoice() .when(simple("${property.type} == '" + EventType.CASE_DELETED + "'")) .to(DELETE_CASE_QUEUE) .endChoice() .when(simple("${property.type} == '" + EventType.CASE_COMPLETED + "'")) .to(COMPLETE_CASE_QUEUE) .endChoice() .when(simple("${property.type} == '" + EventType.CORRESPONDENT_CREATED + "'")) .to(CREATE_CORRESPONDENT_QUEUE) .endChoice() .when(simple("${property.type} == '" + EventType.CORRESPONDENT_DELETED + "'")) .to(DELETE_CORRESPONDENT_QUEUE) .endChoice() .when(simple("${property.type} == '" + EventType.CORRESPONDENT_UPDATED + "'")) .to(UPDATE_CORRESPONDENT_QUEUE) .endChoice() .when(simple("${property.type} == '" + EventType.CASE_TOPIC_CREATED + "'")) .to(CREATE_TOPIC_QUEUE) .endChoice() .when(simple("${property.type} == '" + EventType.CASE_TOPIC_DELETED + "'")) .to(DELETE_TOPIC_QUEUE) .endChoice() .when(simple("${property.type} == '" + EventType.SOMU_ITEM_CREATED + "'")) .to(CREATE_SOMU_ITEM_QUEUE) .endChoice() .when(simple("${property.type} == '" + EventType.SOMU_ITEM_DELETED + "'")) .to(DELETE_SOMU_ITEM_QUEUE) .endChoice() .when(simple("${property.type} == '" + EventType.SOMU_ITEM_UPDATED + "'")) .to(UPDATE_SOMU_ITEM_QUEUE) .endChoice() .otherwise() .log(LoggingLevel.DEBUG, "Ignoring Message ${property.type}") .setHeader(SqsConstants.RECEIPT_HANDLE, exchangeProperty(SqsConstants.RECEIPT_HANDLE)) .endChoice() .end() .log("Command processed"); from(CREATE_CASE_QUEUE) .log(LoggingLevel.DEBUG, CREATE_CASE_QUEUE) .unmarshal().json(JsonLibrary.Jackson, CreateCaseRequest.class) .bean(caseDataService, "createCase(${property.caseUUID}, ${body})") .setHeader(SqsConstants.RECEIPT_HANDLE, exchangeProperty(SqsConstants.RECEIPT_HANDLE)); from(UPDATE_CASE_QUEUE) .log(LoggingLevel.DEBUG, UPDATE_CASE_QUEUE) .unmarshal().json(JsonLibrary.Jackson, UpdateCaseRequest.class) .bean(caseDataService, "updateCase(${property.caseUUID}, ${body})") .setHeader(SqsConstants.RECEIPT_HANDLE, exchangeProperty(SqsConstants.RECEIPT_HANDLE)); from(DELETE_CASE_QUEUE) .log(LoggingLevel.DEBUG, DELETE_CASE_QUEUE) .unmarshal().json(JsonLibrary.Jackson, DeleteCaseRequest.class) .bean(caseDataService, "deleteCase(${property.caseUUID}, ${body})") .setHeader(SqsConstants.RECEIPT_HANDLE, exchangeProperty(SqsConstants.RECEIPT_HANDLE)); from(COMPLETE_CASE_QUEUE) .log(LoggingLevel.DEBUG, COMPLETE_CASE_QUEUE) .bean(caseDataService, "completeCase(${property.caseUUID})") .setHeader(SqsConstants.RECEIPT_HANDLE, exchangeProperty(SqsConstants.RECEIPT_HANDLE)); from(CREATE_CORRESPONDENT_QUEUE) .log(LoggingLevel.DEBUG, CREATE_CORRESPONDENT_QUEUE) .unmarshal().json(JsonLibrary.Jackson, CorrespondentDetailsDto.class) .bean(caseDataService, "createCorrespondent(${property.caseUUID}, ${body})") .setHeader(SqsConstants.RECEIPT_HANDLE, exchangeProperty(SqsConstants.RECEIPT_HANDLE)); from(DELETE_CORRESPONDENT_QUEUE) .log(LoggingLevel.DEBUG, DELETE_CORRESPONDENT_QUEUE) .unmarshal().json(JsonLibrary.Jackson, CorrespondentDetailsDto.class) .bean(caseDataService, "deleteCorrespondent(${property.caseUUID}, ${body})") .setHeader(SqsConstants.RECEIPT_HANDLE, exchangeProperty(SqsConstants.RECEIPT_HANDLE)); from(UPDATE_CORRESPONDENT_QUEUE) .log(LoggingLevel.DEBUG, UPDATE_CORRESPONDENT_QUEUE) .unmarshal().json(JsonLibrary.Jackson, CorrespondentDetailsDto.class) .bean(caseDataService, "updateCorrespondent(${property.caseUUID}, ${body})") .setHeader(SqsConstants.RECEIPT_HANDLE, exchangeProperty(SqsConstants.RECEIPT_HANDLE)); from(CREATE_TOPIC_QUEUE) .log(LoggingLevel.DEBUG, CREATE_TOPIC_QUEUE) .unmarshal().json(JsonLibrary.Jackson, CreateTopicRequest.class) .bean(caseDataService, "createTopic(${property.caseUUID}, ${body})") .setHeader(SqsConstants.RECEIPT_HANDLE, exchangeProperty(SqsConstants.RECEIPT_HANDLE)); from(DELETE_TOPIC_QUEUE) .log(LoggingLevel.DEBUG, DELETE_TOPIC_QUEUE) .bean(caseDataService, "deleteTopic(${property.caseUUID}, ${body})") .setHeader(SqsConstants.RECEIPT_HANDLE, exchangeProperty(SqsConstants.RECEIPT_HANDLE)); from(CREATE_SOMU_ITEM_QUEUE) .log(LoggingLevel.DEBUG, CREATE_SOMU_ITEM_QUEUE) .unmarshal().json(JsonLibrary.Jackson, SomuItemDto.class) .log(LoggingLevel.DEBUG, "${body}") .bean(caseDataService, "createSomuItem(${property.caseUUID}, ${body})") .setHeader(SqsConstants.RECEIPT_HANDLE, exchangeProperty(SqsConstants.RECEIPT_HANDLE)); from(DELETE_SOMU_ITEM_QUEUE) .log(LoggingLevel.DEBUG, DELETE_SOMU_ITEM_QUEUE) .unmarshal().json(JsonLibrary.Jackson, SomuItemDto.class) .bean(caseDataService, "deleteSomuItem(${property.caseUUID}, ${body})") .setHeader(SqsConstants.RECEIPT_HANDLE, exchangeProperty(SqsConstants.RECEIPT_HANDLE)); from(UPDATE_SOMU_ITEM_QUEUE) .log(LoggingLevel.DEBUG, UPDATE_SOMU_ITEM_QUEUE) .unmarshal().json(JsonLibrary.Jackson, SomuItemDto.class) .bean(caseDataService, "updateSomuItem(${property.caseUUID}, ${body})") .setHeader(SqsConstants.RECEIPT_HANDLE, exchangeProperty(SqsConstants.RECEIPT_HANDLE)); } private Processor createPayload() { return exchange -> { final Object payLoad = exchange.getProperty("payLoad"); exchange.getOut().setBody(payLoad); }; } }
package xu.qiwei.com.jpushtest.handlers; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.util.Log; /** * Created by xuqiwei on 17-11-20. */ public class MonitorHandler extends Handler{ public MonitorHandler(Looper arg2) { super(arg2); } @Override public void handleMessage(Message msg) { super.handleMessage(msg); Log.e("threadName==",Thread.currentThread().getName()); Log.e("msgwhat==",msg.what+""); Log.e("start",""); } }
package it.unica.pr2.ristoranti; import java.lang.*; public class TooMuchPeopleException extends RuntimeException{ public TooMuchPeopleException(){ } }
package com.toshevski.android.shows.services; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; /** * Created by l3ft on 12/11/15. */ public class NotificationPublisherForService extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Log.i("NotifPubliForSer:", "Startuvan e servisot."); context.startService(new Intent(context, NewEpisodesService.class)); } }
package algo_basic.day1; import java.util.Arrays; import java.util.Scanner; public class SWEA_1966_숫자를_정렬하자 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); StringBuffer sb = new StringBuffer(); int TC = sc.nextInt(); for (int i = 1; i <= TC; i++) { sb.append("#").append(i).append(" "); int N = sc.nextInt(); int[] arr = new int[N]; for (int j = 0; j < N; j++) { arr[j] = sc.nextInt(); } Arrays.sort(arr); for (int j = 0; j < N; j++) { sb.append(arr[j]).append(" "); } sb.append("\n"); } System.out.println(sb); } }