text
stringlengths
10
2.72M
package com.huawei.parkinglot.entity.vehicle; import java.util.ArrayList; import javax.persistence.Entity; import javax.persistence.Table; @Entity @Table(name = "vehicle") public class SUV extends Vehicle { public SUV(String licensePlate) { this.licensePlate = licensePlate; this.type = VehicleType.SUV; this.isParked = false; this.currentParking = null; //this.pastParkings = new ArrayList<>(); } }
/* * 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 jpaModel; import java.io.Serializable; import java.util.Date; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.xml.bind.annotation.XmlRootElement; /** * * @author Fallou */ @Entity @Table(name = "demande_rv") @XmlRootElement @NamedQueries({ @NamedQuery(name = "DemandeRv.findAll", query = "SELECT d FROM DemandeRv d") , @NamedQuery(name = "DemandeRv.findById", query = "SELECT d FROM DemandeRv d WHERE d.id = :id") , @NamedQuery(name = "DemandeRv.findByAdresse", query = "SELECT d FROM DemandeRv d WHERE d.adresse = :adresse") , @NamedQuery(name = "DemandeRv.findByDaterv", query = "SELECT d FROM DemandeRv d WHERE d.daterv = :daterv") , @NamedQuery(name = "DemandeRv.findByEmail", query = "SELECT d FROM DemandeRv d WHERE d.email = :email") , @NamedQuery(name = "DemandeRv.findByNaissance", query = "SELECT d FROM DemandeRv d WHERE d.naissance = :naissance") , @NamedQuery(name = "DemandeRv.findByNom", query = "SELECT d FROM DemandeRv d WHERE d.nom = :nom") , @NamedQuery(name = "DemandeRv.findByPrenom", query = "SELECT d FROM DemandeRv d WHERE d.prenom = :prenom") , @NamedQuery(name = "DemandeRv.findByTelephone", query = "SELECT d FROM DemandeRv d WHERE d.telephone = :telephone") , @NamedQuery(name = "DemandeRv.findByValide", query = "SELECT d FROM DemandeRv d WHERE d.valide = :valide") , @NamedQuery(name = "DemandeRv.findByMatricule", query = "SELECT d FROM DemandeRv d WHERE d.matricule = :matricule")}) public class DemandeRv implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @Column(name = "id") private Long id; @Column(name = "adresse") private String adresse; @Column(name = "daterv") @Temporal(TemporalType.DATE) private Date daterv; @Column(name = "email") private String email; @Column(name = "naissance") @Temporal(TemporalType.DATE) private Date naissance; @Column(name = "nom") private String nom; @Column(name = "prenom") private String prenom; @Column(name = "telephone") private String telephone; @Basic(optional = false) @Column(name = "valide") private String valide; @Column(name = "matricule") private String matricule; public DemandeRv() { } public DemandeRv(Long id) { this.id = id; } public DemandeRv(Long id, String valide) { this.id = id; this.valide = valide; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getAdresse() { return adresse; } public void setAdresse(String adresse) { this.adresse = adresse; } public Date getDaterv() { return daterv; } public void setDaterv(Date daterv) { this.daterv = daterv; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Date getNaissance() { return naissance; } public void setNaissance(Date naissance) { this.naissance = naissance; } public String getNom() { return nom; } public void setNom(String nom) { this.nom = nom; } public String getPrenom() { return prenom; } public void setPrenom(String prenom) { this.prenom = prenom; } public String getTelephone() { return telephone; } public void setTelephone(String telephone) { this.telephone = telephone; } public String getValide() { return valide; } public void setValide(String valide) { this.valide = valide; } public String getMatricule() { return matricule; } public void setMatricule(String matricule) { this.matricule = matricule; } @Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof DemandeRv)) { return false; } DemandeRv other = (DemandeRv) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; } @Override public String toString() { return "jpaModel.DemandeRv[ id=" + id + " ]"; } }
package pe.gob.trabajo.repository; import pe.gob.trabajo.domain.Discapate; import org.springframework.stereotype.Repository; import org.springframework.data.jpa.repository.*; import java.util.List; /** * Spring Data JPA repository for the Discapate entity. */ @SuppressWarnings("unused") @Repository public interface DiscapateRepository extends JpaRepository<Discapate, Long> { @Query("select discapate from Discapate discapate where discapate.nFlgactivo = true") List<Discapate> findAll_Activos(); @Query("select discapate from Discapate discapate where discapate.atencion.id=?1 and discapate.nFlgactivo = true") List<Discapate> findListDiscapateById_Atencion(Long id); }
package uk.co.mobsoc.beacons.transientdata; import java.util.ArrayList; import java.util.UUID; import org.bukkit.entity.Player; import uk.co.mobsoc.beacons.storage.TeamData; /** * Transient data containing all recent invites * @author triggerhapp * */ public class InviteData { private static ArrayList<InviteData> invites = new ArrayList<InviteData>(); private static int INDEX = 1; private int index = -1; private UUID invited; private int teamId = -1; private int preTeamId = -1; private int age = 0; /** * Save an invite for a player into a Team or PrelimTeam. One of the team types must be null and the other a valid team or pre-team * @param player * @param td * @param pd */ public InviteData(Player player, TeamData td, PrelimTeam pd){ invited = player.getUniqueId(); if(td != null){ teamId = td.getTeamId(); } if(pd != null){ preTeamId = pd.getIndex(); } setIndex(INDEX); INDEX ++; invites.add(this); } public UUID getInvited() { return invited; } public void setInvited(UUID invited) { this.invited = invited; } public int getTeamId() { return teamId; } public void setTeamId(int teamId) { this.teamId = teamId; } public int getPreTeamId() { return preTeamId; } public void setPreTeamId(int preTeamId) { this.preTeamId = preTeamId; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int getIndex() { return index; } public void setIndex(int index) { this.index = index; } public static InviteData getInvite(int index) { for(InviteData id : invites){ if(id.getIndex() == index){ return id; } } return null; } }
package com.vilio.nlbs.common.service; import com.vilio.nlbs.commonMapper.pojo.NlbsCity; import com.vilio.nlbs.commonMapper.pojo.NlbsDistributor; import com.vilio.nlbs.commonMapper.pojo.NlbsUser; import java.util.List; import java.util.Map; /** * Created by xiezhilei on 2017/1/12. */ public interface CommonService { public String getUUID() throws Exception; public List<NlbsDistributor> selectChildrenListDistributor(String distributorCode) throws Exception; public List<NlbsUser> selectChildrenListUser(String userCode) throws Exception; List<Map> queryAllMaterialTypeList() throws Exception; List<Map> queryAllApplyRecordStatusList() throws Exception; List<NlbsCity> queryAllCity() throws Exception; public NlbsUser queryNlbsUserByUserNoIgnoreStatus(String userNo) throws Exception; public boolean isAdministrator(String userNo, List<String> roleList) throws Exception; }
package com.filiereticsa.arc.augmentepf.models; import android.util.Log; import com.filiereticsa.arc.augmentepf.AppUtils; import com.filiereticsa.arc.augmentepf.activities.ConnectionActivity; import com.filiereticsa.arc.augmentepf.activities.HomePageActivity; import com.filiereticsa.arc.augmentepf.activities.PathConsultationActivity; import com.filiereticsa.arc.augmentepf.localization.UserIndoorLocationCandidate; import com.filiereticsa.arc.augmentepf.managers.FileManager; import com.filiereticsa.arc.augmentepf.managers.HTTP; import com.filiereticsa.arc.augmentepf.managers.HTTPRequestManager; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.Locale; /** * Created by ARC© Team for AugmentEPF project on 07/05/2017. */ public class Path { public static final String DATE = "date"; public static final String DESTINATION_NAME = "destinationName"; public static final String DESTINATION_TYPE = "destinationType"; public static final String X_BEGIN = "xBegin"; public static final String Y_BEGIN = "yBegin"; public static final String FLOOR_BEGIN = "floorBegin"; public static final String RECORD_LIST = "recordList"; public static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; public static final String MUST_TAKE_ELEVATOR = "mustTakeElevator"; public static final String CLOSEST_DEPARTURE_PLACE = "closestDeparturePlace"; public static final String PATHS_JSON = "paths.json"; private static final String TAG = "Ici (Path)"; public static SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DATE_FORMAT, Locale.ENGLISH); private Position departure; private Place closestDeparturePlace; private Place arrival; private ArrayList<Position> path; private boolean mustTakeElevator; private Date departureDate; private Date arrivalDate; private static ArrayList<Path> paths; public static ArrayList<Path> testPath; private JSONObject pathAsJson; static { testPath = new ArrayList<>(); for (int i = 0; i < 10; i++) { Position pos = new Position(0, 0, 0); Position departureTest = new Position(0, 0, 0); Place closestDeparturePlaceTest = new Place("Closes" + i, pos); Place arrivalTest = new Place("ArrName" + i, pos); ArrayList<Position> pathTest = new ArrayList<>(); Date DepDateTest = new Date(System.currentTimeMillis()); Date ArrDateTest = new Date(System.currentTimeMillis()); Path path = new Path( departureTest, closestDeparturePlaceTest, arrivalTest, false, DepDateTest, ArrDateTest ); testPath.add(path); } } private static ArrayList<Path> allPaths; public Path(Position departure, Place closestDeparturePlace, Place arrival, boolean mustTakeElevator, Date departureDate, Date arrivalDate) { this.departure = departure; this.closestDeparturePlace = closestDeparturePlace; this.arrival = arrival; this.mustTakeElevator = mustTakeElevator; this.departureDate = departureDate; this.arrivalDate = arrivalDate; } public Path(Position departure, Place closestDeparturePlace, Place arrival, boolean mustTakeElevator, Date departureDate) { this.departure = departure; this.closestDeparturePlace = closestDeparturePlace; this.arrival = arrival; this.mustTakeElevator = mustTakeElevator; this.departureDate = departureDate; } public Path(JSONObject jsonObject) { this.pathAsJson = jsonObject; try { int xBegin = -1, yBegin = -1, floor = Integer.MAX_VALUE; if (jsonObject.has(X_BEGIN)) { xBegin = jsonObject.getInt(X_BEGIN); } if (jsonObject.has(Y_BEGIN)) { yBegin = jsonObject.getInt(Y_BEGIN); } if (jsonObject.has(FLOOR_BEGIN)) { floor = jsonObject.getInt(FLOOR_BEGIN); } if (xBegin != -1 && yBegin != -1 && floor != Integer.MAX_VALUE) { this.departure = new Position(xBegin, yBegin, floor); } if (jsonObject.has(CLOSEST_DEPARTURE_PLACE)) { String closestDeparturePlaceName = jsonObject.getString(CLOSEST_DEPARTURE_PLACE); this.closestDeparturePlace = Place.getPlaceFromName(closestDeparturePlaceName); } String arrivalPlaceName = jsonObject.getString(DESTINATION_NAME); this.arrival = Place.getPlaceFromName(arrivalPlaceName); String departureDate = jsonObject.getString(DATE); Calendar calendar = Calendar.getInstance(); calendar.setTime(simpleDateFormat.parse(departureDate)); this.departureDate = calendar.getTime(); this.mustTakeElevator = jsonObject.getBoolean(MUST_TAKE_ELEVATOR); } catch (JSONException | ParseException e) { e.printStackTrace(); } } public Position getDeparture() { return departure; } public void setDeparture(Position departure) { this.departure = departure; } public Place getArrival() { return arrival; } public void setArrival(Place arrival) { this.arrival = arrival; } public ArrayList<Position> getPath() { return path; } public void setPath(ArrayList<Position> path) { this.path = path; } public boolean isMustTakeElevator() { return mustTakeElevator; } public void setMustTakeElevator(boolean mustTakeElevator) { this.mustTakeElevator = mustTakeElevator; } public Date getDepartureDate() { return departureDate; } public void setDepartureDate(Date departureDate) { this.departureDate = departureDate; } public Date getArrivalDate() { return arrivalDate; } public void setArrivalDate(Date arrivalDate) { this.arrivalDate = arrivalDate; } public static ArrayList<Path> getPaths() { if (paths == null) { paths = new ArrayList<>(); } return paths; } public static ArrayList<Path> allPaths(){ allPaths = new ArrayList<>(); if(PlannedPath.getPlannedPaths()!= null){ Log.d(TAG, "allPaths: planned "+PlannedPath.getPlannedPaths().size()); allPaths.addAll(PlannedPath.getPlannedPaths()); } if (getPaths()!= null){ Log.d(TAG, "allPaths: path "+Path.getPaths().size()); allPaths.addAll(getPaths()); } return allPaths; } protected JSONObject getJsonFromPath() { JSONObject pathAsJson = new JSONObject(); Date departureDate = this.getDepartureDate(); if(departureDate!= null){ String departureDateString = simpleDateFormat.format(departureDate); try { pathAsJson.put(DATE, departureDateString); } catch (JSONException e) { e.printStackTrace(); } } try { if (this.closestDeparturePlace != null) { pathAsJson.put(CLOSEST_DEPARTURE_PLACE, this.closestDeparturePlace.getName()); } else { pathAsJson.put(CLOSEST_DEPARTURE_PLACE, "Undefined"); } pathAsJson.put(DESTINATION_NAME, this.getArrival().getName()); pathAsJson.put(MUST_TAKE_ELEVATOR, this.isMustTakeElevator()); if (this.departure!= null) { pathAsJson.put(X_BEGIN, this.departure.getPositionX()); pathAsJson.put(Y_BEGIN, this.departure.getPositionX()); pathAsJson.put(FLOOR_BEGIN, this.departure.getFloor()); } } catch (JSONException e) { e.printStackTrace(); } this.pathAsJson = pathAsJson; return pathAsJson; } public static JSONObject getJsonFromPaths() { JSONObject jsonObject = new JSONObject(); JSONArray jsonArray = new JSONArray(); try { for (int i = 0; i < paths.size(); i++) { Path path = paths.get(i); JSONObject currentPath = path.getJsonFromPath(); jsonArray.put(currentPath); } jsonObject.put(RECORD_LIST, jsonArray); } catch (JSONException e) { e.printStackTrace(); } return jsonObject; } private static void loadPathsFromJson(JSONObject jsonObject) { Log.d(TAG, "loadPathsFromJson: "+jsonObject.toString()); if (paths != null) { paths.clear(); } try { String recordList = jsonObject.getString(RECORD_LIST); if (!recordList.equals("null")) { JSONArray jsonArray = jsonObject.getJSONArray(RECORD_LIST); for (int i = 0; i < jsonArray.length(); i++) { JSONObject currentPathJson = jsonArray.getJSONObject(i); Path path = new Path(currentPathJson); if (paths == null) { paths = new ArrayList<>(); } paths.add(path); } } else { loadPathsFromFile(); } } catch (JSONException e) { e.printStackTrace(); } } public static void loadPathsFromFile() { FileManager fileManager = new FileManager(null, PATHS_JSON); try { loadPathsFromJson(new JSONObject(fileManager.readFile())); } catch (JSONException e) { e.printStackTrace(); } } public static void savePaths() { FileManager fileManager = new FileManager(null, PATHS_JSON); fileManager.saveFile(getJsonFromPaths().toString()); } private void sendPathToServer() { JSONObject jsonObject = this.getJsonFromPath(); try { jsonObject.put(DESTINATION_TYPE, this.getArrival().getType()); jsonObject.put(HTTP.ID_USER, ConnectionActivity.idUser); jsonObject.put(HTTP.TOKEN, ConnectionActivity.token); } catch (JSONException e) { e.printStackTrace(); } HTTPRequestManager.doPostRequest( HTTP.RECORD_TRIP_PHP, jsonObject.toString(), HomePageActivity.httpRequestInterface, HTTPRequestManager.PATH); } public static void askForPaths() { JSONObject jsonObject = new JSONObject(); try { jsonObject.put(HTTP.ID_USER, ConnectionActivity.idUser); jsonObject.put(HTTP.TOKEN, ConnectionActivity.token); } catch (JSONException e) { e.printStackTrace(); } HTTPRequestManager.doPostRequest( HTTP.GET_RECORD_PHP, jsonObject.toString(), PathConsultationActivity.httpRequestInterface, HTTPRequestManager.PATH_HISTORY); } public static void onPathRequestDone(String result) { if (result.equals(HTTP.ERROR)) { loadPathsFromFile(); } else { JSONObject jsonObject; try { jsonObject = new JSONObject(result); String state = jsonObject.getString(HTTP.SUCCESS); if (state.equals(HTTP.TRUE)) { loadPathsFromJson(new JSONObject(result)); savePaths(); } else { loadPathsFromFile(); } } catch (JSONException e) { e.printStackTrace(); } } } public static void createNewPath( UserIndoorLocationCandidate departure, Place arrival, SpecificAttribute specificAttribute) { if (departure != null) { ArrayList<Place> sortedPlaces = AppUtils.sortByClosest(Place.getAllPlaces()); Place closestPlace; if (sortedPlaces != null && sortedPlaces.size() > 0) { closestPlace = sortedPlaces.get(0); Path path = new Path( new Position( departure.indexPath.first, departure.indexPath.second, closestPlace.getPosition().getFloor()), closestPlace, arrival, AppUtils.mustTakeElevator(specificAttribute), Calendar.getInstance().getTime() ); getPaths().add(path); savePaths(); path.sendPathToServer(); } } } public Place getClosestDeparturePlace() { return closestDeparturePlace; } }
/* * SE1021 - 021 * Winter 2017 * Lab: Lab 4 Inheritance with Shapes * Name: Rock Boynton * Created: 12/20/17 */ package boyntonrl; import edu.msoe.se1010.winPlotter.WinPlotter; import java.awt.Color; /** * This class represents a Triangle */ public class Triangle extends Shape { protected double base; protected double height; /** * Constructor -- creates the Triangle * @param x - cartesian x-origin of this Triangle * @param y - cartesian x-origin of this Triangle * @param base - base (along x-axis) of this Triangle * @param height - height (along y-axis) of this Triangle * @param color - the java.awt.Color for this Triangle */ public Triangle(double x, double y, double base, double height, Color color) { super(x, y, color); this.base = base; this.height = height; } /** * Draws the Triangle. The origin of the triangle is the lower-left vertex. To draw a triangle, * move to the origin, then draw a line (using WinPlotter's drawTo method) that represents the * base, followed by the lines that represent the sides. * @param plotter reference to a WinPlotter object used for drawing */ public void draw(WinPlotter plotter) { super.setPenColor(plotter); plotter.moveTo(x, y); plotter.drawTo(x + base, y); plotter.drawTo(x + base/2, y + height); plotter.drawTo(x, y); } }
package com.tencent.mm.plugin.luckymoney.f2f.ui; import android.animation.ValueAnimator; import android.animation.ValueAnimator.AnimatorUpdateListener; import android.view.View; class ShuffleView$11 implements AnimatorUpdateListener { final /* synthetic */ ShuffleView kPn; ShuffleView$11(ShuffleView shuffleView) { this.kPn = shuffleView; } public final void onAnimationUpdate(ValueAnimator valueAnimator) { int i = 0; float floatValue = ((Float) valueAnimator.getAnimatedValue()).floatValue(); if (floatValue == 0.0f) { ShuffleView.b(this.kPn).clear(); ShuffleView.c(this.kPn).clear(); while (i < ShuffleView.d(this.kPn)) { ShuffleView.b(this.kPn).add(Float.valueOf(((View) ShuffleView.e(this.kPn).get(i)).getTranslationX())); ShuffleView.c(this.kPn).add(Float.valueOf(((View) ShuffleView.e(this.kPn).get(i)).getTranslationY())); i++; } return; } while (true) { int i2 = i; if (i2 < ShuffleView.d(this.kPn)) { ((View) ShuffleView.e(this.kPn).get(i2)).setTranslationX((((Float) ShuffleView.b(this.kPn).get(i2)).floatValue() * (1.0f - floatValue)) + (this.kPn.sb(i2) * floatValue)); ((View) ShuffleView.e(this.kPn).get(i2)).setTranslationY((((Float) ShuffleView.c(this.kPn).get(i2)).floatValue() * (1.0f - floatValue)) + (this.kPn.sc(i2) * floatValue)); i = i2 + 1; } else { return; } } } }
package ru.task.codemark.util.exceptions; /** * Перечисление ошибок * которые получаются при валидации элементов * в операциях create и update * * @author Evgeniy Kolesnikov * telegram 89616927595 * email evgeniysanich@mail.ru */ public enum ExceptionName { SUCCESS("success: true"), FAILPASSWORD("success: false, errors: Wrong password. " + "You should use minimum a digit and a capital letter! "), NOTUNIQUELOGIN("success: false , errors: " + "Wrong login. Please change it! "), NOLOGIN("success: false, errors: " + "Wrong login. Please register or insert it!"); private final String message; ExceptionName(String message) { this.message = message; } public String getMessage() { return message; } }
package com.didipark.action; import java.io.IOException; import javax.servlet.http.HttpServletResponse; import org.apache.struts2.interceptor.ServletResponseAware; import com.alibaba.fastjson.JSONObject; import com.didipark.dao.CarportDao; import com.didipark.dao.PhotoDao; import com.didipark.pojo.Carport; import com.didipark.pojo.Photo; import com.didipark.utils.FileUtil; import com.didipark.utils.ImageUtil; import com.didipark.utils.MyConstant; import com.opensymphony.xwork2.ActionSupport; public class AddCarportAction extends ActionSupport implements ServletResponseAware { private static final long serialVersionUID = 1L; private HttpServletResponse response; private String data; private String type; private PhotoDao photoDao; private CarportDao carportDao; private int id; private String describe, addr; private int perHoursMoney, num; private double longitude, latitude; public void setDescribe(String describe) { this.describe = describe; } public void setAddr(String addr) { this.addr = addr; } public void setPerHoursMoney(int perHoursMoney) { this.perHoursMoney = perHoursMoney; } public void setNum(int num) { this.num = num; } public void setLongitude(double longitude) { this.longitude = longitude; } public void setLatitude(double latitude) { this.latitude = latitude; } public void setServletResponse(HttpServletResponse response) { this.response = response; } public void setPhotoDao(PhotoDao photoDao) { this.photoDao = photoDao; } public void setCarportDao(CarportDao carportDao) { this.carportDao = carportDao; } public void setId(int id) { this.id = id; } public void setData(String data) { this.data = data; } public void setType(String type) { this.type = type; } public void addCarport() { String imgeName = null; JSONObject json = new JSONObject(); Carport carport = carportDao.saveCarport(describe, addr, perHoursMoney, num, latitude, longitude, id); if (carport != null) { try { imgeName = FileUtil.saveFile(type, data, MyConstant.DOMAIN_IMG); String url = MyConstant.IMAGE_URL + imgeName; //String url2 = MyConstant.IMAGE2_URL + imgeName; // imgeName = FileUtil.saveFile(type, data, MyConstant.carport); //String url = MyConstant.DOMAIN + imgeName; Photo photo = photoDao.savePhoto(url, carport, url); json.put("message", "success"); json.put("carport", carport); json.put("photoUrl", photo.getPhotoUrl()); json.put("photoUrl2", photo.getPhotoUrl2()); } catch (IOException e) { e.printStackTrace(); } } else { json.put("name", "failed"); } try { System.out.println(json.toString()); byte[] jsonBytes = json.toString().getBytes("utf-8"); response.setContentLength(jsonBytes.length); response.getOutputStream().write(jsonBytes); response.getOutputStream().flush(); response.getOutputStream().close(); } 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 edu.eci.arsw.webstore.persistence; import edu.eci.arsw.webstore.model.Auction; import edu.eci.arsw.webstore.model.Message; import edu.eci.arsw.webstore.model.Notification; import edu.eci.arsw.webstore.model.Product; import edu.eci.arsw.webstore.model.Transaction; import edu.eci.arsw.webstore.model.User; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * Clase WebStoreDB que permite realizar consultas sobre la base de datos. * * @author Juan David */ public class WebStoreDB { // Atributos // Conexion Base de datos Heroku private static final String urlDb = "jdbc:postgresql://ec2-34-200-116-132.compute-1.amazonaws.com:5432/dc5qsgdq0jgp20?user=gpyoydzjumspiy&password=a92e5891a1f575b00c5319227c7f2acbadf68c4ef2dc9e1d35e76aab02c4a277"; // Conexion Base de datos Aws // private static final String urlDb = // "jdbc:postgresql://arsw.cu0adiovages.us-east-1.rds.amazonaws.com:5432/arsw?user=arsw&password=arsw1234"; private Connection c; private User u; private Product p; private Auction a; private Transaction t; private Message m; private Notification n; /** * Metodo que permite generar la conexión con la base de datos. */ public void getConnection() { try { c = DriverManager.getConnection(urlDb); } catch (SQLException e) { } } /****/ //// BASE DE DATOS - Consultas de Usuario /****/ /** * Metodo que permite consultar una lista con todos los usarios que estan en la * base de datos. * * @return Retorna una lista de usuarios registrados en la base de datos. */ public List<User> getAllUsers() { List<User> allUsers = new ArrayList<>(); Statement stmt; try { Class.forName("org.postgresql.Driver"); getConnection(); c.setAutoCommit(false); stmt = c.createStatement(); try (ResultSet rs = stmt.executeQuery("SELECT * FROM usr;")) { c.close(); while (rs.next()) { u = new User(rs.getString("useremail"), rs.getString("usserpassword"), rs.getString("ussernickname")); allUsers.add(u); } stmt.close(); } } catch (ClassNotFoundException | SQLException ex) { Logger.getLogger(WebStoreDB.class.getName()).log(Level.SEVERE, null, ex); } return allUsers; } /** * Metodo que permite realizar la adición de un nuevo usario en la base de * datos. * * @param us Es el usuario el cual se quiere agregar a la base de datos. */ public void createNewUser(User us) { Statement stmt; try { Class.forName("org.postgresql.Driver"); getConnection(); c.setAutoCommit(false); stmt = c.createStatement(); String sql = "INSERT INTO usr (userid,usertype,username,userlastname,useremail,usserpassword,usserimage,ussernickname,ussercode,userphone,userbalance,userfeedback,useractive) " + "VALUES ('" + us.getIdUser() + "','user','','','" + us.getUserEmail() + "','" + us.getUserPassword() + "','','" + us.getUserNickname() + "','','0','0','0',false);"; stmt.executeUpdate(sql); stmt.close(); c.commit(); c.close(); } catch (ClassNotFoundException | SQLException ex) { Logger.getLogger(WebStoreDB.class.getName()).log(Level.SEVERE, null, ex); } } /** * Metodo que permite la consulta de un usuario por su userNickName. * * @param userNickname Es el Nickname del usuario. * @return Retorna el usuario correspondiente con el NickName o null si no * encuentra un usuario con ese nickName. */ public User getUserByUserNickname(String userNickname) { PreparedStatement pstmt; try { Class.forName("org.postgresql.Driver"); getConnection(); c.setAutoCommit(false); String sql = "Select * from usr where ussernickname = ?"; pstmt = c.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); pstmt.setString(1, userNickname); try (ResultSet rs = pstmt.executeQuery()) { c.close(); if (rs.next()) { u = new User(rs.getString("useremail"), rs.getString("usserpassword"), rs.getString("ussernickname")); u.setIdUser(rs.getString("userid")); u.setUserType(rs.getString("usertype")); u.setUserName(rs.getString("username")); u.setUserLastName(rs.getString("userlastname")); u.setUserImage(rs.getString("usserimage")); u.setCodeCountry(rs.getString("ussercode")); u.setUserPhone(rs.getString("userphone")); u.setUserBalance(rs.getDouble("userbalance")); u.setUserFeedback(rs.getInt("userfeedback")); u.setUserActive(rs.getBoolean("useractive")); u.setUserAddress(rs.getString("useraddress")); getAllProductsOfUserNickname(userNickname); } pstmt.close(); } return u; } catch (ClassNotFoundException | SQLException ex) { Logger.getLogger(WebStoreDB.class.getName()).log(Level.SEVERE, null, ex); return null; } } public User getUserByEmail(String email) { PreparedStatement pstmt; try { Class.forName("org.postgresql.Driver"); getConnection(); c.setAutoCommit(false); String sql = "Select * from usr where useremail = ?"; pstmt = c.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); pstmt.setString(1, email); try (ResultSet rs = pstmt.executeQuery()) { c.close(); if (rs.next()) { u = new User(rs.getString("useremail"), rs.getString("usserpassword"), rs.getString("ussernickname")); u.setIdUser(rs.getString("userid")); u.setUserType(rs.getString("usertype")); u.setUserName(rs.getString("username")); u.setUserLastName(rs.getString("userlastname")); u.setUserImage(rs.getString("usserimage")); u.setCodeCountry(rs.getString("ussercode")); u.setUserPhone(rs.getString("userphone")); u.setUserBalance(rs.getDouble("userbalance")); u.setUserFeedback(rs.getInt("userfeedback")); u.setUserActive(rs.getBoolean("useractive")); u.setUserAddress(rs.getString("useraddress")); getAllProductsOfUserNickname(u.getUserNickname()); } pstmt.close(); } return u; } catch (ClassNotFoundException | SQLException ex) { Logger.getLogger(WebStoreDB.class.getName()).log(Level.SEVERE, null, ex); return null; } } private String getUserNicknameByUserId(String userId) { PreparedStatement pstmt; String ans = ""; try { Class.forName("org.postgresql.Driver"); getConnection(); c.setAutoCommit(false); String sql = "Select * from usr where userid = ?"; pstmt = c.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); pstmt.setString(1, userId); try (ResultSet rs = pstmt.executeQuery()) { rs.next(); ans = rs.getString("ussernickname"); c.close(); pstmt.close(); } return ans; } catch (ClassNotFoundException | SQLException ex) { Logger.getLogger(WebStoreDB.class.getName()).log(Level.SEVERE, null, ex); } return ans; } public User getUserById(String id) { PreparedStatement pstmt; try { Class.forName("org.postgresql.Driver"); getConnection(); c.setAutoCommit(false); String sql = "Select * from usr where userid = ?"; pstmt = c.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); pstmt.setString(1, id); try (ResultSet rs = pstmt.executeQuery()) { rs.next(); c.close(); u = new User(rs.getString("useremail"), rs.getString("usserpassword"), rs.getString("ussernickname")); u.setIdUser(rs.getString("userid")); u.setUserType(rs.getString("usertype")); u.setUserName(rs.getString("username")); u.setUserLastName(rs.getString("userlastname")); u.setUserImage(rs.getString("usserimage")); u.setCodeCountry(rs.getString("ussercode")); u.setUserPhone(rs.getString("userphone")); u.setUserBalance(rs.getDouble("userbalance")); u.setUserFeedback(rs.getInt("userfeedback")); u.setUserActive(rs.getBoolean("useractive")); u.setUserAddress(rs.getString("useraddress")); getAllProductsOfUserNickname(rs.getString("ussernickname")); pstmt.close(); } return u; } catch (ClassNotFoundException | SQLException ex) { Logger.getLogger(WebStoreDB.class.getName()).log(Level.SEVERE, null, ex); return null; } } /** * Metodo que permite consultar un usuario por email. * * @param user Es el objeto del usuario. */ public void updateUser(User user) { Statement stmt; try { Class.forName("org.postgresql.Driver"); getConnection(); c.setAutoCommit(false); String sql1 = "UPDATE usr SET username = '" + user.getUserName() + "', userlastname = '" + user.getUserLastName() + "', usserimage = '" + user.getUserImage() + "', ussercode = '" + user.getCodeCountry() + "', userphone = '" + user.getUserPhone() + "', userbalance = '" + user.getUserBalance() + "', useraddress = '" + user.getUserAddress() + "', useractive = '" + user.getUserActive() + "', userfeedback = '" + user.getUserFeedback() + "' WHERE userid = '" + user.getIdUser() + "' "; stmt = c.createStatement(); stmt.executeUpdate(sql1); c.commit(); c.close(); } catch (ClassNotFoundException | SQLException ex) { Logger.getLogger(WebStoreDB.class.getName()).log(Level.SEVERE, null, ex); } } /** * Metodo que permite eliminar un usuario de la base de datos. * * @param userNickname Es el nickName del usuario el cual se quiere eliminar. */ public void deleteUserByUserNickname(String userNickname) { Statement stmt; try { u = getUserByUserNickname(userNickname); deleteAllProductByIdOfUserNickname(u.getIdUser()); Class.forName("org.postgresql.Driver"); c.setAutoCommit(false); String sql1 = "DELETE FROM usr WHERE ussernickname = '" + userNickname + "'"; stmt = c.createStatement(); stmt.executeUpdate(sql1); c.commit(); c.close(); } catch (ClassNotFoundException | SQLException ex) { Logger.getLogger(WebStoreDB.class.getName()).log(Level.SEVERE, null, ex); } } /****/ //// BASE DE DATOS - Consultas de Producto /****/ /** * Metodo que permite consular una lista con todos los productos registrados en * el webStore. * * @return Retorna una lista de productos. */ public List<Product> getAllProducts() { List<Product> allProduct = new ArrayList<>(); Statement stmt; try { Class.forName("org.postgresql.Driver"); getConnection(); c.setAutoCommit(false); stmt = c.createStatement(); try (ResultSet rs = stmt.executeQuery("SELECT * FROM product where productauction is null ;")) { c.close(); while (rs.next()) { p = new Product(rs.getString("productname"), rs.getString("productdescription"), rs.getDouble("productprice"), rs.getString("productImage")); p.setProductId(rs.getString("productid")); p.setProductUser(getUserNicknameByUserId(rs.getString("productuser"))); if (getTransactionByProductId(p.getProductId()) == null) { allProduct.add(p); } } stmt.close(); } } catch (ClassNotFoundException | SQLException ex) { Logger.getLogger(WebStoreDB.class.getName()).log(Level.SEVERE, null, ex); } return allProduct; } /** * Metodo que permite consultar todos los productos relacionados a un usuario. * * @param userNickname Es el nickName del usario. * @return Retorna una lista de productos relacionados al usario dado. */ public List<Product> getAllProductsOfUserNickname(String userNickname) { String SQL = "SELECT * FROM product WHERE productuser = ?"; List<Product> allProductUser = new ArrayList<>(); try { if (u == (null)) { u = getUserByUserNickname(userNickname); } getConnection(); ResultSet rs; try (PreparedStatement pstmt = c.prepareStatement(SQL, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE)) { pstmt.setString(1, u.getIdUser()); rs = pstmt.executeQuery(); c.close(); while (rs.next()) { p = new Product(rs.getString("productname"), rs.getString("productdescription"), rs.getDouble("productprice"), rs.getString("productImage")); p.setProductId(rs.getString("productid")); allProductUser.add(p); } // Se Agregan todos los productos al usuario. u.setProducts(allProductUser); } rs.close(); } catch (Exception ex) { Logger.getLogger(WebStoreDB.class.getName()).log(Level.SEVERE, null, ex); } return allProductUser; } public List<Product> getAllProductsOfUserNicknameWithoutAuction(String userNickname) { String SQL = "SELECT * FROM product WHERE productuser = ? and productauction is null"; List<Product> allProductUser = new ArrayList<>(); try { if (u == (null)) { u = getUserByUserNickname(userNickname); } getConnection(); ResultSet rs; try (PreparedStatement pstmt = c.prepareStatement(SQL, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE)) { pstmt.setString(1, u.getIdUser()); rs = pstmt.executeQuery(); c.close(); while (rs.next()) { p = new Product(rs.getString("productname"), rs.getString("productdescription"), rs.getDouble("productprice"), rs.getString("productImage")); p.setProductId(rs.getString("productid")); if (getTransactionByProductId(p.getProductId()) == null) { allProductUser.add(p); } } // Se Agregan todos los productos al usuario. u.setProducts(allProductUser); } rs.close(); } catch (Exception ex) { Logger.getLogger(WebStoreDB.class.getName()).log(Level.SEVERE, null, ex); } return allProductUser; } public Product getProductByIdOfUserNickname(String id) { String SQL = "SELECT * FROM product WHERE productid = ?"; Product product = null; try { getConnection(); ResultSet rs; try (PreparedStatement pstmt = c.prepareStatement(SQL, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE)) { pstmt.setString(1, id); rs = pstmt.executeQuery(); c.close(); while (rs.next()) { p = new Product(rs.getString("productname"), rs.getString("productdescription"), rs.getDouble("productprice"), rs.getString("productImage")); p.setProductId(rs.getString("productid")); product = p; } } rs.close(); } catch (Exception ex) { Logger.getLogger(WebStoreDB.class.getName()).log(Level.SEVERE, null, ex); } return product; } /** * Metodo que permite registrar un nuevo producto en la base de datos. * * @param pd Es el producto que se agregara a la base de datos. * */ public void createNewProduct(Product pd) { Statement stmt; try { Class.forName("org.postgresql.Driver"); getConnection(); c.setAutoCommit(false); stmt = c.createStatement(); String sql = "INSERT INTO product (productid,productname,productdescription,productprice,productuser,productauction,productImage) " + "VALUES ('" + pd.getProductId() + "','" + pd.getProductName() + "','" + pd.getProductDescription() + "','" + pd.getProductPrice() + "','" + pd.getProductUser() + "',null,'" + pd.getProductImage() + "');"; stmt.executeUpdate(sql); stmt.close(); c.commit(); c.close(); } catch (ClassNotFoundException | SQLException ex) { Logger.getLogger(WebStoreDB.class.getName()).log(Level.SEVERE, null, ex); } } /** * Metodo que edita un producto asociado al usuario. * * @param productId Id del producto * @param pd Es el producto. */ public void editProductById(String productId, Product pd) { Statement stmt; try { Class.forName("org.postgresql.Driver"); getConnection(); c.setAutoCommit(false); String sql1 = "UPDATE product SET productname = '" + pd.getProductName() + "', productdescription = '" + pd.getProductDescription() + "' , productprice = '" + pd.getProductPrice() + "' , productImage = '" + pd.getProductImage() + "' WHERE productid = '" + productId + "' "; stmt = c.createStatement(); stmt.executeUpdate(sql1); c.commit(); c.close(); } catch (ClassNotFoundException | SQLException ex) { Logger.getLogger(WebStoreDB.class.getName()).log(Level.SEVERE, null, ex); } } /** * Metodo que elimina un producto asociado al usuario. * * @param id Id del producto * @param idUser Id del usuario. */ public void deleteProductByIdOfUserNickname(String id, String idUser) { Statement stmt; try { Class.forName("org.postgresql.Driver"); getConnection(); c.setAutoCommit(false); String sql1 = "DELETE FROM product WHERE productuser = '" + idUser + "' AND productid = '" + id + "'"; stmt = c.createStatement(); stmt.executeUpdate(sql1); c.commit(); c.close(); } catch (ClassNotFoundException | SQLException ex) { Logger.getLogger(WebStoreDB.class.getName()).log(Level.SEVERE, null, ex); } } /** * Metodo que elimina todos los productos cuando un usuario es eliminado. * * @param idUser Es el id del usuario */ private void deleteAllProductByIdOfUserNickname(String idUser) { Statement stmt; try { Class.forName("org.postgresql.Driver"); getConnection(); c.setAutoCommit(false); // select * from product where productuser = '3' AND productid = '5'; String sql1 = "DELETE FROM product WHERE productuser = '" + idUser + "'"; stmt = c.createStatement(); stmt.executeUpdate(sql1); c.commit(); c.close(); } catch (ClassNotFoundException | SQLException ex) { Logger.getLogger(WebStoreDB.class.getName()).log(Level.SEVERE, null, ex); } } /****/ //// BASE DE DATOS - Consultas de Transaacciones /****/ /** * Metodo que permite consultar una lista con todos las transacciones que estan * en la base de datos. * * @return Retorna una lista de transacciones registradas en la base de datos. */ public List<Transaction> getAllTransactions() { List<Transaction> allTransactions = new ArrayList<>(); Statement stmt; try { Class.forName("org.postgresql.Driver"); getConnection(); c.setAutoCommit(false); stmt = c.createStatement(); try (ResultSet rs = stmt.executeQuery("SELECT * FROM transaction;")) { c.close(); while (rs.next()) { t = new Transaction(rs.getString("buyer"), rs.getString("seller"), rs.getString("product")); t.setTransactionId(rs.getString("transactionid")); t.setTransactionPrice(rs.getDouble("transactionprice")); t.setTransactionDate(rs.getString("transactiondate")); t.setTransactionActive(rs.getBoolean("transactionactive")); t.setTransactionDateEnd(rs.getString("transactiondateend")); t.setTransactionState(rs.getString("transactionstate")); allTransactions.add(t); } stmt.close(); } } catch (ClassNotFoundException | SQLException ex) { Logger.getLogger(WebStoreDB.class.getName()).log(Level.SEVERE, null, ex); } return allTransactions; } /** * Metodo que permite la consulta de un transaccion por su Id. * * @param transactionId Es el Id de la transaccion. * @return Retorna la tracsaccion correspondiente con el iD o null si no * encuentra la transaccion con ese Id. */ public Transaction getTransactionById(String transactionId) { PreparedStatement pstmt; t = null; try { Class.forName("org.postgresql.Driver"); getConnection(); c.setAutoCommit(false); String sql = "Select * from transaction where transactionid = ?"; pstmt = c.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); pstmt.setString(1, transactionId); try (ResultSet rs = pstmt.executeQuery()) { c.close(); if (rs.next()) { t = new Transaction(rs.getString("buyer"), rs.getString("seller"), rs.getString("product")); t.setTransactionId(rs.getString("transactionid")); t.setTransactionPrice(rs.getDouble("transactionprice")); t.setTransactionDate(rs.getString("transactiondate")); t.setTransactionActive(rs.getBoolean("transactionactive")); t.setTransactionDateEnd(rs.getString("transactiondateend")); t.setTransactionState(rs.getString("transactionstate")); } pstmt.close(); } } catch (ClassNotFoundException | SQLException ex) { Logger.getLogger(WebStoreDB.class.getName()).log(Level.SEVERE, null, ex); } return t; } public Transaction getTransactionByProductId(String productId) { PreparedStatement pstmt; t = null; try { Class.forName("org.postgresql.Driver"); getConnection(); c.setAutoCommit(false); String sql = "Select * from transaction where product = ?"; pstmt = c.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); pstmt.setString(1, productId); try (ResultSet rs = pstmt.executeQuery()) { c.close(); if (rs.next()) { t = new Transaction(rs.getString("buyer"), rs.getString("seller"), rs.getString("product")); t.setTransactionId(rs.getString("transactionid")); t.setTransactionPrice(rs.getDouble("transactionprice")); t.setTransactionDate(rs.getString("transactiondate")); t.setTransactionActive(rs.getBoolean("transactionactive")); t.setTransactionDateEnd(rs.getString("transactiondateend")); t.setTransactionState(rs.getString("transactionstate")); } pstmt.close(); } } catch (ClassNotFoundException | SQLException ex) { Logger.getLogger(WebStoreDB.class.getName()).log(Level.SEVERE, null, ex); } return t; } /** * Este metodo permite obtener las transacciones de un usuario * * @param userId id del usuario * @return lista de transacciones */ public List<Transaction> getTransactionsOfUserById(String userId) { List<Transaction> allTransactions = new ArrayList<>(); PreparedStatement pstmt; try { Class.forName("org.postgresql.Driver"); getConnection(); c.setAutoCommit(false); String sql = "Select * from transaction where seller = ? OR buyer = ?"; pstmt = c.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); pstmt.setString(1, userId); pstmt.setString(2, userId); try (ResultSet rs = pstmt.executeQuery()) { c.close(); while (rs.next()) { t = new Transaction(rs.getString("buyer"), rs.getString("seller"), rs.getString("product")); t.setTransactionId(rs.getString("transactionid")); t.setTransactionPrice(rs.getDouble("transactionprice")); t.setTransactionDate(rs.getString("transactiondate")); t.setTransactionActive(rs.getBoolean("transactionactive")); t.setTransactionDateEnd(rs.getString("transactiondateend")); t.setTransactionState(rs.getString("transactionstate")); allTransactions.add(t); } pstmt.close(); } return allTransactions; } catch (ClassNotFoundException | SQLException ex) { Logger.getLogger(WebStoreDB.class.getName()).log(Level.SEVERE, null, ex); return null; } } /** * Metodo que permite realizar la adición de una nueva transaccion en la base de * datos. * * @param tr Es la transaccion el cual se quiere agregar a la base de datos. */ public void createNewtransaction(Transaction tr) { Statement stmt; try { Class.forName("org.postgresql.Driver"); getConnection(); c.setAutoCommit(false); stmt = c.createStatement(); String sql = "INSERT INTO transaction (transactionid,transactionprice,transactiondate,transactiondateend,transactionactive,buyer,seller,product,transactionstate) " + "VALUES ('" + tr.getTransactionId() + "','" + tr.getTransactionPrice() + "','" + tr.getTransactionDate() + "','" + tr.getTransactionDateEnd() + "','" + tr.getTransactionActive() + "', '" + tr.getBuyer() + "','" + tr.getSeller() + "','" + tr.getProduct() + "','" + tr.getTransactionState() + "');"; stmt.executeUpdate(sql); stmt.close(); c.commit(); c.close(); } catch (ClassNotFoundException | SQLException ex) { Logger.getLogger(WebStoreDB.class.getName()).log(Level.SEVERE, null, ex); } } public void updateTransaction(Transaction tr){ Statement stmt; try { Class.forName("org.postgresql.Driver"); getConnection(); c.setAutoCommit(false); String sql1 = "UPDATE transaction SET transactionstate = '" + tr.getTransactionState() + "', transactionactive = '" + tr.getTransactionActive() +"' , transactionDateEnd = '" + tr.getTransactionDateEnd() +"' WHERE transactionid = '" + tr.getTransactionId() + "'"; stmt = c.createStatement(); stmt.executeUpdate(sql1); c.commit(); c.close(); } catch (ClassNotFoundException | SQLException ex) { Logger.getLogger(WebStoreDB.class.getName()).log(Level.SEVERE, null, ex); } } public void deleteTransactionById(String transactionId) { Statement stmt; try { Class.forName("org.postgresql.Driver"); getConnection(); c.setAutoCommit(false); String sql1 = "DELETE FROM transaction WHERE transactionid = '" + transactionId + "'"; stmt = c.createStatement(); stmt.executeUpdate(sql1); c.commit(); c.close(); } catch (ClassNotFoundException | SQLException ex) { Logger.getLogger(WebStoreDB.class.getName()).log(Level.SEVERE, null, ex); } } /****/ //// BASE DE DATOS - Consultas de Mensajes /****/ /** * * @param transactionId * @return */ public List<Message> getMessagesByTransactionId(String transactionId) { String SQL = "SELECT * FROM message WHERE messagetransaction = ?"; List<Message> allMessageTransaction = new ArrayList<>(); try { getConnection(); ResultSet rs; try (PreparedStatement pstmt = c.prepareStatement(SQL, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE)) { pstmt.setString(1, transactionId); rs = pstmt.executeQuery(); c.close(); while (rs.next()) { m = new Message(rs.getString("messagetransaction"), rs.getString("messageuser"), rs.getString("messagedata"), rs.getString("messageuserimage")); allMessageTransaction.add(m); } } rs.close(); } catch (Exception ex) { Logger.getLogger(WebStoreDB.class.getName()).log(Level.SEVERE, null, ex); } return allMessageTransaction; } /** * Metodo que permite registrar un nuevo mensaje en la base de datos. * * @param msg Es el producto que se agregara a la base de datos. * */ public void createNewMessage(Message msg) { Statement stmt; try { Class.forName("org.postgresql.Driver"); getConnection(); c.setAutoCommit(false); stmt = c.createStatement(); String sql = "INSERT INTO message (messageid,messagetransaction,messageuser,messagedata,messageuserimage) " + "VALUES ('" + msg.getId() + "','" + msg.getIdTransaction() + "','" + msg.getUser() + "','" + msg.getData() + "','" + msg.getUserImage() + "');"; stmt.executeUpdate(sql); stmt.close(); c.commit(); c.close(); } catch (ClassNotFoundException | SQLException ex) { Logger.getLogger(WebStoreDB.class.getName()).log(Level.SEVERE, null, ex); } } /****/ //// BASE DE DATOS - Consultas de Subastas /****/ /** * Metodo que permite consultar todas las subastas de la pagina web. * * @return Retorna una lista con todas las subastas que hay en la pagina. */ public List<Auction> getAllAuctions() { List<Auction> allAuctions = new ArrayList<>(); Statement stmt; try { Class.forName("org.postgresql.Driver"); getConnection(); c.setAutoCommit(false); stmt = c.createStatement(); try (ResultSet rs = stmt.executeQuery("SELECT * FROM auction;")) { c.close(); while (rs.next()) { a = new Auction(rs.getDouble("auctioninitprice"), rs.getString("auctiondate"), rs.getString("auctiondatefinal"), rs.getInt("auctiontimetowait"), rs.getInt("auctiontype"), rs.getBoolean("auctionactive"), rs.getString("seller"), rs.getString("product"), rs.getString("auctionstatus"), rs.getString("productname")); a.setAuctionId(rs.getString("auctionid")); a.setBuyers(getAllBuyersInAuction(a.getAuctionId())); allAuctions.add(a); } stmt.close(); } } catch (ClassNotFoundException | SQLException ex) { Logger.getLogger(WebStoreDB.class.getName()).log(Level.SEVERE, null, ex); } return allAuctions; } public List<Auction> getAuctionsByUsername(String username) { List<Auction> allAuctionsByUsername = new ArrayList<>(); PreparedStatement pstmt; try { Class.forName("org.postgresql.Driver"); getConnection(); c.setAutoCommit(false); String sql = "Select * from auction where seller = ? "; pstmt = c.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); pstmt.setString(1, username); try (ResultSet rs = pstmt.executeQuery()) { c.close(); while (rs.next()) { a = new Auction(rs.getDouble("auctioninitprice"), rs.getString("auctiondate"), rs.getString("auctiondatefinal"), rs.getInt("auctiontimetowait"), rs.getInt("auctiontype"), rs.getBoolean("auctionactive"), rs.getString("seller"), rs.getString("product"), rs.getString("auctionstatus"), rs.getString("productname")); a.setAuctionId(rs.getString("auctionid")); a.setBuyers(getAllBuyersInAuction(a.getAuctionId())); allAuctionsByUsername.add(a); } pstmt.close(); } } catch (ClassNotFoundException | SQLException ex) { Logger.getLogger(WebStoreDB.class.getName()).log(Level.SEVERE, null, ex); } return allAuctionsByUsername; } /** * Metodo que permite realizar la consulade de subasta por id. * * @param auctionId Es el id de la subasta. * @return Retorna la subasta correspondiente al id. */ public Auction getAuctionById(String auctionId) { PreparedStatement pstmt; a = null; try { Class.forName("org.postgresql.Driver"); getConnection(); c.setAutoCommit(false); String sql = "Select * from auction where auctionid = ?"; pstmt = c.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); pstmt.setString(1, auctionId); try (ResultSet rs = pstmt.executeQuery()) { c.close(); if (rs.next()) { a = new Auction(rs.getDouble("auctioninitprice"), rs.getString("auctiondate"), rs.getString("auctiondatefinal"), rs.getInt("auctiontimetowait"), rs.getInt("auctiontype"), rs.getBoolean("auctionactive"), rs.getString("seller"), rs.getString("product"), rs.getString("auctionstatus"), rs.getString("productname")); a.setAuctionId(rs.getString("auctionid")); a.setBuyers(getAllBuyersInAuction(a.getAuctionId())); } pstmt.close(); } } catch (ClassNotFoundException | SQLException ex) { Logger.getLogger(WebStoreDB.class.getName()).log(Level.SEVERE, null, ex); } return a; } /** * Metodo que permite crear la subasta en la base de datos. * * @param au Es la subasta que se va a agregar a la base de datos. */ public void createNewAuction(Auction au) { Statement stmt; try { Class.forName("org.postgresql.Driver"); getConnection(); c.setAutoCommit(false); stmt = c.createStatement(); String sql = "INSERT INTO auction (auctionid,auctioninitprice,auctioncurrentprice,auctionfinalprice,auctiondate,auctiondatefinal,auctiontimetowait,auctiontype,auctionactive,seller,product,auctionstatus,productname) " + "VALUES ('" + au.getAuctionId() + "','" + au.getAuctionInitPrice() + "','" + au.getAuctionCurrentPrice() + "','" + au.getAuctionFinalPrice() + "','" + au.getAuctionDate() + "','" + au.getAuctionDateFinal() + "','" + au.getAuctionTimeToWait() + "','" + au.getAuctionType() + "','" + au.isAuctionActive() + "','" + au.getSellerId() + "','" + au.getProductId() + "','" + au.getAuctionStatus() + "','" + au.getProductName() + "');"; stmt.executeUpdate(sql); stmt.close(); c.commit(); c.close(); } catch (ClassNotFoundException | SQLException ex) { Logger.getLogger(WebStoreDB.class.getName()).log(Level.SEVERE, null, ex); } } /** * Metodo que permite eliminar una subasta de la base de datos. * * @param auctionId Es el id de la subasta que se quiere eliminar. */ public void deleteAuctionById(String auctionId) { Statement stmt; try { Class.forName("org.postgresql.Driver"); getConnection(); c.setAutoCommit(false); String sql1 = "DELETE FROM auction WHERE auctionid = '" + auctionId + "'"; stmt = c.createStatement(); stmt.executeUpdate(sql1); c.commit(); c.close(); } catch (ClassNotFoundException | SQLException ex) { Logger.getLogger(WebStoreDB.class.getName()).log(Level.SEVERE, null, ex); } } /** * Metodo que permite eliminar todos los participantes en la subasta. * * @param auctionId Es el id de la subasta. */ public void deleteBuyersInAuction(String auctionId) { Statement stmt; try { Class.forName("org.postgresql.Driver"); getConnection(); c.setAutoCommit(false); String sql1 = "DELETE FROM buyers WHERE auction = '" + auctionId + "'"; stmt = c.createStatement(); stmt.executeUpdate(sql1); c.commit(); c.close(); } catch (ClassNotFoundException | SQLException ex) { Logger.getLogger(WebStoreDB.class.getName()).log(Level.SEVERE, null, ex); } } public void addUsersInAuction(String auctionId, String userId) { Statement stmt; try { Class.forName("org.postgresql.Driver"); getConnection(); c.setAutoCommit(false); stmt = c.createStatement(); String sql = "INSERT INTO buyers (auction,buyer) " + "VALUES ('" + auctionId + "','" + userId + "');"; stmt.executeUpdate(sql); stmt.close(); c.commit(); c.close(); } catch (ClassNotFoundException | SQLException ex) { Logger.getLogger(WebStoreDB.class.getName()).log(Level.SEVERE, null, ex); } } private List<User> getAllBuyersInAuction(String auctionId) { List<User> allUserInAuction = new ArrayList<>(); PreparedStatement pstmt; try { Class.forName("org.postgresql.Driver"); getConnection(); c.setAutoCommit(false); String sql = "Select * from buyers where auction = ?"; pstmt = c.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); pstmt.setString(1, auctionId); try (ResultSet rs = pstmt.executeQuery()) { c.close(); while (rs.next()) { u = getUserById(rs.getString("buyer")); allUserInAuction.add(u); } pstmt.close(); } } catch (ClassNotFoundException | SQLException ex) { Logger.getLogger(WebStoreDB.class.getName()).log(Level.SEVERE, null, ex); } return allUserInAuction; } // ######################### /// NOTIFICACIONES // ########################## /** * Metodo que permite realizar la adición de una nueva notificacion en la base de * datos. * * @param noti Es la notificacion que se quiere agregar a la base de datos. */ public void createNewNotification(Notification noti) { Statement stmt = null; try { Class.forName("org.postgresql.Driver"); getConnection(); c.setAutoCommit(false); stmt = c.createStatement(); String sql = "INSERT INTO notification " + "VALUES ('" + noti.getNotificationId() + "','" + noti.getNotificationDestination() + "','" + noti.getNotificationMessage() + "','" + noti.getNotificationUrl() + "','" + noti.getNotificationDate() + "','" + noti.getNotificationSend() + "', false ,'" + noti.getNotificationFunction() + "');"; stmt.executeUpdate(sql); stmt.close(); c.commit(); c.close(); } catch (ClassNotFoundException | SQLException ex) { Logger.getLogger(WebStoreDB.class.getName()).log(Level.SEVERE, null, ex); } } /** * Metodo que permite consultar todas las notificaciones de un usuario * @param nickname Es el nickname del usario. * @return Retorna una lista con las notificaciones del usuario. */ public List<Notification> getNotificationsByNickname(String nickname) { ArrayList<Notification> allNotificationsByNickname= new ArrayList<>(); PreparedStatement pstmt; try { Class.forName("org.postgresql.Driver"); getConnection(); c.setAutoCommit(false); String sql = "Select * from notification where notificationdestination = ? "; pstmt = c.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); pstmt.setString(1, nickname); try (ResultSet rs = pstmt.executeQuery()) { c.close(); while (rs.next()) { n = new Notification(rs.getString("notificationmessage"),rs.getString("norificationdate"), rs.getString("notificationdestination"), rs.getString("notificationsend"), rs.getString("notificationurl"), rs.getString("notificationfunction"), rs.getBoolean("notificationviewed")); n.setNotificationId(rs.getString("notificationid")); allNotificationsByNickname.add(n); } pstmt.close(); } } catch (ClassNotFoundException | SQLException ex) { Logger.getLogger(WebStoreDB.class.getName()).log(Level.SEVERE, null, ex); } return allNotificationsByNickname; } /** * Metodo que permite realizar la consulta de una notificacion por ID * @param notificationId Es el id de la notificacion. * @return Retorna la notificacion correspondiente al id. */ public Notification getNotificationsById(String notificationId) { PreparedStatement pstmt; n = null; try { Class.forName("org.postgresql.Driver"); getConnection(); c.setAutoCommit(false); String sql = "Select * from notification where notificationid = ? "; pstmt = c.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); pstmt.setString(1, notificationId); try (ResultSet rs = pstmt.executeQuery()) { c.close(); if(rs.next()) { n = new Notification(rs.getString("notificationmessage"),rs.getString("norificationdate"), rs.getString("notificationdestination"), rs.getString("notificationsend"), rs.getString("notificationurl"), rs.getString("notificationfunction"), rs.getBoolean("notificationviewed")); n.setNotificationId(rs.getString("notificationid")); } pstmt.close(); } } catch (ClassNotFoundException | SQLException ex) { Logger.getLogger(WebStoreDB.class.getName()).log(Level.SEVERE, null, ex); } return n; } /** * Metodo que permite cambiar el estado de la notificacion, solo debe cambiar el estado de notificationViewed * @param viewed Es el nuevo valor de viewed * @param notificationId Es el id de la notificacion. */ public void changeNotificationStatus(boolean viewed, String notificationId){ Statement stmt; try { Class.forName("org.postgresql.Driver"); getConnection(); c.setAutoCommit(false); String sql1 = "UPDATE notification SET notificationviewed = '" + viewed + "' WHERE notificationid = '" + notificationId + "'"; stmt = c.createStatement(); stmt.executeUpdate(sql1); c.commit(); c.close(); } catch (ClassNotFoundException | SQLException ex) { Logger.getLogger(WebStoreDB.class.getName()).log(Level.SEVERE, null, ex); } } /** * Metodo que permite qur permite eliminar una notificaion * @param notificationId Es el id de la notificacion */ public void deleteNotificationById(String notificationId){ Statement stmt; try { Class.forName("org.postgresql.Driver"); getConnection(); c.setAutoCommit(false); String sql1 = "DELETE FROM notification WHERE notificationid = '" + notificationId + "'"; stmt = c.createStatement(); stmt.executeUpdate(sql1); c.commit(); c.close(); } catch (ClassNotFoundException | SQLException ex) { Logger.getLogger(WebStoreDB.class.getName()).log(Level.SEVERE, null, ex); } } }
package dev.etna.jabberclient.utils; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import java.io.ByteArrayOutputStream; public class Drawables { public static byte[] getDrawableAsByteArray(Context context, int drawableID, Bitmap.CompressFormat format) throws Exception { Bitmap bitmap; BitmapDrawable bitmapDrawable; Drawable drawable; Resources resources; ByteArrayOutputStream outStream; resources = context.getResources(); drawable = resources.getDrawable(drawableID, null); bitmapDrawable = (BitmapDrawable) drawable; bitmap = bitmapDrawable.getBitmap(); outStream = new ByteArrayOutputStream(); bitmap.compress(format, 100, outStream); return outStream.toByteArray(); } }
/* * Created on Mar 9, 2006 * * To change the template for this generated file go to * Window - Preferences - Java - Code Generation - Code and Comments */ package com.ibm.jikesbt; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import com.ibm.jikesbt.BT_Repository.LoadLocation; public class BT_RuntimeParamAnnotationsAttribute extends BT_Attribute { public static final String RUNTIME_VISIBLE_PARAMETER_ANNOTATIONS_ATTRIBUTE_NAME = "RuntimeVisibleParameterAnnotations"; public static final String RUNTIME_INVISIBLE_PARAMETER_ANNOTATIONS_ATTRIBUTE_NAME = "RuntimeInvisibleParameterAnnotations"; BT_AnnotationArray parameterAnnotations[]; private String name; public BT_RuntimeParamAnnotationsAttribute(byte data[], BT_ConstantPool pool, String name, BT_Method method, LoadLocation loadedFrom) throws BT_AnnotationAttributeException { super(method, loadedFrom); this.name = name; try { ByteArrayInputStream bais = new ByteArrayInputStream(data); DataInputStream dis = new DataInputStream(bais); int numParameters = dis.readUnsignedByte(); // AKA number_of_classes parameterAnnotations = new BT_AnnotationArray[numParameters]; try { for(int i=0; i<parameterAnnotations.length; i++) { BT_AnnotationArray parameterAnnotation = new BT_AnnotationArray(); parameterAnnotation.read(name, dis, pool); parameterAnnotations[i] = parameterAnnotation; } if(data.length != getLength()) { throw new BT_AnnotationAttributeException(getName(), Messages.getString("JikesBT.{0}_attribute_length_2", name)); } } catch(BT_ConstantPoolException e) { throw new BT_AnnotationAttributeException(getName(), e); } catch(BT_DescriptorException e) { throw new BT_AnnotationAttributeException(getName(), e); } } catch(IOException e) { throw new BT_AnnotationAttributeException(getName(), e); } } void write(DataOutputStream dos, BT_ConstantPool pool) throws IOException { dos.writeShort(pool.indexOfUtf8(name)); // attribute_name_index dos.writeInt(getLength()); // attribute_length dos.writeByte(parameterAnnotations.length); // number_of_classes for (int i = 0; i < parameterAnnotations.length; ++i) { // Per element parameterAnnotations[i].write(dos, pool); } } void dereference(BT_Repository rep) throws BT_AnnotationAttributeException { try { for(int i=0; i<parameterAnnotations.length; i++) { parameterAnnotations[i].dereference(rep, this); } } catch(BT_DescriptorException e) { throw new BT_AnnotationAttributeException(getName(), e); } } void remove() { for(int i=0; i<parameterAnnotations.length; i++) { parameterAnnotations[i].remove(this); } super.remove(); } /** * Undo any reference to the given item. */ void removeReference(BT_Item reference) { for(int i=0; i<parameterAnnotations.length; i++) { parameterAnnotations[i].removeReference(this, reference); } } public void resolve(BT_ConstantPool pool) { pool.indexOfUtf8(getName()); for(int i=0; i<parameterAnnotations.length; i++) { parameterAnnotations[i].resolve(pool); } } /** * @return the byte length of this attribute excluding the initial 6 bytes */ int getLength() { int length = 1; for(int i=0; i<parameterAnnotations.length; i++) { length += parameterAnnotations[i].getLength(); } return length; } public String getName() { return name; } public String toString() { return Messages.getString("JikesBT.{0}_<{1}_bytes>", new Object[] {name, Integer.toString(getLength())}); } }
package com.example.demo.Repository; import com.example.demo.Model.Customer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Repository; import java.util.List; @Repository public class CustomerRepo { @Autowired JdbcTemplate template; //All out SQL, that we run against our DB public List<Customer> fetchAll(){ String sql = "SELECT customer_id,cus_first_name,cus_last_name,driver_licence,street,house_num,city,zip_code FROM address " + "JOIN location ON address.location_id = location.location_id " + "JOIN customer ON customer.address_id = address.address_id"; RowMapper<Customer> rowMapper = new BeanPropertyRowMapper<>(Customer.class); return template.query(sql,rowMapper ); } public Customer addCustomer(Customer c){ String sql1 = "INSERT INTO location (city,zip_code) VALUES (?,?)"; template.update(sql1, c.getCity(),c.getZip_code()); String sql2 = "SELECT @location_id := last_insert_id()"; template.execute(sql2); String sql3 = "INSERT INTO address(street,house_num,location_id) VALUES (?,?,@location_id)"; template.update(sql3,c.getStreet(),c.getHouse_num()); String sql4 = "SELECT @address_id := last_insert_id()"; template.execute(sql4); String sql5 = "INSERT INTO customer (customer_id,cus_first_name, cus_last_name, driver_licence,address_id) VALUES (@address_id,?,?,?,@address_id)"; template.update(sql5, c.getCus_first_name(), c.getCus_last_name(), c.getDriver_licence()); String sql6 = "UPDATE LOCATION SET address_id = @address_id WHERE location_id = @location_id;"; template.execute(sql6); return null; } public Customer findCustomerById(int customer_id){ String sql ="SELECT customer_id,cus_first_name,cus_last_name,driver_licence,street,house_num,city,zip_code FROM customer " + "JOIN address ON customer.address_id = address.address_id " + "JOIN location ON address.location_id = location.location_id WHERE customer_id = ?"; RowMapper<Customer> rowMapper = new BeanPropertyRowMapper<>(Customer.class); Customer c = template.queryForObject(sql,rowMapper, customer_id); return c; } public Boolean deleteCustomer(int customer_id){ String sql = "DELETE FROM customer WHERE customer_id = ?"; template.update(sql,customer_id); String sql2 = "DELETE FROM address WHERE address_id = ?"; template.update(sql2,customer_id); String sql3 = "DELETE FROM location WHERE address_id = ?"; return template.update(sql3,customer_id) < 0; } public Customer updateCustomer(int customer_id, Customer c){ String sql = "UPDATE customer SET cus_first_name = ?, cus_last_name = ?, driver_licence = ? WHERE customer_id = ?"; template.update(sql,c.getCus_first_name(),c.getCus_last_name(),c.getDriver_licence(),c.getCustomer_id()); String sql1 = "UPDATE address SET street = ?, house_num = ? WHERE address_id = ?"; template.update(sql1,c.getStreet(),c.getHouse_num(),c.getCustomer_id()); String sql2 = "UPDATE location SET city = ?, zip_code = ? WHERE address_id = ?"; template.update(sql2,c.getCity(),c.getZip_code(),c.getCustomer_id()); return null; } }
package com.rgsj3.sebbs.service; import com.rgsj3.sebbs.domain.Result; import com.rgsj3.sebbs.repository.UserRepository; import org.springframework.stereotype.Service; import org.springframework.ui.Model; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; @Service public class UserService { @Resource UserRepository userRepository; public Result login(String name, String password, HttpServletRequest httpServletRequest) { var userList = userRepository.findByName(name); if (userList.size() == 0) { return Result.error(1, "用户名错误"); } else { var user = userList.get(0); if (user.getPassword().equals(password)) { var session = httpServletRequest.getSession(); session.setAttribute("user", user); return Result.success(); } else { return Result.error(1, "密码错误"); } } } public Result logout(HttpServletRequest httpServletRequest) { httpServletRequest.getSession().removeAttribute("user"); return Result.success(); } public void loginUser(Model model, HttpServletRequest httpServletRequest) { var session = httpServletRequest.getSession(); if (session.getAttribute("user") != null) { model.addAttribute("user", session.getAttribute("user")); } else { model.addAttribute("user", null); } } public void courseManagement(Model model, HttpServletRequest httpServletRequest){ User user = (User) httpServletRequest.getSession().getAttribute("user"); List<Course> courseList = courseRepository.findAllByTeacherIs(user); for (Course c:courseList){ Integer num = studentCourseRepository.countByCourse(c); c.setStuNumber(num); courseRepository.save(c); } model.addAttribute("courseList",courseList); } }
package com.neo; import java.util.Properties; import kafka.javaapi.producer.Producer; import kafka.producer.KeyedMessage; import kafka.producer.ProducerConfig; import org.apache.flume.Channel; import org.apache.flume.Context; import org.apache.flume.Event; import org.apache.flume.EventDeliveryException; import org.apache.flume.Transaction; import org.apache.flume.conf.Configurable; import org.apache.flume.sink.AbstractSink; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class KafkaSink extends AbstractSink implements Configurable { private static final Logger logger = LoggerFactory.getLogger(KafkaSink.class); private String topic; private Producer<String, String> producer; @Override public Status process() throws EventDeliveryException { Channel channel = getChannel(); Transaction tx = channel.getTransaction(); try { tx.begin(); Event e = channel.take(); if (e == null) { tx.rollback(); return Status.BACKOFF; } KeyedMessage<String, String> data = new KeyedMessage<String, String>(topic, new String(e.getBody())); producer.send(data); logger.info("Message: {}" + new String(e.getBody())); tx.commit(); return Status.READY; } catch (Exception e) { logger.error("KafkaSinkException:{}", e); tx.rollback(); return Status.BACKOFF; } finally { tx.close(); } } @Override public void configure(Context context) { topic = "kafka-flume"; Properties props = new Properties(); props.setProperty("metadata.broker.list", "GS01:9092"); props.setProperty("serializer.class", "kafka.serializer.StringEncoder"); // props.setProperty("producer.type", "async"); // props.setProperty("batch.num.messages", "1"); props.put("request.required.acks", "1"); ProducerConfig config = new ProducerConfig(props); producer = new Producer<String, String>(config); } }
package com.mango.leo.zsproject.datacenter.fragments; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.mango.leo.zsproject.R; /** * Created by admin on 2018/5/11. */ public class ProjectFragment extends android.support.v4.app.Fragment { @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = LayoutInflater.from(getActivity()).inflate(R.layout.project, container, false); return view; } }
package org.mvirtual.util.lang; import java.util.Map; import java.util.HashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @author Kiyoshi Murata */ public class TemplateString { private String template; private String substitutionOnMissing; public TemplateString() { template = ""; substitutionOnMissing = "?"; } public TemplateString(String t) { template = t; substitutionOnMissing = "?"; } /** * Constructor. * @param t Template string. * @param s Default substitution string when no substitution string is given. */ public TemplateString(String t, String s) { template = t; substitutionOnMissing = s; } public String substitute(String[] keys, String[] values) { int i = 0; HashMap<String, String> map = new HashMap<String, String>(); for (String key : keys) { String value; if (i > values.length) { value = ""; } else { value = values[i]; } map.put(key, value); i++; } return substitute(map); } public String substitute(Map<String, String> substitutions) { Pattern p = Pattern.compile("\\$\\{(\\w+)\\}"); Matcher m = p.matcher(template); StringBuffer result = new StringBuffer(); int s = 0; while (m.find()) { String sub = substitutions.get(m.group(1)); if (sub == null) { sub = substitutionOnMissing; } result.append(template, s, m.start()); result.append(sub); s = m.end(); } result.append(template, s, template.length()); return result.toString(); } @Override public String toString() { return template; } }
package com.codeapin.dicodingmovieapp.ui.searchmovie; import android.os.Bundle; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.widget.SearchView; import com.codeapin.dicodingmovieapp.R; import com.codeapin.dicodingmovieapp.data.remote.model.ApiResponse; import com.codeapin.dicodingmovieapp.data.remote.model.MovieItem; import com.codeapin.dicodingmovieapp.data.remote.service.ApiClient; import com.codeapin.dicodingmovieapp.ui.moviedetails.MovieDetailActivity; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.schedulers.Schedulers; public class SearchMovieActivity extends AppCompatActivity { private static final String TAG = SearchMovieActivity.class.getSimpleName(); public static final String EXTRA_MOVIE_LIST = "MOVIE_LIST"; @BindView(R.id.sv_movies) SearchView svMovies; @BindView(R.id.rv_popular_movie) RecyclerView rvPopularMovie; @BindView(R.id.sr_movie_search) SwipeRefreshLayout srMovieSearch; private SearchMovieAdapter searchMoviewAdapter; private CompositeDisposable compositeDisposable = new CompositeDisposable(); private ApiResponse apiResponse; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_search_movie); ButterKnife.bind(this); setupRecyclerView(); svMovies.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { retrieveItems(query); return true; } @Override public boolean onQueryTextChange(String newText) { return false; } }); if (savedInstanceState != null) { apiResponse = savedInstanceState.getParcelable(EXTRA_MOVIE_LIST); if (apiResponse != null) { searchMoviewAdapter.setData(apiResponse.getResults()); } } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putParcelable(EXTRA_MOVIE_LIST, apiResponse); } private void retrieveItems(String q) { ApiClient.getApiService().getMovies(q) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .doOnSubscribe(disposable -> { compositeDisposable.add(disposable); srMovieSearch.setEnabled(true); srMovieSearch.setRefreshing(true); }) .doFinally(() -> { srMovieSearch.setRefreshing(false); srMovieSearch.setEnabled(false); }) .subscribe( apiResponse -> { this.apiResponse = apiResponse; searchMoviewAdapter.setData(apiResponse .getResults()); }, throwable -> Log.d(TAG, "retrieveItems: ", throwable)); } private void setupRecyclerView() { searchMoviewAdapter = new SearchMovieAdapter(); searchMoviewAdapter.setItemViewClickListener(item -> MovieDetailActivity.start(this, item)); rvPopularMovie.setAdapter(searchMoviewAdapter); rvPopularMovie.setLayoutManager(new LinearLayoutManager(this)); } }
package generic_test; /** * Description: * * @author Baltan * @date 2018/4/16 20:32 */ class Box<T> { private T object; public void set(T object) { this.object = object; } public T get() { return object; } public static void main(String[] args) { Box box = new Box(); box.set(new Cat()); Cat c = (Cat) box.get(); } }
package com.study.spring.discount; import com.study.spring.member.Grade; import com.study.spring.member.Member; public class RateDiscountPolicy implements DiscountPolicy { private final int discountRate = 10; @Override public int discount(Member member, int price) { if(member.getGrade() == Grade.VIP) return price * discountRate/100; else return 0; } }
package com.example.tp3; import android.util.JsonReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; /** * Process the response to a GET request to the Web service * https://www.thesportsdb.com/api/v1/json/1/searchteams.php?t=R * Responses must be provided in JSON. * */ public class JSONResponseHandlerTeam { private static final String TAG = JSONResponseHandlerTeam.class.getSimpleName(); private Team team; public JSONResponseHandlerTeam(Team team) { this.team = team; } /** * @param response done by the Web service * @return A Team with attributes filled with the collected information if response was * successfully analyzed */ public void readJsonStream(InputStream response) throws IOException { JsonReader reader = new JsonReader(new InputStreamReader(response, "UTF-8")); try { readTeams(reader); } finally { reader.close(); } } public void readTeams(JsonReader reader) throws IOException { reader.beginObject(); while (reader.hasNext()) { String name = reader.nextName(); if (name.equals("teams")) { readArrayTeams(reader); } else { reader.skipValue(); } } reader.endObject(); } private void readArrayTeams(JsonReader reader) throws IOException { reader.beginArray(); int nb = 0; // only consider the first element of the array while (reader.hasNext() ) { reader.beginObject(); while (reader.hasNext()) { String name = reader.nextName(); if (nb==0) { if (name.equals("idTeam")) { team.setIdTeam(reader.nextLong()); } else if (name.equals("strTeam")) { team.setName(reader.nextString()); } else if (name.equals("strLeague")) { team.setLeague(reader.nextString()); } else if (name.equals("idLeague")) { team.setIdLeague(reader.nextLong()); } else if (name.equals("strStadium")) { team.setStadium(reader.nextString()); } else if (name.equals("strStadiumLocation")) { team.setStadiumLocation(reader.nextString()); } else if (name.equals("strTeamBadge")) { team.setTeamBadge(reader.nextString()); } else { reader.skipValue(); } } else { reader.skipValue(); } } reader.endObject(); nb++; } reader.endArray(); } }
package basic.database.console; import java.io.IOException; import java.net.URL; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ResourceBundle; import basic.example.ConnectionDB; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.PasswordField; import javafx.scene.control.TextField; import javafx.stage.Modality; import javafx.stage.Stage; import javafx.stage.StageStyle; public class loginConlloer implements Initializable { @FXML private TextField id; @FXML private PasswordField pass; @FXML Button lg, si; ObservableList<member> list; Connection conn = ConnectionDB.getDB(); Stage primaryStage; public void setPrimaryStage(Stage primaryStage) { } @Override public void initialize(URL location, ResourceBundle resources) { lg.setOnAction(s->Login()); } public void Login() { Stage stage = new Stage(StageStyle.UTILITY); stage.initModality(Modality.WINDOW_MODAL); stage.initOwner(lg.getScene().getWindow()); ObservableList<member> list = FXCollections.observableArrayList(); String sql = "select * from member"; try { PreparedStatement pstmt = conn.prepareStatement(sql); ResultSet rs = pstmt.executeQuery(); while (rs.next()) { member mem = new member(rs.getString("ID"), rs.getString("PASS")); list.add(mem); }; } catch (SQLException e1) { e1.printStackTrace(); } for(member m : list) { if(m.getId().equals(id.getText())&& m.getPass().equals(pass.getText())) { try { Parent parent; parent = FXMLLoader.load(getClass().getResource("Boardlist.fxml")); Scene scene = new Scene(parent); stage.setTitle("예약"); stage.setScene(scene); stage.show(); } catch (IOException e) { e.printStackTrace(); } } } } }
package com.ardhendu.popupwindow1; import android.content.Context; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.widget.Button; import android.widget.LinearLayout; import android.widget.PopupWindow; public class MainActivity extends AppCompatActivity { Button showPopupBtn, closePopupBtn; PopupWindow popupWindow; LinearLayout linearLayout1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); showPopupBtn = (Button) findViewById(R.id.showPopupBtn); linearLayout1 = (LinearLayout) findViewById(R.id.linearLayout1); showPopupBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //instantiate the popup.xml layout file LayoutInflater layoutInflater = (LayoutInflater) MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View customView = layoutInflater.inflate(R.layout.popup,null); closePopupBtn = (Button) customView.findViewById(R.id.closePopupBtn); //instantiate popup window popupWindow = new PopupWindow(customView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); //display the popup window popupWindow.showAtLocation(linearLayout1, Gravity.CENTER, 0, 0); //close the popup window on button click closePopupBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { popupWindow.dismiss(); } }); } }); } }
package com.example.ashvant.stock; /** * Created by ashvant on 11/28/17. */ public class FavouriteData { String symbol = ""; String price = ""; String change = ""; String percent = ""; public String getSymbol() { return symbol; } public void setSymbol(String symbol) { this.symbol = symbol; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } public String getChange() { return change; } public void setChange(String change) { this.change = change; } public String getPercent() { return percent; } public void setPercent(String percent) { this.percent = percent; } }
package com.tencent.mm.plugin.wallet.balance.ui; import android.graphics.drawable.ColorDrawable; import android.os.Build.VERSION; import android.os.Bundle; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.ImageView; import android.widget.ImageView.ScaleType; import android.widget.LinearLayout; import android.widget.TextView; import com.tencent.mm.ab.l; import com.tencent.mm.plugin.wallet_core.id_verify.util.RealnameGuideHelper; import com.tencent.mm.plugin.wallet_core.model.Orders; import com.tencent.mm.plugin.wallet_core.model.Orders.Commodity; import com.tencent.mm.plugin.wxpay.a$e; import com.tencent.mm.plugin.wxpay.a.c; import com.tencent.mm.plugin.wxpay.a.f; import com.tencent.mm.plugin.wxpay.a.g; import com.tencent.mm.plugin.wxpay.a.h; import com.tencent.mm.plugin.wxpay.a.i; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.wallet_core.ui.WalletBaseUI; import com.tencent.mm.wallet_core.ui.e; import java.text.SimpleDateFormat; import java.util.Date; public class WalletBalanceFetchResultUI extends WalletBaseUI { private LinearLayout klz; private Orders mCZ; private ImageView mvq; private ImageView mvr; private ImageView mvs; private TextView mvt; private TextView mvu; private TextView mvv; private TextView mvw; private TextView mvx; private TextView mvy; static /* synthetic */ void a(WalletBalanceFetchResultUI walletBalanceFetchResultUI) { if (walletBalanceFetchResultUI.sy.containsKey("key_realname_guide_helper")) { RealnameGuideHelper realnameGuideHelper = (RealnameGuideHelper) walletBalanceFetchResultUI.sy.getParcelable("key_realname_guide_helper"); if (realnameGuideHelper != null) { Bundle bundle = new Bundle(); bundle.putString("realname_verify_process_jump_activity", ".balance.ui.WalletBalanceResultUI"); bundle.putString("realname_verify_process_jump_plugin", "wallet"); realnameGuideHelper.b(walletBalanceFetchResultUI, bundle, new 3(walletBalanceFetchResultUI)); walletBalanceFetchResultUI.sy.remove("key_realname_guide_helper"); return; } return; } walletBalanceFetchResultUI.cDK().a(walletBalanceFetchResultUI, 0, walletBalanceFetchResultUI.sy); } public void onCreate(Bundle bundle) { super.onCreate(bundle); getSupportActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(c.white))); View customView = getSupportActionBar().getCustomView(); if (customView != null) { View findViewById = customView.findViewById(f.divider); if (findViewById != null) { findViewById.setBackgroundColor(getResources().getColor(c.half_alpha_white)); } customView = customView.findViewById(16908308); if (customView != null && (customView instanceof TextView)) { ((TextView) customView).setTextColor(getResources().getColor(c.black)); } } if (VERSION.SDK_INT >= 21) { Window window = getWindow(); window.addFlags(Integer.MIN_VALUE); window.setStatusBarColor(getResources().getColor(c.white)); if (VERSION.SDK_INT >= 23) { getWindow().getDecorView().setSystemUiVisibility(8192); } } this.mController.contentView.setFitsSystemWindows(true); this.mCZ = (Orders) this.sy.getParcelable("key_orders"); initView(); showHomeBtn(false); enableBackMenu(false); setMMTitle((String) cDL().ui(0)); setBackBtn(new 1(this)); } protected final void initView() { this.mvq = (ImageView) findViewById(f.brdu_state_iv_1); this.mvr = (ImageView) findViewById(f.brdu_state_iv_2); this.mvs = (ImageView) findViewById(f.brdu_state_iv_3); this.mvq.setImageResource(a$e.bank_remit_detail_state_circle_succ); this.mvr.setScaleType(ScaleType.CENTER_CROP); this.mvr.setImageResource(h.remittance_wait); this.mvs.setImageResource(a$e.bank_remit_detail_state_circle_unknown); this.mvt = (TextView) findViewById(f.brdu_state_title_tv_1); this.mvu = (TextView) findViewById(f.brdu_state_title_tv_2); this.mvv = (TextView) findViewById(f.brdu_state_title_tv_3); this.mvt.setText(i.wallet_balance_launch_fetch_title); this.mvu.setText(i.wallet_balance_fetch_waiting_title); this.mvu.setTextColor(getResources().getColor(c.normal_text_color)); this.mvv.setText(i.wallet_balance_fetch_success_title); this.mvw = (TextView) findViewById(f.brdu_state_desc_tv_1); this.mvx = (TextView) findViewById(f.brdu_state_desc_tv_2); this.mvy = (TextView) findViewById(f.brdu_state_desc_tv_3); this.mvw.setVisibility(8); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm"); this.mvx.setText(getString(i.wallet_balance_fetch_expect_arrive_time, new Object[]{simpleDateFormat.format(new Date(this.mCZ.poZ))})); this.mvx.setVisibility(0); this.mvy.setVisibility(8); this.klz = (LinearLayout) findViewById(f.brdu_content_layout); this.klz.setBackgroundResource(a$e.bank_remit_detail_desc_singleline_layout_bg); WalletBalanceFetchResultItemView walletBalanceFetchResultItemView = new WalletBalanceFetchResultItemView(this, true); walletBalanceFetchResultItemView.b(i.wallet_balance_result_total_fee_fetch, e.e(this.mCZ.mBj, this.mCZ.lNV)); this.klz.addView(walletBalanceFetchResultItemView); if (this.mCZ.mxE > 0.0d) { walletBalanceFetchResultItemView = new WalletBalanceFetchResultItemView(this, true); walletBalanceFetchResultItemView.b(i.wallet_balance_result_charge_fee, e.e(this.mCZ.mxE, this.mCZ.lNV)); this.klz.addView(walletBalanceFetchResultItemView); } if (this.mCZ.ppf != null && this.mCZ.ppf.size() > 0) { CharSequence charSequence; Commodity commodity = (Commodity) this.mCZ.ppf.get(0); String str = commodity.lNT; if (bi.oW(commodity.ppy)) { Object charSequence2 = str; } else { charSequence2 = str + " " + getString(i.wallet_pay_bankcard_tail) + commodity.ppy; } WalletBalanceFetchResultItemView walletBalanceFetchResultItemView2 = new WalletBalanceFetchResultItemView(this); walletBalanceFetchResultItemView2.b(i.wallet_balance_fetch_bankcard_title, charSequence2); this.klz.addView(walletBalanceFetchResultItemView2); } ((Button) findViewById(f.brdu_finish_btn)).setOnClickListener(new 2(this)); findViewById(f.brdu_timeline_mask).setVisibility(8); findViewById(f.brdu_content_mask).setVisibility(8); } public final boolean d(int i, int i2, String str, l lVar) { return false; } protected final int getLayoutId() { return g.bank_remit_detail_ui; } }
public class DrowShip2 extends DrowShip { public DrowShip2(int[][] battleground) { super(battleground, 2); } }
package mx.com.alex.crazycards.activities; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBarActivity; import android.view.Menu; import android.view.MenuItem; import mx.com.alex.crazycards.database.AndroidDatabaseManager; import mx.com.alex.crazycards.fragments.GameFragment; import mx.com.alex.crazycards.fragments.NavigationDrawerFragment; import mx.com.alex.crazycards.R; public class MainActivity extends ActionBarActivity implements NavigationDrawerFragment.NavigationDrawerCallbacks{ private NavigationDrawerFragment mNavigationDrawerFragment; private CharSequence mTitle; private FragmentManager fm; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); fm = getSupportFragmentManager(); setContentView(R.layout.activity_main); mNavigationDrawerFragment = (NavigationDrawerFragment) getSupportFragmentManager().findFragmentById(R.id.navigation_drawer); mTitle = getTitle(); mNavigationDrawerFragment.setUp( R.id.navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout)); } @Override public void onNavigationDrawerItemSelected(int position) { switch (position) { case 0: mTitle = getString(R.string.title_section1); break; case 1: getSupportFragmentManager().beginTransaction().replace(R.id.container,new GameFragment()).commit(); break; case 3: mTitle = getString(R.string.title_section3); break; } } public void onSectionAttached(int number) { switch (number) { case 1: mTitle = getString(R.string.title_section1); break; case 2: mTitle = getString(R.string.title_section2); break; case 3: mTitle = getString(R.string.title_section3); break; } } public void restoreActionBar() { ActionBar actionBar = getSupportActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); actionBar.setDisplayShowTitleEnabled(true); actionBar.setTitle(mTitle); } @Override public boolean onCreateOptionsMenu(Menu menu) { if (!mNavigationDrawerFragment.isDrawerOpen()) { // Only show items in the action bar relevant to this screen // if the drawer is not showing. Otherwise, let the drawer // decide what to show in the action bar. getMenuInflater().inflate(R.menu.menu_main, menu); restoreActionBar(); return true; } return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); switch (item.getItemId()) { case R.id.action_settings: Intent intent = new Intent(this, AndroidDatabaseManager.class); startActivity(intent); break; } //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } /* @Override public void onStartSelected(Verb word) { getSupportFragmentManager().beginTransaction().addToBackStack(null) .replace(R.id.container, CityFragment.newInstance(word)) .commit(); }*/ }
package assignment10.fitbit2; import jssc.SerialPort; import jssc.SerialPortException; public class SerialComm { SerialPort port; private boolean debug; public SerialComm(String name, boolean debugSetting) { port = new SerialPort(name); debug = debugSetting; try { port.openPort(); port.setParams(SerialPort.BAUDRATE_9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); } catch (Exception e) { e.printStackTrace(); } } public SerialComm(String name) { this(name, true); } public static void main(String[] args) { SerialComm serialComm = new SerialComm("COM3"); while (true) { try { while (serialComm.available()) { byte b = serialComm.readByte(); System.out.println((char)b); // serialComm.readByte(); } } catch (Exception e) { e.printStackTrace(); } } } public boolean available() throws SerialPortException { return (port.getInputBufferBytesCount() > 0); } public byte readByte() throws SerialPortException { byte[] byteArray = port.readBytes(1); if (debug) { System.out.print("[0x" + String.format("%02x", byteArray[0]) + "]"); } return byteArray[0]; } public void writeByte(byte theByte) throws SerialPortException { port.writeByte(theByte); if (debug) { System.out.println("<0x" + String.format("%02x", theByte) + ">"); } } public void setDebug(boolean setting) { debug = setting; } }
/* * SUNSHINE TEAHOUSE PRIVATE LIMITED CONFIDENTIAL * __________________ * * [2015] - [2017] Sunshine Teahouse Private Limited * All Rights Reserved. * * NOTICE: All information contained herein is, and remains * the property of Sunshine Teahouse Private Limited and its suppliers, * if any. The intellectual and technical concepts contained * herein are proprietary to Sunshine Teahouse Private Limited * and its suppliers, and are protected by trade secret or copyright law. * Dissemination of this information or reproduction of this material * is strictly forbidden unless prior written permission is obtained * from Sunshine Teahouse Private Limited. */ // // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.11 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2016.03.22 at 01:07:13 PM IST // package www.chaayos.com.chaimonkbluetoothapp.domain.model.new_model; import java.io.Serializable; /** * <p> * Java class for OrderMetadata complex type. * * <p> * The following schema fragment specifies the expected content contained within * this class. * * <pre> * &lt;complexType name="OrderMetadata"&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element name="metadataId" type="{http://www.w3.org/2001/XMLSchema}int"/&gt; * &lt;element name="orderId" type="{http://www.w3.org/2001/XMLSchema}int"/&gt; * &lt;element name="attributeName" type="{http://www.w3.org/2001/XMLSchema}string"/&gt; * &lt;element name="attributeValue" type="{http://www.w3.org/2001/XMLSchema}string"/&gt; * &lt;/sequence&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ public class OrderMetadata implements Serializable{ /** * */ private static final long serialVersionUID = -9176250779625403395L; private String objectId; private Long version; /** * Added to avoid a runtime error whereby the detachAll property is checked * for existence but not actually used. */ private String detachAll; protected int metadataId; protected int orderId; protected String attributeName; protected String attributeValue; public String getObjectId() { return objectId; } public void setObjectId(String _id) { this.objectId = _id; } public Long getVersion() { return version; } public void setVersion(Long version) { this.version = version; } public String getDetachAll() { return detachAll; } public void setDetachAll(String detachAll) { this.detachAll = detachAll; } /** * Gets the value of the metadataId property. * */ public int getMetadataId() { return metadataId; } /** * Sets the value of the metadataId property. * */ public void setMetadataId(int value) { this.metadataId = value; } /** * Gets the value of the orderId property. * */ public int getOrderId() { return orderId; } /** * Sets the value of the orderId property. * */ public void setOrderId(int value) { this.orderId = value; } /** * Gets the value of the attributeName property. * * @return possible object is {@link String } * */ public String getAttributeName() { return attributeName; } /** * Sets the value of the attributeName property. * * @param value * allowed object is {@link String } * */ public void setAttributeName(String value) { this.attributeName = value; } /** * Gets the value of the attributeValue property. * * @return possible object is {@link String } * */ public String getAttributeValue() { return attributeValue; } /** * Sets the value of the attributeValue property. * * @param value * allowed object is {@link String } * */ public void setAttributeValue(String value) { this.attributeValue = value; } }
package com.cooksys.teamOneSocialMedia.services.impl; import org.springframework.stereotype.Service; import com.cooksys.teamOneSocialMedia.repositories.HashtagRepository; import com.cooksys.teamOneSocialMedia.repositories.UserRepository; import com.cooksys.teamOneSocialMedia.service.ValidateService; import lombok.RequiredArgsConstructor; @Service @RequiredArgsConstructor public class ValidateServiceImpl implements ValidateService { private final UserRepository userRepository; private final HashtagRepository hashtagRepository; @Override public boolean doesHashtagExist(String label) { return hashtagRepository.findByLabel(label).isPresent(); } @Override public boolean doesUsernameExist(String username) { return userRepository.findByCredentialsUsernameAndDeletedFalse(username).isPresent(); } }
package com.tyss.capgemini.loanproject.exceptions; @SuppressWarnings("serial") public class InvalidPhoneException extends RuntimeException { public InvalidPhoneException(String msg) { super(msg); } }
package org.bofur.search; import org.bofur.R; import org.bofur.SearchActivity; import org.bofur.bean.Department; import org.bofur.bean.Facility; import org.bofur.bean.Speciality; import org.bofur.search.statement.CompositStatement; import org.bofur.search.statement.EqualStatement; import org.bofur.search.statement.InStatement; import org.bofur.search.statement.LikeStatement; import org.bofur.search.statement.SelectStatement; import org.bofur.search.statement.SelectWithConditionStatement; import org.bofur.search.statement.Statement; import android.widget.EditText; public class QueryBuilder { private SearchActivity activity; private CompositStatement conditions; public QueryBuilder(SearchActivity activity) { this.activity = activity; } public String getQuery() { conditions = new CompositStatement(); addNameCond(getTextFromEdit(R.id.title_text)); addYearStatement(activity.getModerator().getYear()); addStudentCondition(getTextFromEdit(R.id.first_name_text), getTextFromEdit(R.id.second_name_text), getTextFromEdit(R.id.last_name_text)); do { Speciality speciality = activity.getModerator().getSpeciality(); if (speciality != null) { addSpecialityStatement(speciality); break; } Department department = activity.getModerator().getDepartment(); if (department != null) { addDepartmentStatement(department); break; } Facility facility = activity.getModerator().getFacility(); if (facility != null) { addFacilityStatement(facility); } break; } while(true); return new SelectStatement("*", "degrees", conditions).generate(); } public void addNameCond(String name) { conditions.add(new LikeStatement("name", name)); } public void addStudentCondition(String firstName, String secondName, String lastName) { CompositStatement studentConditions = new CompositStatement(); studentConditions.add(new LikeStatement("first_name", firstName)); studentConditions.add(new LikeStatement("second_name", secondName)); studentConditions.add(new LikeStatement("last_name", lastName)); Statement select = new SelectWithConditionStatement("id", "students", studentConditions); Statement in = new InStatement("student_id", select); conditions.add(in); } public void addSpecialityStatement(Speciality speciality) { Statement equal = new EqualStatement("speciality_id", speciality); Statement select = new SelectWithConditionStatement("id", "students", equal); Statement in = new InStatement("student_id", select); conditions.add(in); } public void addDepartmentStatement(Department department) { Statement equal = new EqualStatement("department_id", department); Statement specialitiesSelect = new SelectWithConditionStatement("id", "specialites", equal); Statement inStudents = new InStatement("student_id", specialitiesSelect); Statement studentsSelect = new SelectWithConditionStatement("id", "students", inStudents); Statement in = new InStatement("student_id", studentsSelect); conditions.add(in); } public void addFacilityStatement(Facility facility) { Statement equal = new EqualStatement("facility_id", facility); Statement departmentsSelect = new SelectWithConditionStatement("id", "departments", equal); Statement inDepartments = new InStatement("department_id", departmentsSelect); Statement specialitiesSelect = new SelectWithConditionStatement("id", "specialities", inDepartments); Statement inStudents = new InStatement("speciality_id", specialitiesSelect); Statement studentsSelect = new SelectWithConditionStatement("id", "students", inStudents); Statement in = new InStatement("student_id", studentsSelect); conditions.add(in); } public void addYearStatement(String year) { conditions.add(new EqualStatement("year", year)); } private String getTextFromEdit(int editId) { return ((EditText)activity.findViewById(editId)).getText().toString(); } }
package com.nju.edu.cn.model; import com.nju.edu.cn.entity.ContractBackTestParams; /** * Created by shea on 2018/10/25. */ public class ContractBackTestParamsBean extends ContractBackTestParams { private Long contractId; private String createTimeStr; public Long getContractId() { return contractId; } public void setContractId(Long contractId) { this.contractId = contractId; } public String getCreateTimeStr() { return createTimeStr; } public void setCreateTimeStr(String createTimeStr) { this.createTimeStr = createTimeStr; } }
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.components.devtools_bridge.apiary; import android.net.http.AndroidHttpClient; import org.chromium.base.JNINamespace; /** * Factory for creating clients for external APIs. */ @JNINamespace("devtools_bridge::android") public class ApiaryClientFactory { private static final String USER_AGENT = "DevTools bridge"; public static final String OAUTH_SCOPE = "https://www.googleapis.com/auth/clouddevices"; protected final AndroidHttpClient mHttpClient = AndroidHttpClient.newInstance(USER_AGENT); /** * Creates a new GCD client with auth token. */ public GCDClient newGCDClient(String oAuthToken) { return new GCDClient(mHttpClient, getAPIKey(), oAuthToken); } /** * Creates a new anonymous client. GCD requires client been not authenticated by user or * device credentials for finalizing registration. */ public GCDClient newAnonymousGCDClient() { return new GCDClient(mHttpClient, nativeGetAPIKey()); } public OAuthClient newOAuthClient() { return new OAuthClient( mHttpClient, OAUTH_SCOPE, getOAuthClientId(), nativeGetOAuthClientSecret()); } public BlockingGCMRegistrar newGCMRegistrar() { return new BlockingGCMRegistrar(); } public void close() { mHttpClient.close(); } public String getOAuthClientId() { return nativeGetOAuthClientId(); } protected String getAPIKey() { return nativeGetAPIKey(); } private native String nativeGetAPIKey(); private native String nativeGetOAuthClientId(); private native String nativeGetOAuthClientSecret(); }
/* 138. Copy List with Random Pointer A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null. Return a deep copy of the list. Example 1: Input: {"$id":"1","next":{"$id":"2","next":null,"random":{"$ref":"2"},"val":2},"random":{"$ref":"2"},"val":1} Explanation: Node 1's value is 1, both of its next and random pointer points to Node 2. Node 2's value is 2, its next pointer points to null and its random pointer points to itself. */ package leetcode_linkedlist; import java.util.*; public class Question_138 { class Node { public int val; public Node next; public Node random; public Node() {} public Node(int _val,Node _next,Node _random) { val = _val; next = _next; random = _random; } } public Node copyRandomList(Node head) { HashMap<Node, Node> copy = new HashMap<>(); Node temp = head; while (temp != null) { copy.put(temp, new Node(temp.val, null, null)); temp = temp.next; } temp = head; while (temp != null) { copy.get(temp).next = copy.get(temp.next); copy.get(temp).random = copy.get(temp.random); temp = temp.next; } return copy.get(head); } public void solve() { int[] input = {1, 2, 3}; } }
/* * Copyright 2005-2010 the original author or authors. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 sdloader.util.databuffer; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public abstract class CompositeDataBuffer implements DataBuffer { protected DataBuffer firstDataBuffer; protected DataBuffer nextDataBuffer; protected boolean useNextBuffer = false; protected long size; protected long firstDataBufferLimitSize; public CompositeDataBuffer(long firstDataBufferLimitSize) { this.firstDataBufferLimitSize = firstDataBufferLimitSize; firstDataBuffer = createFirstDataBuffer(); } public InputStream getInputStream() throws IOException { return new CompositeDataBufferInputStream(this); } public OutputStream getOutputStream() throws IOException { return new DataBuffer.DelegateOutputStream(this); } public long getSize() { return size; } public void write(byte[] buf, int offset, int length) throws IOException { if (useNextBuffer) { nextDataBuffer.write(buf, offset, length); size += length; } else { if ((size + length) > firstDataBufferLimitSize) { int writeSize = (int) (firstDataBufferLimitSize - size); firstDataBuffer.write(buf, offset, writeSize); size += writeSize; offset += writeSize; writeSize = length - writeSize; checkBuffer(); write(buf, offset, writeSize); } else { firstDataBuffer.write(buf, offset, length); size += length; } } } public void write(int data) throws IOException { checkBuffer(); if (useNextBuffer) { nextDataBuffer.write(data); } else { firstDataBuffer.write(data); } size++; } private void checkBuffer() { if (size == firstDataBufferLimitSize) { nextDataBuffer = createNextDataBuffer(); useNextBuffer = true; } } public void dispose() { firstDataBuffer.dispose(); if (nextDataBuffer != null) { nextDataBuffer.dispose(); } } protected abstract DataBuffer createFirstDataBuffer(); protected abstract DataBuffer createNextDataBuffer(); private static class CompositeDataBufferInputStream extends InputStream { private InputStream firstDataBufferInputStream; private InputStream nextDataBufferInputStream; private CompositeDataBuffer target; private long totalReadSize; private boolean useNextBuffer = false; public CompositeDataBufferInputStream(CompositeDataBuffer target) throws IOException { this.target = target; firstDataBufferInputStream = target.firstDataBuffer .getInputStream(); } @Override public int read() throws IOException { if (target.getSize() <= totalReadSize) { return -1; } checkStream(); totalReadSize++; return useNextBuffer ? nextDataBufferInputStream.read() : firstDataBufferInputStream.read(); } @Override public int read(byte[] buf, int offset, int length) throws IOException { if (target.getSize() <= totalReadSize) { return -1; } checkStream(); int readSize = 0; if (useNextBuffer) { readSize = nextDataBufferInputStream.read(buf, offset, length); } else { if ((totalReadSize + length) > target.firstDataBufferLimitSize) { length = (int) (target.firstDataBufferLimitSize -totalReadSize); } readSize = firstDataBufferInputStream.read(buf, offset, length); } totalReadSize += readSize; return readSize; } private void checkStream() throws IOException { if (totalReadSize == target.firstDataBufferLimitSize) { useNextBuffer = true; nextDataBufferInputStream = target.nextDataBuffer .getInputStream(); } } @Override public void close() throws IOException { firstDataBufferInputStream.close(); if (nextDataBufferInputStream != null) { nextDataBufferInputStream.close(); } } } }
package com.rc.portal.vo; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import com.rc.app.framework.webapp.model.BaseModel; public class TMemberCertificatesExample extends BaseModel{ protected String orderByClause; protected List oredCriteria; public TMemberCertificatesExample() { oredCriteria = new ArrayList(); } protected TMemberCertificatesExample(TMemberCertificatesExample example) { this.orderByClause = example.orderByClause; this.oredCriteria = example.oredCriteria; } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public List getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); } public static class Criteria { protected List criteriaWithoutValue; protected List criteriaWithSingleValue; protected List criteriaWithListValue; protected List criteriaWithBetweenValue; protected Criteria() { super(); criteriaWithoutValue = new ArrayList(); criteriaWithSingleValue = new ArrayList(); criteriaWithListValue = new ArrayList(); criteriaWithBetweenValue = new ArrayList(); } public boolean isValid() { return criteriaWithoutValue.size() > 0 || criteriaWithSingleValue.size() > 0 || criteriaWithListValue.size() > 0 || criteriaWithBetweenValue.size() > 0; } public List getCriteriaWithoutValue() { return criteriaWithoutValue; } public List getCriteriaWithSingleValue() { return criteriaWithSingleValue; } public List getCriteriaWithListValue() { return criteriaWithListValue; } public List getCriteriaWithBetweenValue() { return criteriaWithBetweenValue; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteriaWithoutValue.add(condition); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } Map map = new HashMap(); map.put("condition", condition); map.put("value", value); criteriaWithSingleValue.add(map); } protected void addCriterion(String condition, List values, String property) { if (values == null || values.size() == 0) { throw new RuntimeException("Value list for " + property + " cannot be null or empty"); } Map map = new HashMap(); map.put("condition", condition); map.put("values", values); criteriaWithListValue.add(map); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } List list = new ArrayList(); list.add(value1); list.add(value2); Map map = new HashMap(); map.put("condition", condition); map.put("values", list); criteriaWithBetweenValue.add(map); } public Criteria andIdIsNull() { addCriterion("id is null"); return this; } public Criteria andIdIsNotNull() { addCriterion("id is not null"); return this; } public Criteria andIdEqualTo(Long value) { addCriterion("id =", value, "id"); return this; } public Criteria andIdNotEqualTo(Long value) { addCriterion("id <>", value, "id"); return this; } public Criteria andIdGreaterThan(Long value) { addCriterion("id >", value, "id"); return this; } public Criteria andIdGreaterThanOrEqualTo(Long value) { addCriterion("id >=", value, "id"); return this; } public Criteria andIdLessThan(Long value) { addCriterion("id <", value, "id"); return this; } public Criteria andIdLessThanOrEqualTo(Long value) { addCriterion("id <=", value, "id"); return this; } public Criteria andIdIn(List values) { addCriterion("id in", values, "id"); return this; } public Criteria andIdNotIn(List values) { addCriterion("id not in", values, "id"); return this; } public Criteria andIdBetween(Long value1, Long value2) { addCriterion("id between", value1, value2, "id"); return this; } public Criteria andIdNotBetween(Long value1, Long value2) { addCriterion("id not between", value1, value2, "id"); return this; } public Criteria andMemberIdIsNull() { addCriterion("member_id is null"); return this; } public Criteria andMemberIdIsNotNull() { addCriterion("member_id is not null"); return this; } public Criteria andMemberIdEqualTo(Long value) { addCriterion("member_id =", value, "memberId"); return this; } public Criteria andMemberIdNotEqualTo(Long value) { addCriterion("member_id <>", value, "memberId"); return this; } public Criteria andMemberIdGreaterThan(Long value) { addCriterion("member_id >", value, "memberId"); return this; } public Criteria andMemberIdGreaterThanOrEqualTo(Long value) { addCriterion("member_id >=", value, "memberId"); return this; } public Criteria andMemberIdLessThan(Long value) { addCriterion("member_id <", value, "memberId"); return this; } public Criteria andMemberIdLessThanOrEqualTo(Long value) { addCriterion("member_id <=", value, "memberId"); return this; } public Criteria andMemberIdIn(List values) { addCriterion("member_id in", values, "memberId"); return this; } public Criteria andMemberIdNotIn(List values) { addCriterion("member_id not in", values, "memberId"); return this; } public Criteria andMemberIdBetween(Long value1, Long value2) { addCriterion("member_id between", value1, value2, "memberId"); return this; } public Criteria andMemberIdNotBetween(Long value1, Long value2) { addCriterion("member_id not between", value1, value2, "memberId"); return this; } public Criteria andIdcardJustUrlIsNull() { addCriterion("idcard_just_url is null"); return this; } public Criteria andIdcardJustUrlIsNotNull() { addCriterion("idcard_just_url is not null"); return this; } public Criteria andIdcardJustUrlEqualTo(String value) { addCriterion("idcard_just_url =", value, "idcardJustUrl"); return this; } public Criteria andIdcardJustUrlNotEqualTo(String value) { addCriterion("idcard_just_url <>", value, "idcardJustUrl"); return this; } public Criteria andIdcardJustUrlGreaterThan(String value) { addCriterion("idcard_just_url >", value, "idcardJustUrl"); return this; } public Criteria andIdcardJustUrlGreaterThanOrEqualTo(String value) { addCriterion("idcard_just_url >=", value, "idcardJustUrl"); return this; } public Criteria andIdcardJustUrlLessThan(String value) { addCriterion("idcard_just_url <", value, "idcardJustUrl"); return this; } public Criteria andIdcardJustUrlLessThanOrEqualTo(String value) { addCriterion("idcard_just_url <=", value, "idcardJustUrl"); return this; } public Criteria andIdcardJustUrlLike(String value) { addCriterion("idcard_just_url like", value, "idcardJustUrl"); return this; } public Criteria andIdcardJustUrlNotLike(String value) { addCriterion("idcard_just_url not like", value, "idcardJustUrl"); return this; } public Criteria andIdcardJustUrlIn(List values) { addCriterion("idcard_just_url in", values, "idcardJustUrl"); return this; } public Criteria andIdcardJustUrlNotIn(List values) { addCriterion("idcard_just_url not in", values, "idcardJustUrl"); return this; } public Criteria andIdcardJustUrlBetween(String value1, String value2) { addCriterion("idcard_just_url between", value1, value2, "idcardJustUrl"); return this; } public Criteria andIdcardJustUrlNotBetween(String value1, String value2) { addCriterion("idcard_just_url not between", value1, value2, "idcardJustUrl"); return this; } public Criteria andIdcardBackUrlIsNull() { addCriterion("idcard_back_url is null"); return this; } public Criteria andIdcardBackUrlIsNotNull() { addCriterion("idcard_back_url is not null"); return this; } public Criteria andIdcardBackUrlEqualTo(String value) { addCriterion("idcard_back_url =", value, "idcardBackUrl"); return this; } public Criteria andIdcardBackUrlNotEqualTo(String value) { addCriterion("idcard_back_url <>", value, "idcardBackUrl"); return this; } public Criteria andIdcardBackUrlGreaterThan(String value) { addCriterion("idcard_back_url >", value, "idcardBackUrl"); return this; } public Criteria andIdcardBackUrlGreaterThanOrEqualTo(String value) { addCriterion("idcard_back_url >=", value, "idcardBackUrl"); return this; } public Criteria andIdcardBackUrlLessThan(String value) { addCriterion("idcard_back_url <", value, "idcardBackUrl"); return this; } public Criteria andIdcardBackUrlLessThanOrEqualTo(String value) { addCriterion("idcard_back_url <=", value, "idcardBackUrl"); return this; } public Criteria andIdcardBackUrlLike(String value) { addCriterion("idcard_back_url like", value, "idcardBackUrl"); return this; } public Criteria andIdcardBackUrlNotLike(String value) { addCriterion("idcard_back_url not like", value, "idcardBackUrl"); return this; } public Criteria andIdcardBackUrlIn(List values) { addCriterion("idcard_back_url in", values, "idcardBackUrl"); return this; } public Criteria andIdcardBackUrlNotIn(List values) { addCriterion("idcard_back_url not in", values, "idcardBackUrl"); return this; } public Criteria andIdcardBackUrlBetween(String value1, String value2) { addCriterion("idcard_back_url between", value1, value2, "idcardBackUrl"); return this; } public Criteria andIdcardBackUrlNotBetween(String value1, String value2) { addCriterion("idcard_back_url not between", value1, value2, "idcardBackUrl"); return this; } public Criteria andIdcardTypeIsNull() { addCriterion("idcard_type is null"); return this; } public Criteria andIdcardTypeIsNotNull() { addCriterion("idcard_type is not null"); return this; } public Criteria andIdcardTypeEqualTo(Integer value) { addCriterion("idcard_type =", value, "idcardType"); return this; } public Criteria andIdcardTypeNotEqualTo(Integer value) { addCriterion("idcard_type <>", value, "idcardType"); return this; } public Criteria andIdcardTypeGreaterThan(Integer value) { addCriterion("idcard_type >", value, "idcardType"); return this; } public Criteria andIdcardTypeGreaterThanOrEqualTo(Integer value) { addCriterion("idcard_type >=", value, "idcardType"); return this; } public Criteria andIdcardTypeLessThan(Integer value) { addCriterion("idcard_type <", value, "idcardType"); return this; } public Criteria andIdcardTypeLessThanOrEqualTo(Integer value) { addCriterion("idcard_type <=", value, "idcardType"); return this; } public Criteria andIdcardTypeIn(List values) { addCriterion("idcard_type in", values, "idcardType"); return this; } public Criteria andIdcardTypeNotIn(List values) { addCriterion("idcard_type not in", values, "idcardType"); return this; } public Criteria andIdcardTypeBetween(Integer value1, Integer value2) { addCriterion("idcard_type between", value1, value2, "idcardType"); return this; } public Criteria andIdcardTypeNotBetween(Integer value1, Integer value2) { addCriterion("idcard_type not between", value1, value2, "idcardType"); return this; } public Criteria andIdcardCodeIsNull() { addCriterion("idcard_code is null"); return this; } public Criteria andIdcardCodeIsNotNull() { addCriterion("idcard_code is not null"); return this; } public Criteria andIdcardCodeEqualTo(String value) { addCriterion("idcard_code =", value, "idcardCode"); return this; } public Criteria andIdcardCodeNotEqualTo(String value) { addCriterion("idcard_code <>", value, "idcardCode"); return this; } public Criteria andIdcardCodeGreaterThan(String value) { addCriterion("idcard_code >", value, "idcardCode"); return this; } public Criteria andIdcardCodeGreaterThanOrEqualTo(String value) { addCriterion("idcard_code >=", value, "idcardCode"); return this; } public Criteria andIdcardCodeLessThan(String value) { addCriterion("idcard_code <", value, "idcardCode"); return this; } public Criteria andIdcardCodeLessThanOrEqualTo(String value) { addCriterion("idcard_code <=", value, "idcardCode"); return this; } public Criteria andIdcardCodeLike(String value) { addCriterion("idcard_code like", value, "idcardCode"); return this; } public Criteria andIdcardCodeNotLike(String value) { addCriterion("idcard_code not like", value, "idcardCode"); return this; } public Criteria andIdcardCodeIn(List values) { addCriterion("idcard_code in", values, "idcardCode"); return this; } public Criteria andIdcardCodeNotIn(List values) { addCriterion("idcard_code not in", values, "idcardCode"); return this; } public Criteria andIdcardCodeBetween(String value1, String value2) { addCriterion("idcard_code between", value1, value2, "idcardCode"); return this; } public Criteria andIdcardCodeNotBetween(String value1, String value2) { addCriterion("idcard_code not between", value1, value2, "idcardCode"); return this; } public Criteria andIdcardAddressIsNull() { addCriterion("idcard_address is null"); return this; } public Criteria andIdcardAddressIsNotNull() { addCriterion("idcard_address is not null"); return this; } public Criteria andIdcardAddressEqualTo(String value) { addCriterion("idcard_address =", value, "idcardAddress"); return this; } public Criteria andIdcardAddressNotEqualTo(String value) { addCriterion("idcard_address <>", value, "idcardAddress"); return this; } public Criteria andIdcardAddressGreaterThan(String value) { addCriterion("idcard_address >", value, "idcardAddress"); return this; } public Criteria andIdcardAddressGreaterThanOrEqualTo(String value) { addCriterion("idcard_address >=", value, "idcardAddress"); return this; } public Criteria andIdcardAddressLessThan(String value) { addCriterion("idcard_address <", value, "idcardAddress"); return this; } public Criteria andIdcardAddressLessThanOrEqualTo(String value) { addCriterion("idcard_address <=", value, "idcardAddress"); return this; } public Criteria andIdcardAddressLike(String value) { addCriterion("idcard_address like", value, "idcardAddress"); return this; } public Criteria andIdcardAddressNotLike(String value) { addCriterion("idcard_address not like", value, "idcardAddress"); return this; } public Criteria andIdcardAddressIn(List values) { addCriterion("idcard_address in", values, "idcardAddress"); return this; } public Criteria andIdcardAddressNotIn(List values) { addCriterion("idcard_address not in", values, "idcardAddress"); return this; } public Criteria andIdcardAddressBetween(String value1, String value2) { addCriterion("idcard_address between", value1, value2, "idcardAddress"); return this; } public Criteria andIdcardAddressNotBetween(String value1, String value2) { addCriterion("idcard_address not between", value1, value2, "idcardAddress"); return this; } public Criteria andCreateDtIsNull() { addCriterion("create_dt is null"); return this; } public Criteria andCreateDtIsNotNull() { addCriterion("create_dt is not null"); return this; } public Criteria andCreateDtEqualTo(Date value) { addCriterion("create_dt =", value, "createDt"); return this; } public Criteria andCreateDtNotEqualTo(Date value) { addCriterion("create_dt <>", value, "createDt"); return this; } public Criteria andCreateDtGreaterThan(Date value) { addCriterion("create_dt >", value, "createDt"); return this; } public Criteria andCreateDtGreaterThanOrEqualTo(Date value) { addCriterion("create_dt >=", value, "createDt"); return this; } public Criteria andCreateDtLessThan(Date value) { addCriterion("create_dt <", value, "createDt"); return this; } public Criteria andCreateDtLessThanOrEqualTo(Date value) { addCriterion("create_dt <=", value, "createDt"); return this; } public Criteria andCreateDtIn(List values) { addCriterion("create_dt in", values, "createDt"); return this; } public Criteria andCreateDtNotIn(List values) { addCriterion("create_dt not in", values, "createDt"); return this; } public Criteria andCreateDtBetween(Date value1, Date value2) { addCriterion("create_dt between", value1, value2, "createDt"); return this; } public Criteria andCreateDtNotBetween(Date value1, Date value2) { addCriterion("create_dt not between", value1, value2, "createDt"); return this; } } }
package in.codingninjas.expensemanager; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /** * Created by manishakhattar on 27/06/17. */ public class ExpenseOpenHelper extends SQLiteOpenHelper{ public final static String EXPENSE_TABLE_NAME = "Expense"; public final static String EXPENSE_TITLE = "title"; public final static String EXPENSE_ID = "_id"; public final static String EXPENSE_PRICE = "price" ; public final static String EXPENSE_CATEGORY = "category" ; public static ExpenseOpenHelper expenseOpenHelper; public static ExpenseOpenHelper getOpenHelperInstance(Context context){ if(expenseOpenHelper == null){ expenseOpenHelper = new ExpenseOpenHelper(context); } return expenseOpenHelper; } private ExpenseOpenHelper(Context context) { super(context, "Expenses.db", null, 1); } public void onCreate(SQLiteDatabase db) { String query = "create table " + EXPENSE_TABLE_NAME +" ( " + EXPENSE_ID + " integer primary key autoincrement, " + EXPENSE_TITLE +" text, " + EXPENSE_PRICE + " real, " + EXPENSE_CATEGORY + " text);"; db.execSQL(query); } public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // if(oldVersion == 1 && newVersion == 2){ // // }else if(oldVersion ) // Column insert // Drop table // Create } }
/* * generated by Xtext */ package com.rockwellcollins.atc.parser.antlr; import java.io.InputStream; import org.eclipse.xtext.parser.antlr.IAntlrTokenFileProvider; public class LimpAntlrTokenFileProvider implements IAntlrTokenFileProvider { @Override public InputStream getAntlrTokenFile() { ClassLoader classLoader = getClass().getClassLoader(); return classLoader.getResourceAsStream("com/rockwellcollins/atc/parser/antlr/internal/InternalLimp.tokens"); } }
package com.isystk.sample.web.base.controller.html; import java.io.Serializable; import lombok.Getter; import lombok.Setter; @Setter @Getter public abstract class BaseForm implements Serializable { // 改定番号 Integer version; }
package com.kaysanshi.springsecurityoauth2.configure; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import sun.net.www.protocol.http.AuthenticationInfo; /** * Description: * spring security配置 * WebSecurityConfigurerAdapter是默认情况下 Spring security的http配置 * 优先级高于ResourceServerConfigurer,用于保护oauth相关的endpoints,同时主要作用于用户的登录(form login,Basic auth) * @date:2020/10/29 9:41 * @author: kaysanshi **/ @Configuration public class WebSecurityConfigure extends WebSecurityConfigurerAdapter { /** * 为了让认证配置类注入使用 * * @return * @throws Exception */ @Bean @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } /** * 自定义认证逻辑时需要实现这个类 * * @return * @throws Exception */ @Bean @Override protected UserDetailsService userDetailsService() { return super.userDetailsService(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("admin") .password(new BCryptPasswordEncoder().encode("123")) //123 .roles("admin") .and() .withUser("user") .password(new BCryptPasswordEncoder().encode("123")) //123 .roles("user"); } @Override protected void configure(HttpSecurity http) throws Exception { http.antMatcher("/oauth/**").authorizeRequests() .antMatchers("/oauth/**").permitAll() .and().csrf().disable(); } }
/** * Author: obullxl@gmail.com * Copyright (c) 2004-2013 All Rights Reserved. */ package com.atom.core.lang.utils; import java.io.InputStream; import org.apache.commons.io.IOUtils; import org.junit.Test; import com.github.obullxl.lang.xml.XMLNode; import com.github.obullxl.lang.xml.XMLUtils; /** * XMLUtils工具类测试 * * @author obullxl@gmail.com * @version $Id: XMLUtilsTest.java, V1.0.1 2013-2-25 上午11:57:08 $ */ public class XMLUtilsTest { /** * XMLUtilsTest.xml */ @Test public void test_XMLUtils() { InputStream input = null; try { input = XMLUtils.class.getResourceAsStream("/XMLUtilsTest.xml"); XMLNode root = XMLUtils.toXMLNode(input); System.out.println(root); } finally { IOUtils.closeQuietly(input); } } }
package com.example.afshindeveloper.afshindeveloperandroid; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import com.example.afshindeveloper.afshindeveloperandroid.datamodel.Post; import java.util.ArrayList; import java.util.List; import static com.android.volley.VolleyLog.TAG; /** * Created by afshindeveloper on 12/09/2017. */ public class MyAppDatabaseOpenHelper extends SQLiteOpenHelper { private static final String TAG = "DatabaseOpenHelper"; private static final String DATABASE_NAME="db_7learn"; private static final int DATABASE_VERSION=1; public static final String POST_TABLE_NAME="tbl_posts"; public static final String COL_ID = "col_id"; public static final String COL_TITLE = "col_title"; public static final String COL_CONTENT = "col_content"; public static final String COL_POST_IMAGE_URL = "col_post_image_url"; public static final String COL_IS_VISITED = "col_is_visited"; public static final String COL_DATE = "col_date"; private static final String SQL_COMMAND_CREATE_POST_TABLE = "CREATE TABLE IF NOT EXISTS " +POST_TABLE_NAME+"(" + COL_ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+ COL_TITLE+" TEXT, "+ COL_CONTENT+" TEXT, "+ COL_POST_IMAGE_URL+" TEXT, "+ COL_IS_VISITED+" INTEGER DEFAULT 0, "+ COL_DATE+" TEXT);"; Context context; public MyAppDatabaseOpenHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); this.context = context; } @Override public void onCreate(SQLiteDatabase sqLiteDatabase) { try { sqLiteDatabase.execSQL(SQL_COMMAND_CREATE_POST_TABLE); } catch (SQLException e){ Log.e(TAG,"onCreate: "+e.toString()); } } @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) { } public void addposts(List<Post> posts){ AddPostsTask addPostsTask=new AddPostsTask(context,posts,this); addPostsTask.execute(); } public List<Post> getposts(){ List<Post> posts=new ArrayList<>(); SQLiteDatabase sqLiteDatabase=this.getReadableDatabase(); Cursor cursor=sqLiteDatabase.rawQuery("SELECT * FROM "+POST_TABLE_NAME,null); cursor.moveToFirst(); if (cursor.getCount()>0){ while (!cursor.isAfterLast()){ Post post=new Post(); post.setId(cursor.getInt(0)); post.setTitle(cursor.getString(1)); post.setContent(cursor.getString(2)); post.setPostimage(cursor.getString(3)); post.setIsvisited(cursor.getInt(4)); post.setDate(cursor.getString(5)); posts.add(post); cursor.moveToNext(); } } cursor.close(); sqLiteDatabase.close(); return posts; } public void setpostisvisited(int postId,int isvisited){ SQLiteDatabase sqLiteDatabase=this.getWritableDatabase(); ContentValues contentValues=new ContentValues(); contentValues.put(COL_IS_VISITED,isvisited); int rowAffected=sqLiteDatabase.update(POST_TABLE_NAME,contentValues,COL_ID+" = ?",new String[]{String.valueOf(postId)}); Log.i(TAG, "setpostisvisited: rowaffected=> "+rowAffected); sqLiteDatabase.close(); } private boolean checkPostExists(int postId){ SQLiteDatabase sqLiteDatabase= this.getReadableDatabase(); Cursor cursor= sqLiteDatabase.rawQuery("SELECT * FROM " +POST_TABLE_NAME+" WHERE " +COL_ID+ " = ?",new String[]{String.valueOf(postId)}); return cursor.moveToFirst(); } private void deletPost(int postId){ SQLiteDatabase sqLiteDatabase=this.getWritableDatabase(); sqLiteDatabase.delete(POST_TABLE_NAME,COL_ID+" = ?",new String[]{String.valueOf(postId)} ); } }
package com.gracecode.android.btgps.ui.fragment; import android.app.Fragment; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.gracecode.android.btgps.BluetoothGPS; import com.gracecode.android.btgps.R; public class StatusFragment extends Fragment { private BroadcastReceiver mStatusReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { switch (intent.getAction()) { case BluetoothGPS.ACTION_UPDATE_LOCATION: break; case BluetoothGPS.ACTION_DEVICE_CONNECT_FAILED: break; case BluetoothGPS.ACTION_UPDATE_SENTENCE: ((TextView) getView()).setText(intent.getStringExtra(BluetoothGPS.EXTRA_SENTENCE)); break; } } }; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_status, null); } @Override public void onStart() { super.onStart(); getActivity().registerReceiver(mStatusReceiver, BluetoothGPS.getIntentFilter()); } @Override public void onStop() { super.onStop(); getActivity().unregisterReceiver(mStatusReceiver); } }
package com.fleet.mybatis.generator.config; import org.mybatis.generator.api.MyBatisGenerator; import org.mybatis.generator.config.Configuration; import org.mybatis.generator.config.xml.ConfigurationParser; import org.mybatis.generator.internal.DefaultShellCallback; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.InputStream; import java.util.ArrayList; import java.util.List; /** * @author April Han */ public class MybatisGenerator { private static final Logger logger = LoggerFactory.getLogger(MybatisGenerator.class); public static void main(String[] args) throws Exception { // 告警信息 List<String> warnings = new ArrayList<>(); ConfigurationParser cp = new ConfigurationParser(warnings); // 读取 MBG 配置文件 InputStream is = MybatisGenerator.class.getResourceAsStream("/mybatis-generator.xml"); Configuration config = cp.parseConfiguration(is); is.close(); // 当生成的代码重复时,覆盖原代码 boolean overwrite = true; DefaultShellCallback callback = new DefaultShellCallback(overwrite); MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings); myBatisGenerator.generate(null); // 输出告警信息 for (String warning : warnings) { logger.warn("【告警】:{}", warning); } } }
import java.util.Scanner; class circumference{ public static void main(String args[]){ double r, area,circum; Scanner sc = new Scanner (System.in); System.out.println("Enter radius"); r = sc.nextDouble(); area = 3.14 * r *r; System.out.println("Area of circle = "+area); circum = 2 *3.14 *r; System.out.println("Circumference of circle = "+circum); } }
package com.melonBean.controller; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import com.melonBean.dao.EmployeeMapper; import com.melonBean.entities.Employee; @Controller public class EmployeeController { @Autowired private EmployeeMapper employeeMapper ; @RequestMapping("/getEmpById") public String getEmpById(Integer id,Map model){ Employee employee = employeeMapper.getEmpById(id); model.put("emp", employee); return "emp"; } }
package controller; import handlers.DoorChain; import handlers.DoorOne; import handlers.DoorThree; import handlers.DoorTwo; import model.KeyManager; import ui.DungeonView; import ui.ScenePane; public class Controller { private static Controller instance; private KeyManager manager; private Controller() { manager = new KeyManager(); } public static Controller getInstance() { if (instance == null) { instance = new Controller(); } return instance; } public void addKey() { manager.addKey(); } public void openDoor() { DoorChain door1 = new DoorOne(); DoorChain door2 = new DoorTwo(); DoorChain door3 = new DoorThree(); door1.setNextDoor(door2); door2.setNextDoor(door3); door1.tryDoor(manager.getKey()); } public void openLeftDoor() { ScenePane.getInstance().setCenterPane(new DungeonView("Left_door_open.png").getDungeon()); } public void openMiddleDoor() { ScenePane.getInstance().setCenterPane(new DungeonView("middle_door_open.png").getDungeon()); } public void openRightDoor() { ScenePane.getInstance().setCenterPane(new DungeonView("right_door_open.png").getDungeon()); } public void newRoom() { ScenePane.getInstance().setCenterPane(new DungeonView("closed_doors.png").getDungeon()); } }
package chap07.sec04.exam01_overriding; public class Computer extends Calculator { // 어노테이션 : 컴파일러에게 코드(재정의여부)의 검증을 요청한다. @Override //메소드 재정의(overriding) double areaCircle(double r) { System.out.println("Computer 객체의 areaCircle() 실행"); return Math.PI * r * r; } }
/** **************************************************************************** * Copyright (c) The Spray Project. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Spray Dev Team - initial API and implementation **************************************************************************** */ /* * generated by Xtext */ package org.eclipselabs.spray.styles; import org.eclipse.xtext.naming.DefaultDeclarativeQualifiedNameProvider; import org.eclipselabs.spray.xtext.scoping.SprayImportedNamespaceScopeProvider; /** * Use this class to register components to be used at runtime / without the * Equinox extension registry. */ public class StyleRuntimeModule extends org.eclipselabs.spray.styles.AbstractStyleRuntimeModule { public Class<? extends org.eclipse.xtext.scoping.IScopeProvider> bindIScopeProvider() { return org.eclipselabs.spray.styles.scoping.StyleScopeProvider.class; } /** * Implicit imports */ @Override public void configureIScopeProviderDelegate(com.google.inject.Binder binder) { binder.bind(org.eclipse.xtext.scoping.IScopeProvider.class).annotatedWith(com.google.inject.name.Names.named(org.eclipse.xtext.scoping.impl.AbstractDeclarativeScopeProvider.NAMED_DELEGATE)).to(SprayImportedNamespaceScopeProvider.class); } // contributed by // org.eclipse.xtext.generator.exporting.QualifiedNamesFragment public Class<? extends org.eclipse.xtext.naming.IQualifiedNameProvider> bindIQualifiedNameProvider() { return DefaultDeclarativeQualifiedNameProvider.class; } }
package samsung.com.suveyapplication; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.samsung.provider.SamsungProvider; import com.samsung.table.tblVendedores; /** * Created by SamSunger on 5/13/2015. */ public class LoginFailAcitivity extends AppCompatActivity { private EditText txtEmail; private Button btnOK; private Button btnCancel; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.login_fail); ActionBar actionBar = getSupportActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); txtEmail = (EditText) findViewById(R.id.txtemail); btnOK = (Button) findViewById(R.id.btnok); btnCancel = (Button) findViewById(R.id.btncancel); btnOK.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (txtEmail.getText().toString().equals("")) { Toast.makeText(getBaseContext(), "Email is not null ! ", Toast.LENGTH_SHORT).show(); } else { boolean flag = checkEmail(txtEmail.getText().toString()); if (flag) { Intent i = new Intent(getBaseContext(), MainAcitivity.class); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(i); finish(); } else { txtEmail.setText(""); Toast.makeText(getBaseContext(), "Email is not correct ! ", Toast.LENGTH_SHORT).show(); } } } }); btnCancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } private boolean checkEmail(String email) { Cursor c = getContentResolver().query(SamsungProvider.URI_VENDEDORES, null, null, null, null); if (c.getCount() == 0) { return false; } while (c.moveToNext()) { String Email = c.getString(c.getColumnIndexOrThrow(tblVendedores.Email1)); if (Email.equals(email)) { return true; } } return false; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: this.finish(); return true; } return super.onOptionsItemSelected(item); } }
package com.ssm.wechatpro.dao; import java.util.List; import java.util.Map; /** * 订单列表 * */ public interface WechatOrderLogMapper { /** * 当前用户创建订单 * @param map * @throws Exception */ public void insertOrderLog(Map<String, Object> map) throws Exception; /** * 显示当前用户的全部订单(按照未付款、已付款,订单编号递降) * @param map * @return * @throws Exception */ public List<Map<String, Object>> selectByUserId(Map<String, Object> map)throws Exception; /** * 显示当前用户未付款的订单 * @param map * @return * @throws Exception */ public List<Map<String, Object>> selectByWetherPayment(Map<String, Object> map) throws Exception; /** * 根据商店id查找到最新的一条数据获取其订单编号 * @param map * @return * @throws Exception */ public Map<String, Object> selsctByShoppindId(Map<String, Object> map)throws Exception; /** * 支付订单(支付状态更改为1,更新支付时间)(通过创建人id和餐厅id) * * @param map * @throws Exception */ public void modifyOrderLog(Map<String, Object> map) throws Exception; /** * 逻辑删除该订单(已经做完给顾客)(通过创建人id和餐厅id) * @param map * @throws Exception */ public void deleteOrderLog(Map<String, Object> map) throws Exception; //查询商品的名称和价格 public Map<String,Object> selectProduct(Map<String,Object> map) throws Exception; //回显餐厅名称 public Map<String,Object> selectShopName(Map<String,Object> map) throws Exception; }
package com.test.leverton.model; /** * Created by adarshbhattarai on 4/25/18. */ public class URL { String longUrl; String shortUrl; public URL(String longUrl, String shortUrl){ this.longUrl=longUrl; this.shortUrl=shortUrl; } public String getLongUrl() { return longUrl; } public String getShortUrl() { return shortUrl; } }
package com.app.service; import org.springframework.http.ResponseEntity; import org.springframework.web.multipart.MultipartFile; import com.app.model.Employee; public interface IEmployeeService { ResponseEntity<Employee> saveEmps(MultipartFile file); }
package com.tuitaking.point2offer; import org.junit.Assert; import org.junit.Test; public class LengthOfLongestSubstring_48T { @Test public void test(){ LengthOfLongestSubstring_48 lengthOfLongestSubstring_48=new LengthOfLongestSubstring_48(); Assert.assertEquals(lengthOfLongestSubstring_48.lengthOfLongestSubstring("pwwkew"),3); Assert.assertEquals(lengthOfLongestSubstring_48.lengthOfLongestSubstring("bbbbb"),1); Assert.assertEquals(lengthOfLongestSubstring_48.lengthOfLongestSubstring("av"),2); } }
package blockchain.ledger_file.convertion; import blockchain.block.Block; import blockchain.block.Data; import blockchain.block.Header; import blockchain.utility.ByteArrayReader; import blockchain.utility.ByteUtils; import java.util.ArrayList; /* This class converts block objects to byte arrays and back */ public class BlockConverter extends Converter<Block> { private final HeaderConverter headerConverter; private final DataConverter dataConverter; public BlockConverter(short CONVERTER_VERSION_UID) { super(CONVERTER_VERSION_UID); headerConverter = new HeaderConverter(CONVERTER_VERSION_UID); dataConverter = new DataConverter(CONVERTER_VERSION_UID); } @Override // Converts a block object to a byte array public byte[] bytesFromInstance(Block block) { ArrayList<byte[]> bytes = new ArrayList<>(); bytes.add(headerConverter.bytesFromInstance(block.getHeader())); bytes.add(dataConverter.bytesFromInstance(block.getData())); return ByteUtils.combineByteArrays(bytes); } @Override // Converts a byte array to a corresponding Block object public Block instanceFromBytes(byte[] bytes) { ByteArrayReader byteReader = new ByteArrayReader(bytes); Header header = headerConverter.instanceFromBytes(byteReader.readNext(headerConverter.getByteSize(), false)); int dataByteSize = bytes.length - headerConverter.getByteSize(); Data data = dataConverter.instanceFromBytes(byteReader.readNext(dataByteSize, false)); return new Block(header, data); } @Override public short getOBJECT_TYPE_UID() { return (short) 1; } @Override // Byte size is variable public int getByteSize() { return -1; } }
package cqu.shy.resource; import java.awt.image.BufferedImage; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.ImageIcon; public class ImageResource { //欢迎界面 public static BufferedImage WelcomePlane1IMG; public static BufferedImage WelcomePlane2IMG; public static BufferedImage BackgroundIMG; //帮助界面 public static BufferedImage HelpIMG; //主机相关图片 public static BufferedImage HeroplaneIMG; public static BufferedImage HerodeathIMG; public static BufferedImage Herobullet1IMG; public static BufferedImage Herobullet2IMG; public static BufferedImage Herobullet3IMG; public static BufferedImage Herobullet4IMG; public static BufferedImage HerobulletPowerIMG; public static BufferedImage SkillZ_iconIMG; public static BufferedImage SkillZCold_iconIMG; public static BufferedImage SkillZ_leftIMG; public static BufferedImage SkillZ_middleIMG; public static BufferedImage SkillZ_rightIMG; //敌机相关图片 public static BufferedImage EnemysmallIMG; public static BufferedImage EnemymiddleIMG; public static BufferedImage EnemylargeIMG; public static BufferedImage EnemysmallbulletIMG; public static BufferedImage EnemymiddlebulletIMG; public static BufferedImage EnemylargebulletIMG; public static BufferedImage ExplosionsmallIMG; public static BufferedImage ExplosionmiddleIMG; public static BufferedImage ExplosionlargeIMG; public static BufferedImage ExplosionBulletIMG; //道具相关 public static BufferedImage item1_1IMG; public static BufferedImage item1_2IMG; public static BufferedImage item2_1IMG; public static BufferedImage item2_2IMG; public static BufferedImage item3_1IMG; public static BufferedImage item3_2IMG; public static BufferedImage item4_1IMG; public static BufferedImage item4_2IMG; //BOSS相关 public static BufferedImage Boss1IMG; public static BufferedImage Boss1_flashIMG; public static BufferedImage Boss2IMG; public static BufferedImage Boss2_flashIMG; public static BufferedImage Boss3IMG; public static BufferedImage Boss3_flashIMG; public static BufferedImage ExplosionBOSSIMG; public static BufferedImage ExplosionBOSS2IMG; public static BufferedImage BossWarningIMG; public static BufferedImage BossBullet1_1IMG; public static BufferedImage BossBullet1_2IMG; public static BufferedImage BossBullet2_1LeftIMG; public static BufferedImage BossBullet2_1MiddleIMG; public static BufferedImage BossBullet2_1RightIMG; public static BufferedImage BossBullet2_2IMG; public static BufferedImage BossBullet3_1IMG; public static BufferedImage BossBullet3_1SideIMG; public static BufferedImage BossBullet3_2IMG; //游戏通关 public static BufferedImage GameFinishIMG; static{ try { WelcomePlane1IMG= ImageIO.read(ImageResource.class.getResourceAsStream("/image/Welcome/WelcomePlane1.png")); WelcomePlane2IMG= ImageIO.read(ImageResource.class.getResourceAsStream("/image/Welcome/WelcomePlane2.png")); BackgroundIMG = ImageIO.read(ImageResource.class.getResourceAsStream("/image/Welcome/Background.png")); HelpIMG = ImageIO.read(ImageResource.class.getResourceAsStream("/image/HelpScene/Help.png")); HeroplaneIMG = ImageIO.read(ImageResource.class.getResourceAsStream("/image/Hero/hero_plane.png")); HerodeathIMG = ImageIO.read(ImageResource.class.getResourceAsStream("/image/Hero/hero_death.png")); Herobullet1IMG = ImageIO.read(ImageResource.class.getResourceAsStream("/image/Bullet/bullet_hero1.png")); Herobullet2IMG = ImageIO.read(ImageResource.class.getResourceAsStream("/image/Bullet/bullet_hero2.png")); Herobullet3IMG = ImageIO.read(ImageResource.class.getResourceAsStream("/image/Bullet/bullet_hero3.png")); Herobullet4IMG = ImageIO.read(ImageResource.class.getResourceAsStream("/image/Bullet/bullet_hero4.png")); HerobulletPowerIMG = ImageIO.read(ImageResource.class.getResourceAsStream("/image/Bullet/bullet_HeroPower.png")); SkillZ_iconIMG = ImageIO.read(ImageResource.class.getResourceAsStream("/image/Skill/skillZ_icon.png")); SkillZCold_iconIMG= ImageIO.read(ImageResource.class.getResourceAsStream("/image/Skill/skillZcold_icon.png")); SkillZ_leftIMG = ImageIO.read(ImageResource.class.getResourceAsStream("/image/Skill/skill_Z-left.png")); SkillZ_middleIMG = ImageIO.read(ImageResource.class.getResourceAsStream("/image/Skill/skill_Z.png")); SkillZ_rightIMG = ImageIO.read(ImageResource.class.getResourceAsStream("/image/Skill/skill_Z-right.png")); EnemysmallIMG = ImageIO.read(ImageResource.class.getResourceAsStream("/image/Enemy/enemy_small.png")); EnemymiddleIMG = ImageIO.read(ImageResource.class.getResourceAsStream("/image/Enemy/enemy_middle.png")); EnemylargeIMG = ImageIO.read(ImageResource.class.getResourceAsStream("/image/Enemy/enemy_large.png")); EnemysmallbulletIMG = ImageIO.read(ImageResource.class.getResourceAsStream("/image/Bullet/bullet_small.png")); EnemymiddlebulletIMG = ImageIO.read(ImageResource.class.getResourceAsStream("/image/Bullet/bullet_middle.png")); EnemylargebulletIMG = ImageIO.read(ImageResource.class.getResourceAsStream("/image/Bullet/bullet_large.png")); ExplosionsmallIMG = ImageIO.read(ImageResource.class.getResourceAsStream("/image/Explosion/Explosion_small.png")); ExplosionmiddleIMG = ImageIO.read(ImageResource.class.getResourceAsStream("/image/Explosion/Explosion_middle.png")); ExplosionlargeIMG = ImageIO.read(ImageResource.class.getResourceAsStream("/image/Explosion/Explosion_large.png")); ExplosionBulletIMG = ImageIO.read(ImageResource.class.getResourceAsStream("/image/Explosion/ExplosionBullet.png")); item1_1IMG = ImageIO.read(ImageResource.class.getResourceAsStream("/image/Item/Item1_1.png")); item1_2IMG = ImageIO.read(ImageResource.class.getResourceAsStream("/image/Item/Item1_2.png")); item2_1IMG = ImageIO.read(ImageResource.class.getResourceAsStream("/image/Item/Item2_1.png")); item2_2IMG = ImageIO.read(ImageResource.class.getResourceAsStream("/image/Item/Item2_2.png")); item3_1IMG = ImageIO.read(ImageResource.class.getResourceAsStream("/image/Item/Item3_1.png")); item3_2IMG = ImageIO.read(ImageResource.class.getResourceAsStream("/image/Item/Item3_2.png")); item4_1IMG = ImageIO.read(ImageResource.class.getResourceAsStream("/image/Item/Item4_1.png")); item4_2IMG = ImageIO.read(ImageResource.class.getResourceAsStream("/image/Item/Item4_2.png")); Boss1IMG = ImageIO.read(ImageResource.class.getResourceAsStream("/image/Boss/Boss1.png")); Boss1_flashIMG = ImageIO.read(ImageResource.class.getResourceAsStream("/image/Boss/Boss1_flash.png")); Boss2IMG = ImageIO.read(ImageResource.class.getResourceAsStream("/image/Boss/Boss2.png")); Boss2_flashIMG = ImageIO.read(ImageResource.class.getResourceAsStream("/image/Boss/Boss2_flash.png")); Boss3IMG = ImageIO.read(ImageResource.class.getResourceAsStream("/image/Boss/Boss3.png")); Boss3_flashIMG = ImageIO.read(ImageResource.class.getResourceAsStream("/image/Boss/Boss3_flash.png")); ExplosionBOSSIMG = ImageIO.read(ImageResource.class.getResourceAsStream("/image/Explosion/ExplosionBoss.png")); ExplosionBOSS2IMG = ImageIO.read(ImageResource.class.getResourceAsStream("/image/Explosion/ExplosionBoss2.png")); BossWarningIMG = ImageIO.read(ImageResource.class.getResourceAsStream("/image/Boss/BossWarning.png")); BossBullet1_1IMG = ImageIO.read(ImageResource.class.getResourceAsStream("/image/Bullet/bullet_boss1_1.png")); BossBullet1_2IMG = ImageIO.read(ImageResource.class.getResourceAsStream("/image/Bullet/bullet_boss1_2.png")); BossBullet2_1LeftIMG = ImageIO.read(ImageResource.class.getResourceAsStream("/image/Bullet/bullet_boss2_1-left.png")); BossBullet2_1RightIMG = ImageIO.read(ImageResource.class.getResourceAsStream("/image/Bullet/bullet_boss2_1-right.png")); BossBullet2_1MiddleIMG = ImageIO.read(ImageResource.class.getResourceAsStream("/image/Bullet/bullet_boss2_1.png")); BossBullet2_2IMG = ImageIO.read(ImageResource.class.getResourceAsStream("/image/Bullet/bullet_boss2_2.png")); BossBullet3_1IMG = ImageIO.read(ImageResource.class.getResourceAsStream("/image/Bullet/bullet_boss3_1.png")); BossBullet3_1SideIMG = ImageIO.read(ImageResource.class.getResourceAsStream("/image/Bullet/bullet_boss3_1-side.png")); BossBullet3_2IMG = ImageIO.read(ImageResource.class.getResourceAsStream("/image/Bullet/bullet_boss3_2.png")); GameFinishIMG = ImageIO.read(ImageResource.class.getResourceAsStream("/image/GameScene/GameFinish.png")); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
package com.sixmac.entity; import javax.persistence.*; /** * Created by Administrator on 2016/6/2 0002. */ @Entity @Table(name = "t_message_watching") public class MessageWatching extends BaseEntity { @ManyToOne @JoinColumn( name= "user_id") private User user; @ManyToOne @JoinColumn(name = "to_user_id") private User toUser; @Column(name = "type") private Integer type; @ManyToOne @JoinColumn(name = "big_race_id") private BigRace bigRace; @ManyToOne @JoinColumn(name = "watching_race_id") private WatchingRace watchingRace; @Transient private String content; public User getUser() { return user; } public void setUser(User user) { this.user = user; } public User getToUser() { return toUser; } public void setToUser(User toUser) { this.toUser = toUser; } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } public BigRace getBigRace() { return bigRace; } public void setBigRace(BigRace bigRace) { this.bigRace = bigRace; } public WatchingRace getWatchingRace() { return watchingRace; } public void setWatchingRace(WatchingRace watchingRace) { this.watchingRace = watchingRace; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } }
package com.xiaoxiao.contorller.frontline; import com.xiaoxiao.service.frontline.FrontlineHeadPhotoService; import com.xiaoxiao.utils.Result; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * _ooOoo_ * o8888888o * 88" . "88 * (| -_- |) * O\ = /O * ____/`---'\____ * .' \\| |// `. * / \\||| : |||// \ * / _||||| -:- |||||- \ * | | \\\ - /// | | * | \_| ''\---/'' | | * \ .-\__ `-` ___/-. / * ___`. .' /--.--\ `. . __ * ."" '< `.___\_<|>_/___.' >'"". * | | : `- \`.;`\ _ /`;.`/ - ` : | | * \ \ `-. \_ __\ /__ _/ .-` / / * ======`-.____`-.___\_____/___.-`____.-'====== * `=---=' * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ * 佛祖保佑 永无BUG * 佛曰: * 写字楼里写字间,写字间里程序员; * 程序人员写程序,又拿程序换酒钱。 * 酒醒只在网上坐,酒醉还来网下眠; * 酒醉酒醒日复日,网上网下年复年。 * 但愿老死电脑间,不愿鞠躬老板前; * 奔驰宝马贵者趣,公交自行程序员。 * 别人笑我忒疯癫,我笑自己命太贱; * 不见满街漂亮妹,哪个归得程序员? * * @project_name:xiaoxiao_final_blogs * @date:2019/12/23:11:41 * @author:shinelon * @Describe: */ @RestController @RequestMapping(value = "/frontline/head/photo") @CrossOrigin(origins = "*",maxAge = 3600) public class FrontlineHeadPhotoController { @Autowired private FrontlineHeadPhotoService frontlineHeadPhotoService; /** * 全部的数据 * @return */ @PostMapping(value = "/findAll") public Result findAll(){ return this.frontlineHeadPhotoService.findAll(); } }
package com.example.demo.command; import com.example.demo.model.Employee; public class EmpCommand { Employee emp; public Employee getEmp() { return emp; } public void setEmp(Employee emp) { this.emp = emp; } }
package org.jbpm.jpdl.el.impl; import org.jbpm.JbpmConfiguration.Configs; import org.jbpm.context.exe.ContextInstance; import org.jbpm.graph.exe.ExecutionContext; import org.jbpm.graph.exe.Token; import org.jbpm.jpdl.el.ELException; import org.jbpm.jpdl.el.VariableResolver; import org.jbpm.taskmgmt.exe.SwimlaneInstance; import org.jbpm.taskmgmt.exe.TaskInstance; import org.jbpm.taskmgmt.exe.TaskMgmtInstance; public class JbpmVariableResolver implements VariableResolver { public JbpmVariableResolver() { } public Object resolveVariable(String name) throws ELException { ExecutionContext executionContext = ExecutionContext.currentExecutionContext(); if ("taskInstance".equals(name)) return executionContext.getTaskInstance(); if ("processInstance".equals(name)) return executionContext.getProcessInstance(); if ("processDefinition".equals(name)) return executionContext.getProcessDefinition(); if ("token".equals(name)) return executionContext.getToken(); if ("taskMgmtInstance".equals(name)) return executionContext.getTaskMgmtInstance(); if ("contextInstance".equals(name)) return executionContext.getContextInstance(); TaskInstance taskInstance = executionContext.getTaskInstance(); if (taskInstance != null && taskInstance.hasVariableLocally(name)) { return taskInstance.getVariable(name); } ContextInstance contextInstance = executionContext.getContextInstance(); if (contextInstance != null) { Token token = executionContext.getToken(); if (contextInstance.hasVariable(name, token)) { //https://issues.jboss.org/browse/JBPM-3729 return contextInstance.getVariable(name, token); } if (contextInstance.hasTransientVariable(name)) { return contextInstance.getTransientVariable(name); } } TaskMgmtInstance taskMgmtInstance = executionContext.getTaskMgmtInstance(); if (taskMgmtInstance != null) { SwimlaneInstance swimlaneInstance = taskMgmtInstance.getSwimlaneInstance(name); if (swimlaneInstance != null) return swimlaneInstance.getActorId(); } return Configs.hasObject(name) ? Configs.getObject(name) : null; } }
package com.example.university.commands.faculty; import com.example.university.commands.Command; import com.example.university.db.FacultyDao; import com.example.university.db.FacultySubjectsDao; import com.example.university.db.SubjectDao; import com.example.university.entities.Faculty; import com.example.university.entities.FacultySubjects; import com.example.university.entities.Subject; import com.example.university.utils.Fields; import com.example.university.utils.InputValidator; import com.example.university.utils.Path; import com.example.university.utils.RequestType; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Collection; /** * Invoked when user wants to add faculty. Command allowed only for admins. */ public class AddFaculty extends Command { private static final long serialVersionUID = 1L; private static final Logger LOG = LogManager.getLogger(AddFaculty.class); @Override public String execute(HttpServletRequest request, HttpServletResponse response, RequestType requestType) throws IOException, ServletException { LOG.debug("Executing Command"); if (RequestType.GET == requestType) { return doGet(request); } return doPost(request); } /** * Forwards to add page. * * @return path to the add faculty page. */ private String doGet(HttpServletRequest request) { SubjectDao subjectDao = new SubjectDao(); Collection<Subject> allSubjects = subjectDao.findAll(); request.setAttribute("allSubjects", allSubjects); LOG.trace("Set request attribute 'allSubjects' = {}", allSubjects); return Path.FORWARD_FACULTY_ADD_ADMIN; } /** * Redirects user after submitting add faculty form. * * @return path to the view of added faculty if fields properly filled, * otherwise refreshes add Faculty page. */ private String doPost(HttpServletRequest request) { String nameRu = request.getParameter(Fields.FACULTY_NAME_RU); String nameEn = request.getParameter(Fields.FACULTY_NAME_EN); String totalPlaces = request.getParameter(Fields.FACULTY_TOTAL_PLACES); String budgetPlaces = request.getParameter(Fields.FACULTY_BUDGET_PLACES); boolean valid = InputValidator.validateFacultyParameters(nameRu, nameEn, budgetPlaces, totalPlaces); if (!valid) { setErrorMessage(request, ERROR_FILL_ALL_FIELDS); LOG.debug("errorMessage: Not all fields are properly filled"); return Path.REDIRECT_FACULTY_ADD_ADMIN; } FacultyDao facultyDao = new FacultyDao(); if (facultyDao.find(nameEn) != null || facultyDao.find(nameRu) != null) { setErrorMessage(request, ERROR_FACULTY_EXISTS); LOG.debug("Can not create faculty with names {}, {}", nameEn, nameRu); return Path.REDIRECT_FACULTY_ADD_ADMIN; } int total = Integer.parseInt(totalPlaces); int budget = Integer.parseInt(budgetPlaces); Faculty faculty = new Faculty(nameRu, nameEn, budget, total); facultyDao.create(faculty); LOG.trace("Create faculty record in database: {}", faculty); // only after creating a faculty record we can proceed with // adding faculty subjects String[] chosenSubjectsIds = request.getParameterValues("subjects"); if (chosenSubjectsIds != null) { FacultySubjectsDao fsd = new FacultySubjectsDao(); for (String subjectId : chosenSubjectsIds) { FacultySubjects facultySubject = new FacultySubjects(Integer.parseInt(subjectId), faculty.getId()); fsd.create(facultySubject); LOG.trace("FacultySubjects record created in database: {}", facultySubject); } } return Path.REDIRECT_TO_FACULTY + nameEn; } }
// ********************************************************************** // This file was generated by a TAF parser! // TAF version 3.2.1.6 by WSRD Tencent. // Generated from `/data/jcetool/taf//upload/geraldzhu/CommClientInterface.jce' // ********************************************************************** package CommonClientInterface; public final class E_PLATFORM_ID implements java.io.Serializable { private static E_PLATFORM_ID[] __values = new E_PLATFORM_ID[5]; private int __value; private String __T = new String(); public static final int _PLAT_ANDROID = 1; public static final E_PLATFORM_ID PLAT_ANDROID = new E_PLATFORM_ID(0,_PLAT_ANDROID,"PLAT_ANDROID"); public static final int _PLAT_IPHONE = 2; public static final E_PLATFORM_ID PLAT_IPHONE = new E_PLATFORM_ID(1,_PLAT_IPHONE,"PLAT_IPHONE"); public static final int _PLAT_SYB = 3; public static final E_PLATFORM_ID PLAT_SYB = new E_PLATFORM_ID(2,_PLAT_SYB,"PLAT_SYB"); public static final int _PLAT_WINDOWSPHONE = 4; public static final E_PLATFORM_ID PLAT_WINDOWSPHONE = new E_PLATFORM_ID(3,_PLAT_WINDOWSPHONE,"PLAT_WINDOWSPHONE"); public static final int _PLAT_OTHER = 10; public static final E_PLATFORM_ID PLAT_OTHER = new E_PLATFORM_ID(4,_PLAT_OTHER,"PLAT_OTHER"); public static E_PLATFORM_ID convert(int val) { for(int __i = 0; __i < __values.length; ++__i) { if(__values[__i].value() == val) { return __values[__i]; } } assert false; return null; } public static E_PLATFORM_ID convert(String val) { for(int __i = 0; __i < __values.length; ++__i) { if(__values[__i].toString().equals(val)) { return __values[__i]; } } assert false; return null; } public int value() { return __value; } public String toString() { return __T; } private E_PLATFORM_ID(int index, int val, String s) { __T = s; __value = val; __values[index] = this; } }
package kodlamaio.hrms.entities.concretes; import java.time.LocalDate; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor @Entity @Table(name="job_adverts") public class JobAdvert { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name="id") private int id; @Column(name="description") private String description; @Column(name="max_salaries") private double maxSalaries; @Column(name="min_salaries") private double minSalaries; @Column(name="vacant_position_number") private String vacantPositionNumber; @Column(name="application_start_date") private LocalDate applicationStartDate = LocalDate.now(); @Column(name="application_deadline") private LocalDate applicationDeadline; @Column(name="status") private boolean status = false; @Column(name = "is_verified") private boolean isVerified = false; @ManyToOne() @JoinColumn(name="employer_id") @JsonPropertyOrder({"companyName","website"}) private transient Employer employer; @ManyToOne() @JoinColumn(name = "city") @JsonPropertyOrder({"id","name"}) private City city; @ManyToOne() @JoinColumn(name="job_title", referencedColumnName = "id") private JobTitle jobTitle; @ManyToOne() @JoinColumn(name = "job_type") private JobType jobType; @ManyToOne() @JoinColumn(name = "job_time") private JobTime jobTime; @ManyToOne() @JoinColumn(name = "employee_id") private Employee employee; }
package Dao; import Entidades.entDepartamento; import Entidades.entDistrito; import Entidades.entProvincia; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; public class DistritoDAO { public static List<entDistrito> listarDistritoXProvincia(int IdProvincia) throws Exception { List<entDistrito> listDistrito = null; Connection conn =null; CallableStatement stmt = null; ResultSet dr = null; try { String sql="select id_Distrito,Id_Provincia,nombre from Distrito where Id_Provincia="+IdProvincia; conn = ConexionDAO.getConnection(); stmt = conn.prepareCall(sql); dr = stmt.executeQuery(); while(dr.next()) { if(listDistrito == null) listDistrito = new ArrayList<entDistrito>(); entProvincia objProvincia = new entProvincia(); objProvincia.setId_provincia(dr.getInt(2)); entDistrito objDistrito = new entDistrito(); objDistrito.setId_istrito(dr.getInt(1)); objDistrito.setNombre(dr.getString(3)); objDistrito.setObjProvincia(objProvincia); listDistrito.add(objDistrito); } } catch (Exception e) { throw new Exception("Listar Distrito "+e.getMessage(), e); } finally{ try { dr.close(); stmt.close(); conn.close(); } catch (Exception e) { } } return listDistrito; } public static entDistrito buscarId (int idDistrito) throws Exception { entDistrito objDistrito = null; Connection conn =null; CallableStatement stmt = null; ResultSet dr = null; try { String sql="select d.id_Distrito,d.id_Provincia,d.Nombre,p.nombre,x.nombre from Distrito as d inner join Provincia as p on d.id_Provincia=p.id_Provincia\n" + " inner join Departamento x on p.id_Departamento=x.id_Departamento\n" + "where d.id_Distrito="+idDistrito; conn = ConexionDAO.getConnection(); stmt = conn.prepareCall(sql); dr = stmt.executeQuery(); if(dr.next()) { entDepartamento objclsDepartamento = new entDepartamento(); objclsDepartamento.setNombre(dr.getString(5)); entProvincia objProvincia = new entProvincia(); objProvincia.setId_provincia(dr.getInt(2)); objProvincia.setNombre(dr.getString(4)); objProvincia.setObjDepartamento(objclsDepartamento); objDistrito = new entDistrito(); objDistrito.setId_istrito(dr.getInt(1)); objDistrito.setNombre(dr.getString(3)); objDistrito.setObjProvincia(objProvincia); } } catch (Exception e) { throw new Exception("Listar Distrito "+e.getMessage(), e); } finally{ try { dr.close(); stmt.close(); conn.close(); } catch (Exception e) { } } return objDistrito; } }
package ru.job4j.webarchitecturejsp.logic; import ru.job4j.webarchitecturejsp.model.User; import java.util.List; /** * Программа может работать и с БД(DBStore) и с коллекцией(MemoryStore) * Чтобы запустить приложение, необходимо после запуска TomCat вбить в браузер http://localhost:8082/chapter_007/usersjsp * Login admin passwod 1 * * */ public class ValidateService { //Тут сейчас используется коллекция. // private MemoryStore store = MemoryStore.getMemoryStore(); //Для работы с БД нужно раскомментировать следующую строку, и закомментировать предидущую private DBStore store = DBStore.getInstance(); //==========================Singletone====================================== private static ValidateService validateService; private static final class Holder { private static final ValidateService SERVICE = new ValidateService(); } public static ValidateService getValidateService() { return Holder.SERVICE; } private ValidateService() { store.addUser(new User("Uriy", "admin", "1", "ura@mail.ru", "1111", "admin", "Kyrgyzstan", "Bishkek")); store.addUser(new User("Ivan", "user", "1", "ivan@mail.ru", "1111", "user", "France", "Paris")); } //============================================================================ /** * Метод для добавления пользователя. * * @param user * @return */ public boolean add(User user) { return store.addUser(user); } /** * Метод для обновления данных пользователя. * * @param id * @param user * @return */ public boolean update(int id, User user) { return store.updateUser(id, user); } /** * Метод для удаления пользователя. * * @param id * @return */ public boolean delete(int id) { return store.deleteUser(id); } /** * Метод возвращает список всех пользователей. Сначала проверяет, есть ли в мапе хотябы 1 пользователь * @return */ public List<User> findAll() { if (store.findAll().size() > 0) { return store.findAll(); } return null; } /** * Метод поиска пользователя по id. * @param id * @return */ public User findById(int id) { return store.findById(id); } /** * Поиск пользователя по логину. * @param login * @return */ public User findByLogin(String login) { return store.findByLogin(login); } /** * Метод проверяет - существует ли пользователь с данным логином и паролем * @param login * @param password * @return */ public boolean isCredentional(String login, String password) { return store.isCredentional(login, password); } }
package com.jack.rookietest.csv; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVRecord; import java.io.*; /** * @author jack * @Classname CsvReadTest2 * Create by jack 2020/1/5 * @date: 2020/1/5 12:16 * @Description: * 官方文档:http://commons.apache.org/proper/commons-csv/user-guide.html * 使用apache的csv工具解析csv文件 * * * 参考资料: * https://www.jianshu.com/p/3eb98254fe0f?tdsourcetag=s_pcqq_aiomsg *https://blog.csdn.net/a158123/article/details/82085350 * */ public class CsvReadTest2 { public static void main(String[] args) throws IOException { String fileUlr = "F:\\20191226-YUBINMST7_mon1.csv"; //Reader in = new FileReader("path/to/file.csv"); InputStreamReader inputStreamReader = new InputStreamReader( new FileInputStream(fileUlr),"UTF-8"); BufferedReader reader = new BufferedReader(inputStreamReader); Iterable<CSVRecord> records = CSVFormat.EXCEL.parse(reader); int i = 0; for (CSVRecord record : records) { //System.out.println(record.get(0)+","); System.out.println(record.getComment()); i++; /*String lastName = record.get("Last Name"); String firstName = record.get("First Name");*/ if (i > 10) { break; } } } }
package com.p4square.ccbapi.model; /** * A collection of lookup table types supported by CCB. */ public enum LookupTableType { ABILITY, ACTIVITY, AGE_BRACKET, AREA, CHURCH_SERVICE, DEPARTMENT, EVENT_GROUPING, GIFT, GROUP_GROUPING, GROUP_TYPE, HOW_JOINED_CHURCH, HOW_THEY_HEARD, MEET_DAY, MEET_TIME, MEMBERSHIP_TYPE, PASSION, REASON_LEFT_CHURCH, SCHOOL, SCHOOL_GRADE, SIGNIFICANT_EVENT, SPIRITUAL_MATURITY, STYLE, TRANSACTION_GROUPING, UDF_GRP_PULLDOWN_1, UDF_GRP_PULLDOWN_2, UDF_GRP_PULLDOWN_3, UDF_IND_PULLDOWN_1, UDF_IND_PULLDOWN_2, UDF_IND_PULLDOWN_3, UDF_IND_PULLDOWN_4, UDF_IND_PULLDOWN_5, UDF_IND_PULLDOWN_6, UDF_RESOURCE_PULLDOWN_1; /** * @return the identifier used by the CCB API. */ public String getIdentifier() { return toString().toLowerCase(); } }
package p5; import java.io.BufferedReader; import java.io.FileReader; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.function.Function; public class P5 { ArrayList<Integer> numbers = new ArrayList<>(); ArrayList<Integer> solutions = new ArrayList<>(); HashMap<String, Function<Integer[],Integer>> functions = new HashMap<>(); public static void main(String[] args) { P5 p5 = new P5(); p5.readFile("input1.txt"); p5.doAlgorithm(); p5.getSolution(); } private void getSolution() { Collections.sort(solutions); solutions.forEach((x)-> System.out.print(x + " ")); System.out.println(" "); for(int i = 1; i< Integer.MAX_VALUE; i++) { if(!solutions.contains(i)) { System.out.println(i); break; } } } public void readFile(String filename) { try { BufferedReader reader = new BufferedReader(new FileReader(filename)); int n = Integer.parseInt(reader.readLine()); String[] splitted = reader.readLine().split(" "); for(String x : splitted) { numbers.add(Integer.parseInt(x)); solutions.add(Integer.parseInt(x)); } reader.close(); }catch(Exception e) { System.out.println("Error while reading the file"); } } public void doAlgorithm() { functions.put("*", (x)-> { return x[0] * x[1]; }); functions.put("/", (x)-> { return ( x[0] % x[1] == 0)? x[0]/x[1]: -1; }); functions.put("+", (x)-> { return x[0] + x[1]; }); functions.put("-", (x)-> { return x[0] - x[1]; }); ArrayList<String> operations = new ArrayList<>(); operations.add("*"); operations.add("+"); operations.add("-"); operations.add("/"); for(int number : numbers) { ArrayList<Integer> copy = (ArrayList<Integer>) numbers.clone(); copy.remove(copy.indexOf(number)); startGenerating(number, copy, operations ); } } private void startGenerating(Integer number, ArrayList<Integer> copy, ArrayList<String> operations) { Integer copyNumber = number.intValue(); if(copy.size()== 0 || operations.size() == 0) { } for(int i= 0; i< copy.size(); i++) { int nextNum = copy.get(i); ArrayList<Integer> copyClone = (ArrayList<Integer>) copy.clone(); copyClone.remove(copyClone.indexOf(nextNum)); for(int j = 0; j<operations.size(); j++) { copyNumber = functions.get(operations.get(j)).apply(new Integer[]{ number, nextNum}); if(copyNumber < 0) continue; ArrayList<String> copyOperations =(ArrayList<String>) operations.clone(); copyOperations.remove(copyOperations.indexOf(operations.get(j))); solutions.add(copyNumber); startGenerating(copyNumber, copyClone, copyOperations); } copyNumber = number; } } }
package com.tencent.mm.plugin.luckymoney.appbrand.ui.prepare; import android.content.Intent; import com.tencent.mm.plugin.luckymoney.appbrand.a.e; import com.tencent.mm.protocal.c.bhg; import com.tencent.mm.protocal.c.bhh; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.ui.MMActivity.a; public final class d implements a, a { private String appId = null; boolean kMA; final int kMB = (hashCode() & 65535); c kMy; bhh kMz; public final /* synthetic */ void a(Object obj, Intent intent) { c cVar = (c) obj; x.i("MicroMsg.WxaPrepareLuckyMoneyLogic", "onCreate "); this.appId = intent.getStringExtra("appId"); this.kMy = cVar; } public final void onDestroy() { x.i("MicroMsg.WxaPrepareLuckyMoneyLogic", "onDestroy "); this.kMy = null; } public final void b(int i, int i2, String str, int i3) { x.i("MicroMsg.WxaPrepareLuckyMoneyLogic", "prepareRandomLuckyMoney() called with: moneyTotalAmount = [" + i + "], packageAmount = [" + i2 + "], wishing = [" + str + "], scope = [" + i3 + "]"); if (this.kMy != null) { bhg bhg = new bhg(); bhg.bPS = this.appId; bhg.kLe = 1; bhg.qYf = i2; bhg.sbh = (long) i; bhg.kLf = str; bhg.sie = i3; a(bhg); } } public final void c(int i, int i2, String str, int i3) { x.i("MicroMsg.WxaPrepareLuckyMoneyLogic", "prepareFixLuckyMoney() called with: packageMoneyAmount = [" + i + "], packageAmount = [" + i2 + "], wishing = [" + str + "], scope = [" + i3 + "]"); if (this.kMy != null) { bhg bhg = new bhg(); bhg.bPS = this.appId; bhg.kLe = 0; bhg.qYf = i2; bhg.sid = i; bhg.kLf = str; bhg.sie = i3; a(bhg); } } private void a(bhg bhg) { x.i("MicroMsg.WxaPrepareLuckyMoneyLogic", "prepareImpl "); if (this.kMA) { x.i("MicroMsg.WxaPrepareLuckyMoneyLogic", "prepareImpl isRequesting"); return; } this.kMA = true; new e(bhg).b(new 1(this)); } final void Q(Intent intent) { this.kMA = false; if (this.kMy != null) { this.kMy.b(0, intent); } } public final void b(int i, int i2, Intent intent) { x.i("MicroMsg.WxaPrepareLuckyMoneyLogic", "mmOnActivityResult() called with: requestCode = [" + i + "], resultCode = [" + i2 + "], data = [" + intent + "]"); if (i != this.kMB) { return; } if (i2 == -1) { this.kMy.a(b.class, new Intent(), new 2(this)); return; } x.i("MicroMsg.WxaPrepareLuckyMoneyLogic", "mmOnActivityResult() REQUEST_CODE_WALLET called cancel "); Q(new Intent().putExtra("result_error_code", 10001).putExtra("result_error_msg", "fail:pay fail")); } }
package com.javarush.task.task27.task2708; import java.util.Set; /* Убираем deadLock используя открытые вызовы */ public class Solution { public static void main(String[] args) { final long deadLineTime = System.currentTimeMillis() + 5000; //waiting for 5 sec final RealEstate realEstate = new RealEstate(); Set<Apartment> allApartments = realEstate.getAllApartments(); final Apartment[] apartments = allApartments.toArray(new Apartment[allApartments.size()]); for (int i = 0; i < 20; i++) { new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < 10; i++) { realEstate.revalidate(); } } }, "RealEstateThread" + i).start(); new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < apartments.length; i++) { apartments[i].revalidate(true); } } }, "ApartmentThread" + i).start(); } Thread deamonThread = new Thread(new Runnable() { @Override public void run() { while (System.currentTimeMillis() < deadLineTime) try { Thread.sleep(2); } catch (InterruptedException ignored) { } System.out.println("The dead lock occurred"); } }); deamonThread.setDaemon(true); deamonThread.start(); } public class RealEstate { private final Set<Apartment> allApartments; private final Set<Apartment> activeApartments; public RealEstate() { allApartments = new HashSet(); activeApartments = new HashSet(); //add some data allApartments.add(new Apartment(this)); allApartments.add(new Apartment(this)); allApartments.add(new Apartment(this)); allApartments.add(new Apartment(this)); allApartments.add(new Apartment(this)); allApartments.add(new Apartment(this)); } public Set<Apartment> getAllApartments() { return allApartments; } public void up(Apartment apartment) { activeApartments.add(apartment); } public void revalidate() { Set<Apartment> copy; synchronized (this) { copy = new HashSet<>(allApartments); activeApartments.clear(); for (Apartment apartment : copy) { boolean randomValue = Math.random() * 2 % 2 == 0; apartment.revalidate(randomValue); } } } public class Apartment { private String location; private final RealEstate realEstate; public Apartment(RealEstate realEstate) { this.realEstate = realEstate; setLocation(String.valueOf(Math.random() * 10)); } public String getLocation() { return location; } public void setLocation(String location) { synchronized (this) { this.location = location; } } public void revalidate(boolean isEmpty) { if (isEmpty) { realEstate.up(this); } } } } }
package PresentationLayer.View; import javax.swing.*; import java.awt.*; import java.awt.event.ActionListener; /** * The type Client view. */ public class ClientView extends JFrame { private JButton searchProductsBtn = new JButton(" Search "); private JButton createNewOrderBtn = new JButton("Create Order"); private JButton viewProductsBtn = new JButton("View Products"); private JButton addProductsBtn = new JButton("Add"); private JTextField priceText = new JTextField(); private JTextField idProductText = new JTextField(); private JTextField titleText = new JTextField(); private JTextField ratingText = new JTextField(); private JTextField caloriesText = new JTextField(); private JTextField proteinText = new JTextField(); private JTextField fatText = new JTextField(); private JTextField sodiumText = new JTextField(); private JTextField priceProductText = new JTextField(); /** * Instantiates a new Client view. */ public ClientView(){ this.setTitle("Client Frame"); //this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setSize(450,750); this.setLocationRelativeTo(null); this.setVisible(true); this.setLayout(null); this.getContentPane().setBackground(new Color(245, 255, 255, 111)); titleText.setPreferredSize(new Dimension(100, 30)); ratingText.setPreferredSize(new Dimension(100, 30)); caloriesText.setPreferredSize(new Dimension(100, 30)); proteinText.setPreferredSize(new Dimension(100, 30)); fatText.setPreferredSize(new Dimension(100, 30)); sodiumText.setPreferredSize(new Dimension(100, 30)); priceProductText.setPreferredSize(new Dimension(100, 30)); priceText.setPreferredSize(new Dimension(100, 30)); priceText.setEditable(false); idProductText.setPreferredSize(new Dimension(50 , 30)); JPanel createOrderPanel = new JPanel(); createOrderPanel.setBounds(0,50,450,100); createOrderPanel.add(new JLabel("Add a product ")); createOrderPanel.add(idProductText); createOrderPanel.add(addProductsBtn); createOrderPanel.add(new JLabel("Total ")); createOrderPanel.add(priceText); createOrderPanel.add(createNewOrderBtn); JPanel titlePanel = new JPanel(); titlePanel.setBounds(50,200,250,50); titlePanel.add(new JLabel(" title ")); titlePanel.add(titleText); JPanel ratingPanel = new JPanel(); ratingPanel.setBounds(50,250,250,50); ratingPanel.add(new JLabel(" >= rating")); ratingPanel.add(ratingText); JPanel caloriesPanel = new JPanel(); caloriesPanel.setBounds(50,300,250,50); caloriesPanel.add(new JLabel(" <= calories")); caloriesPanel.add(caloriesText); JPanel proteinPanel = new JPanel(); proteinPanel.setBounds(50,350,250,50); proteinPanel.add(new JLabel(" <= protein")); proteinPanel.add(proteinText); JPanel fatPanel = new JPanel(); fatPanel.setBounds(50,400,250,50); fatPanel.add(new JLabel(" <= fat ")); fatPanel.add(fatText); JPanel sodiumPanel = new JPanel(); sodiumPanel.setBounds(50,450,250,50); sodiumPanel.add(new JLabel(" <= sodium")); sodiumPanel.add(sodiumText); JPanel priceProductPanel = new JPanel(); priceProductPanel.setBounds(50,500,250,50); priceProductPanel.add(new JLabel(" <= price ")); priceProductPanel.add(priceProductText); JPanel searchPanel = new JPanel(); searchPanel.setBounds(0,550,200,50); //searchPanel.add(new JLabel(" Search ")); searchPanel.add(searchProductsBtn); JPanel viewPanel = new JPanel(); viewPanel.setBounds(120,150,200,50); viewPanel.add(viewProductsBtn); JPanel allPanels = new JPanel(); allPanels.add(createOrderPanel); allPanels.add(searchPanel); allPanels.add(titlePanel); allPanels.add(sodiumPanel); allPanels.add(ratingPanel); allPanels.add(caloriesPanel); allPanels.add(fatPanel); allPanels.add(priceProductPanel); allPanels.add(proteinPanel); allPanels.add(viewPanel); allPanels.setLayout(null); this.setContentPane(allPanels); } /** * Addsearch products btn. * * @param act the act */ public void addsearchProductsBtn(ActionListener act){ searchProductsBtn.addActionListener(act); } /** * Add view product btn. * * @param act the act */ public void addViewProductBtn(ActionListener act){ viewProductsBtn.addActionListener(act); } /** * Add add product btn. * * @param act the act */ public void addAddProductBtn(ActionListener act){ addProductsBtn.addActionListener(act); } /** * Add create order btn. * * @param act the act */ public void addCreateOrderBtn(ActionListener act){ createNewOrderBtn.addActionListener(act); } /** * Gets price text. * * @return the price text */ public String getPriceText() { return priceText.getText(); } /** * Sets price text. * * @param priceText the price text */ public void setPriceText(String priceText) { this.priceText.setText(priceText); } /** * Gets id product text. * * @return the id product text */ public String getIdProductText() { return idProductText.getText(); } /** * Gets title text. * * @return the title text */ public String getTitleText() { return titleText.getText(); } /** * Gets rating text. * * @return the rating text */ public String getRatingText() { return ratingText.getText(); } /** * Gets calories text. * * @return the calories text */ public String getCaloriesText() { return caloriesText.getText(); } /** * Gets protein text. * * @return the protein text */ public String getProteinText() { return proteinText.getText(); } /** * Gets fat text. * * @return the fat text */ public String getFatText() { return fatText.getText(); } /** * Gets sodium text. * * @return the sodium text */ public String getSodiumText() { return sodiumText.getText(); } /** * Gets price product text. * * @return the price product text */ public String getPriceProductText() { return priceProductText.getText(); } }
package org.stepik.api.objects.recommendations; /** * @author meanmail */ public class ReactionPost { private int reaction; private String lesson; private String user; public int getReaction() { return reaction; } public void setReaction(int reaction) { this.reaction = reaction; } public long getLesson() { if (lesson == null) { lesson = "0"; } try { return Long.valueOf(lesson); } catch (NumberFormatException e) { return 0; } } public void setLesson(long lesson) { this.lesson = String.valueOf(lesson); } public long getUser() { if (user == null) { user = "0"; } try { return Long.valueOf(user); } catch (NumberFormatException e) { return 0; } } public void setUser(long user) { this.user = String.valueOf(user); } }
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2015.09.03 at 09:19:50 PM EDT // package org.oasisopen.xliff; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for stateValueList. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="stateValueList"> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}NMTOKEN"> * &lt;enumeration value="final"/> * &lt;enumeration value="needs-adaptation"/> * &lt;enumeration value="needs-l10n"/> * &lt;enumeration value="needs-review-adaptation"/> * &lt;enumeration value="needs-review-l10n"/> * &lt;enumeration value="needs-review-translation"/> * &lt;enumeration value="needs-translation"/> * &lt;enumeration value="new"/> * &lt;enumeration value="signed-off"/> * &lt;enumeration value="translated"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */ @XmlType(name = "stateValueList") @XmlEnum public enum StateValueList { /** * Indicates the terminating state. * */ @XmlEnumValue("final") FINAL("final"), /** * Indicates only non-textual information needs adaptation. * */ @XmlEnumValue("needs-adaptation") NEEDS_ADAPTATION("needs-adaptation"), /** * Indicates both text and non-textual information needs adaptation. * */ @XmlEnumValue("needs-l10n") NEEDS_L_10_N("needs-l10n"), /** * Indicates only non-textual information needs review. * */ @XmlEnumValue("needs-review-adaptation") NEEDS_REVIEW_ADAPTATION("needs-review-adaptation"), /** * Indicates both text and non-textual information needs review. * */ @XmlEnumValue("needs-review-l10n") NEEDS_REVIEW_L_10_N("needs-review-l10n"), /** * Indicates that only the text of the item needs to be reviewed. * */ @XmlEnumValue("needs-review-translation") NEEDS_REVIEW_TRANSLATION("needs-review-translation"), /** * Indicates that the item needs to be translated. * */ @XmlEnumValue("needs-translation") NEEDS_TRANSLATION("needs-translation"), /** * Indicates that the item is new. For example, translation units that were not in a previous version of the document. * */ @XmlEnumValue("new") NEW("new"), /** * Indicates that changes are reviewed and approved. * */ @XmlEnumValue("signed-off") SIGNED_OFF("signed-off"), /** * Indicates that the item has been translated. * */ @XmlEnumValue("translated") TRANSLATED("translated"); private final String value; StateValueList(String v) { value = v; } public String value() { return value; } public static StateValueList fromValue(String v) { for (StateValueList c: StateValueList.values()) { if (c.value.equals(v)) { return c; } } throw new IllegalArgumentException(v); } }
package Execucao; import InterpretadorDoPrograma.*; import Lista.*; import Memoria.*; import Excecoes.*; public class SolverDeExpressoes { public static ManipuladorDaLista pilha = new ManipuladorDaLista(); private static Lista<SimbolosCefetiny> exp = new Lista<SimbolosCefetiny>(); public static SimbolosCefetiny solve(Lista<SimbolosCefetiny> expressao){ exp = expressao; exp =toPosfix(exp); ManipuladorDaLista<SimbolosCefetiny> aux = new ManipuladorDaLista<>(); for(int i=0;i<exp.getTamanho();i++){ if(exp.get(i).getToken()==ContantesDaLinguagem.T_IDENTIFIER){ String a = exp.get(i).getLexema(); exp.set(i, Memoria.get(a)); } } for(int i=0;i<exp.getTamanho();i++){ if(exp.get(i).getToken()== ContantesDaLinguagem.T_CONSTANT) aux.push(exp.get(i)); else{ SimbolosCefetiny op1,op2, res; switch(exp.get(i).getLexema()){ case("+"): op1=aux.pop(); op2=aux.pop(); if(op1.getTipo()== op2.getTipo() && (op1.getTipo() == ContantesDaLinguagem.T_INTEGER || op1.getTipo() == ContantesDaLinguagem.T_DOUBLE || op1.getTipo() == ContantesDaLinguagem.T_STRING)){ if(op1.getTipo()==ContantesDaLinguagem.T_INTEGER){ res = new SimbolosCefetiny(ContantesDaLinguagem.T_CONSTANT,(String.valueOf(Integer.parseInt(op1.getLexema()) + Integer.parseInt(op2.getLexema())))); res.setTipo(ContantesDaLinguagem.T_INTEGER); } else if(op1.getTipo()==ContantesDaLinguagem.T_DOUBLE){ res = new SimbolosCefetiny(ContantesDaLinguagem.T_CONSTANT,(String.valueOf(Double.parseDouble(op1.getLexema()) + Double.parseDouble(op2.getLexema())))); res.setTipo(ContantesDaLinguagem.T_DOUBLE); } else{ res = new SimbolosCefetiny(ContantesDaLinguagem.T_CONSTANT,(op2.getLexema()+op1.getLexema())); res.setTipo(ContantesDaLinguagem.T_STRING); } aux.push(res); } else if((op1.getTipo() == ContantesDaLinguagem.T_INTEGER && op2.getTipo() == ContantesDaLinguagem.T_DOUBLE) || (op1.getTipo() == ContantesDaLinguagem.T_DOUBLE && op2.getTipo() == ContantesDaLinguagem.T_INTEGER)){ res = new SimbolosCefetiny(ContantesDaLinguagem.T_CONSTANT,String.valueOf(Double.parseDouble(op2.getLexema()) + Double.parseDouble(op1.getLexema()))); res.setTipo(ContantesDaLinguagem.T_DOUBLE); aux.push(res); } else if((op1.getTipo() != op2.getTipo()) && (op1.getTipo() == ContantesDaLinguagem.T_STRING || op2.getTipo() == ContantesDaLinguagem.T_STRING)){ res = new SimbolosCefetiny(ContantesDaLinguagem.T_CONSTANT,String.valueOf((op2.getLexema()) + (op1.getLexema()))); res.setTipo(ContantesDaLinguagem.T_STRING); aux.push(res); } else throw new FalhaErroDeSintaxe("Operandos invalidos para o operador \"+\" "); break; case("-"): op1=aux.pop(); op2=aux.pop(); if(op1.getTipo()== op2.getTipo() && (op1.getTipo() == ContantesDaLinguagem.T_INTEGER || op1.getTipo() == ContantesDaLinguagem.T_DOUBLE)){ if(op1.getTipo()==ContantesDaLinguagem.T_DOUBLE){ res = new SimbolosCefetiny(ContantesDaLinguagem.T_CONSTANT,(String.valueOf(Double.parseDouble(op2.getLexema()) - Double.parseDouble(op1.getLexema())))); res.setTipo(ContantesDaLinguagem.T_DOUBLE); } else{ res = new SimbolosCefetiny(ContantesDaLinguagem.T_CONSTANT,(String.valueOf(Integer.parseInt(op2.getLexema()) - Integer.parseInt(op1.getLexema())))); res.setTipo(ContantesDaLinguagem.T_INTEGER); } aux.push(res); } else if((op1.getTipo() == ContantesDaLinguagem.T_INTEGER || op1.getTipo() == ContantesDaLinguagem.T_DOUBLE) && (op2.getTipo() == ContantesDaLinguagem.T_DOUBLE || op2.getTipo() == ContantesDaLinguagem.T_INTEGER)){ res = new SimbolosCefetiny(ContantesDaLinguagem.T_CONSTANT,String.valueOf(Double.parseDouble(op2.getLexema()) - Double.parseDouble(op1.getLexema()))); res.setTipo(ContantesDaLinguagem.T_DOUBLE); aux.push(res); } else throw new FalhaErroDeSintaxe("Operandos invalidos para o operador \"-\" "); break; case("*"): op1=aux.pop(); op2=aux.pop(); if(op1.getTipo()== op2.getTipo() && (op1.getTipo() == ContantesDaLinguagem.T_INTEGER || op1.getTipo() == ContantesDaLinguagem.T_DOUBLE)){ if(op1.getTipo()==ContantesDaLinguagem.T_DOUBLE){ res = new SimbolosCefetiny(ContantesDaLinguagem.T_CONSTANT,String.valueOf(Double.parseDouble(op2.getLexema()) * Double.parseDouble(op1.getLexema()))); res.setTipo(ContantesDaLinguagem.T_DOUBLE); } else{ res = new SimbolosCefetiny(ContantesDaLinguagem.T_CONSTANT,String.valueOf(Integer.parseInt(op2.getLexema()) * Integer.parseInt(op1.getLexema()))); res.setTipo(ContantesDaLinguagem.T_DOUBLE); } aux.push(res); } else if((op1.getTipo() == ContantesDaLinguagem.T_INTEGER || op1.getTipo() == ContantesDaLinguagem.T_DOUBLE) && (op2.getTipo() == ContantesDaLinguagem.T_DOUBLE || op2.getTipo() == ContantesDaLinguagem.T_INTEGER)){ res = new SimbolosCefetiny(ContantesDaLinguagem.T_CONSTANT,String.valueOf(Double.parseDouble(op2.getLexema()) * Double.parseDouble(op1.getLexema()))); res.setTipo(ContantesDaLinguagem.T_DOUBLE); aux.push(res); } else throw new FalhaErroDeSintaxe("Operandos invalidos para o operador \"*\" "); break; case("div"): op1=aux.pop(); op2=aux.pop(); if(op1.getTipo()== op2.getTipo() && (op1.getTipo() == ContantesDaLinguagem.T_INTEGER)){ res = new SimbolosCefetiny(ContantesDaLinguagem.T_CONSTANT,String.valueOf(Integer.parseInt(op2.getLexema()) / Integer.parseInt(op1.getLexema()))); res.setTipo(ContantesDaLinguagem.T_INTEGER); aux.push(res); } else throw new FalhaErroDeSintaxe("Operandos invalidos para o operador \"div\" "); break; case("^"): op1=aux.pop(); op2=aux.pop(); if((op1.getTipo() == ContantesDaLinguagem.T_INTEGER || op1.getTipo() == ContantesDaLinguagem.T_DOUBLE) && (op2.getTipo() == ContantesDaLinguagem.T_INTEGER || op2.getTipo() == ContantesDaLinguagem.T_DOUBLE)){ res = new SimbolosCefetiny(ContantesDaLinguagem.T_CONSTANT,String.valueOf(Math.pow(Double.parseDouble(op2.getLexema()),Double.parseDouble(op1.getLexema())))); res.setTipo(ContantesDaLinguagem.T_DOUBLE); aux.push(res); } else throw new FalhaErroDeSintaxe("Operandos invalidos para o operador \"^\" "); break; case("/"): op1=aux.pop(); op2=aux.pop(); if(op1.getTipo()== op2.getTipo() && (op1.getTipo() == ContantesDaLinguagem.T_INTEGER || op1.getTipo() == ContantesDaLinguagem.T_DOUBLE)){ if(op1.getTipo()==ContantesDaLinguagem.T_DOUBLE){ res = new SimbolosCefetiny(ContantesDaLinguagem.T_CONSTANT,String.valueOf(Double.parseDouble(op2.getLexema()) / Double.parseDouble(op1.getLexema()))); res.setTipo(ContantesDaLinguagem.T_DOUBLE); } else{ res = new SimbolosCefetiny(ContantesDaLinguagem.T_CONSTANT,String.valueOf(Integer.parseInt(op2.getLexema()) / Integer.parseInt(op1.getLexema()))); res.setTipo(ContantesDaLinguagem.T_INTEGER); } aux.push(res); } else if((op1.getTipo() == ContantesDaLinguagem.T_INTEGER || op1.getTipo() == ContantesDaLinguagem.T_DOUBLE) && (op2.getTipo() == ContantesDaLinguagem.T_DOUBLE || op2.getTipo() == ContantesDaLinguagem.T_INTEGER)){ res = new SimbolosCefetiny(ContantesDaLinguagem.T_CONSTANT,String.valueOf(Double.parseDouble(op2.getLexema()) / Double.parseDouble(op1.getLexema()))); res.setTipo(ContantesDaLinguagem.T_DOUBLE); aux.push(res); } else throw new FalhaErroDeSintaxe("Operandos invalidos para o operador \"/\" "); break; case("sqrt"): op1=aux.pop(); if(op1.getTipo() == ContantesDaLinguagem.T_INTEGER || op1.getTipo() == ContantesDaLinguagem.T_DOUBLE){ res= new SimbolosCefetiny(ContantesDaLinguagem.T_CONSTANT,String.valueOf(Math.sqrt(Double.parseDouble(op1.getLexema())))); res.setTipo(ContantesDaLinguagem.T_DOUBLE); aux.push(res); } else throw new FalhaErroDeSintaxe("Operando invalido para o operador \"sqrt\" "); break; case("mod"): op1=aux.pop(); op2=aux.pop(); if(op1.getTipo()== op2.getTipo() && (op1.getTipo() == ContantesDaLinguagem.T_INTEGER || op1.getTipo() == ContantesDaLinguagem.T_DOUBLE)){ if(op1.getTipo()==ContantesDaLinguagem.T_DOUBLE){ res= new SimbolosCefetiny(ContantesDaLinguagem.T_CONSTANT,String.valueOf(Double.parseDouble(op2.getLexema()) % Double.parseDouble(op1.getLexema()))); res.setTipo(ContantesDaLinguagem.T_DOUBLE); } else{ res= new SimbolosCefetiny(ContantesDaLinguagem.T_CONSTANT,String.valueOf(Integer.parseInt(op2.getLexema()) % Integer.parseInt(op1.getLexema()))); res.setTipo(ContantesDaLinguagem.T_INTEGER); } aux.push(res); } else if((op1.getTipo() == ContantesDaLinguagem.T_INTEGER || op1.getTipo() == ContantesDaLinguagem.T_DOUBLE) && (op2.getTipo() == ContantesDaLinguagem.T_DOUBLE || op2.getTipo() == ContantesDaLinguagem.T_INTEGER)){ res= new SimbolosCefetiny(ContantesDaLinguagem.T_CONSTANT,String.valueOf(Double.parseDouble(op2.getLexema()) % Double.parseDouble(op1.getLexema()))); res.setTipo(ContantesDaLinguagem.T_DOUBLE); aux.push(res); } else throw new FalhaErroDeSintaxe("Operandos invalidos para o operador \"mod\" "); break; case("not"): op1=aux.pop(); if(op1.getTipo() == ContantesDaLinguagem.T_BOOLEAN){ res = new SimbolosCefetiny(ContantesDaLinguagem.T_CONSTANT,String.valueOf(!(Boolean.parseBoolean(op1.getLexema())))); res.setTipo(ContantesDaLinguagem.T_BOOLEAN); aux.push(res); } else throw new FalhaErroDeSintaxe("Operando invalido para o operador \"not\" "); break; case("or"): op1=aux.pop(); op2=aux.pop(); if(op1.getTipo() == ContantesDaLinguagem.T_BOOLEAN && op2.getTipo() == ContantesDaLinguagem.T_BOOLEAN){ res = new SimbolosCefetiny(ContantesDaLinguagem.T_CONSTANT,String.valueOf((Boolean.parseBoolean(op1.getLexema())) || (Boolean.parseBoolean(op2.getLexema())))); res.setTipo(ContantesDaLinguagem.T_BOOLEAN); aux.push(res); } else throw new FalhaErroDeSintaxe("Operando invalido para o operador \"or\" "); break; case("and"): op1=aux.pop(); op2=aux.pop(); if(op1.getTipo() == ContantesDaLinguagem.T_BOOLEAN && op2.getTipo() == ContantesDaLinguagem.T_BOOLEAN){ res = new SimbolosCefetiny(ContantesDaLinguagem.T_CONSTANT,String.valueOf((Boolean.parseBoolean(op1.getLexema())) && (Boolean.parseBoolean(op2.getLexema())))); res.setTipo(ContantesDaLinguagem.T_BOOLEAN); aux.push(res); } else throw new FalhaErroDeSintaxe("Operando invalido para o operador \"and\" "); break; case("="): op1=aux.pop(); op2=aux.pop(); if(op1.getTipo() == ContantesDaLinguagem.T_BOOLEAN && op2.getTipo() == ContantesDaLinguagem.T_BOOLEAN){ res = new SimbolosCefetiny(ContantesDaLinguagem.T_CONSTANT,String.valueOf((Boolean.parseBoolean(op1.getLexema())) == (Boolean.parseBoolean(op2.getLexema())))); res.setTipo(ContantesDaLinguagem.T_BOOLEAN); aux.push(res); } else if((op1.getTipo() == ContantesDaLinguagem.T_DOUBLE || op1.getTipo() == ContantesDaLinguagem.T_INTEGER) && (op2.getTipo() == ContantesDaLinguagem.T_DOUBLE || op2.getTipo() == ContantesDaLinguagem.T_INTEGER)){ res = new SimbolosCefetiny(ContantesDaLinguagem.T_CONSTANT,String.valueOf((Double.parseDouble(op2.getLexema())) == (Double.parseDouble(op1.getLexema())))); res.setTipo(ContantesDaLinguagem.T_BOOLEAN); aux.push(res); } else if(op1.getTipo()==ContantesDaLinguagem.T_STRING && op2.getTipo()==ContantesDaLinguagem.T_STRING){ res = new SimbolosCefetiny(ContantesDaLinguagem.T_CONSTANT,String.valueOf(op1.getLexema().equals(op2.getLexema()))); res.setTipo(ContantesDaLinguagem.T_BOOLEAN); aux.push(res); } else throw new FalhaErroDeSintaxe("Operando invalido para o operador \"=\" "); break; case("<>"): op1=aux.pop(); op2=aux.pop(); if(op1.getTipo() == ContantesDaLinguagem.T_BOOLEAN && op2.getTipo() == ContantesDaLinguagem.T_BOOLEAN){ res = new SimbolosCefetiny(ContantesDaLinguagem.T_CONSTANT,String.valueOf((Boolean.parseBoolean(op1.getLexema())) != (Boolean.parseBoolean(op2.getLexema())))); res.setTipo(ContantesDaLinguagem.T_BOOLEAN); aux.push(res); } else if((op1.getTipo() == ContantesDaLinguagem.T_DOUBLE || op1.getTipo() == ContantesDaLinguagem.T_INTEGER) && (op2.getTipo() == ContantesDaLinguagem.T_DOUBLE || op2.getTipo() == ContantesDaLinguagem.T_INTEGER)){ res = new SimbolosCefetiny(ContantesDaLinguagem.T_CONSTANT,String.valueOf((Double.parseDouble(op2.getLexema())) != (Double.parseDouble(op1.getLexema())))); res.setTipo(ContantesDaLinguagem.T_BOOLEAN); aux.push(res); } else throw new FalhaErroDeSintaxe("Operando invalido para o operador \"<>\" "); break; case(">"): op1=aux.pop(); op2=aux.pop(); if((op1.getTipo() == ContantesDaLinguagem.T_DOUBLE || op1.getTipo() == ContantesDaLinguagem.T_INTEGER) && (op2.getTipo() == ContantesDaLinguagem.T_DOUBLE || op2.getTipo() == ContantesDaLinguagem.T_INTEGER)){ res = new SimbolosCefetiny(ContantesDaLinguagem.T_CONSTANT,String.valueOf((Double.parseDouble(op2.getLexema())) > (Double.parseDouble(op1.getLexema())))); res.setTipo(ContantesDaLinguagem.T_BOOLEAN); aux.push(res); } else throw new FalhaErroDeSintaxe("Operando invalido para o operador \">\" "); break; case(">="): op1=aux.pop(); op2=aux.pop(); if((op1.getTipo() == ContantesDaLinguagem.T_DOUBLE || op1.getTipo() == ContantesDaLinguagem.T_INTEGER) && (op2.getTipo() == ContantesDaLinguagem.T_DOUBLE || op2.getTipo() == ContantesDaLinguagem.T_INTEGER)){ res = new SimbolosCefetiny(ContantesDaLinguagem.T_CONSTANT,String.valueOf((Double.parseDouble(op2.getLexema())) >= (Double.parseDouble(op1.getLexema())))); res.setTipo(ContantesDaLinguagem.T_BOOLEAN); aux.push(res); } else throw new FalhaErroDeSintaxe("Operando invalido para o operador \">=\" "); break; case("<"): op1=aux.pop(); op2=aux.pop(); if((op1.getTipo() == ContantesDaLinguagem.T_DOUBLE || op1.getTipo() == ContantesDaLinguagem.T_INTEGER) && (op2.getTipo() == ContantesDaLinguagem.T_DOUBLE || op2.getTipo() == ContantesDaLinguagem.T_INTEGER)){ res = new SimbolosCefetiny(ContantesDaLinguagem.T_CONSTANT,String.valueOf((Double.parseDouble(op2.getLexema())) < (Double.parseDouble(op1.getLexema())))); res.setTipo(ContantesDaLinguagem.T_BOOLEAN); aux.push(res); } else throw new FalhaErroDeSintaxe("Operando invalido para o operador \"<\" "); break; case("<="): op1=aux.pop(); op2=aux.pop(); if((op1.getTipo() == ContantesDaLinguagem.T_DOUBLE || op1.getTipo() == ContantesDaLinguagem.T_INTEGER) && (op2.getTipo() == ContantesDaLinguagem.T_DOUBLE || op2.getTipo() == ContantesDaLinguagem.T_INTEGER)){ res = new SimbolosCefetiny(ContantesDaLinguagem.T_CONSTANT,String.valueOf((Double.parseDouble(op2.getLexema())) <= (Double.parseDouble(op1.getLexema())))); res.setTipo(ContantesDaLinguagem.T_BOOLEAN); aux.push(res); } else throw new FalhaErroDeSintaxe("Operando invalido para o operador \"<=\" "); break; } } } return aux.pop(); } public static Lista<SimbolosCefetiny> toPosfix(Lista<SimbolosCefetiny> exp){ Lista<SimbolosCefetiny> pos = new Lista<>(); ManipuladorDaLista<SimbolosCefetiny> aux = new ManipuladorDaLista<>(); int abriuPar = 0; for(int i=0;i<exp.getTamanho();i++){ if(exp.get(i).getToken()==ContantesDaLinguagem.ABREPAR){ abriuPar++; aux.push(exp.get(i)); } else if(exp.get(i).getToken()==ContantesDaLinguagem.FECHAPAR){ if(abriuPar==0) throw new FalhaErroDeSintaxe("Parenteses nao foi aberto "); while((aux.peek().getToken()!=ContantesDaLinguagem.ABREPAR)){ pos.add(aux.pop()); } abriuPar--; aux.pop(); } else if(exp.get(i).getToken()==ContantesDaLinguagem.T_IDENTIFIER || exp.get(i).getToken()==ContantesDaLinguagem.T_CONSTANT) pos.add(exp.get(i)); else if(aux.isEmpty() || !precedenciaMenor(exp.get(i).getToken(),aux.peek().getToken())){ aux.push(exp.get(i)); } else if(precedenciaMenor(exp.get(i).getToken(),aux.peek().getToken())){ while(!aux.isEmpty() && precedenciaMenor(exp.get(i).getToken(),aux.peek().getToken()) ){ pos.add(aux.pop()); } aux.push(exp.get(i)); } } while(!aux.isEmpty()) pos.add(aux.pop()); return pos; } private static boolean precedenciaMenor(int op1,int op2){ if(op2 == ContantesDaLinguagem.ABREPAR) return false; else if(op2 == ContantesDaLinguagem.UNOP) return true; else if(op1 == ContantesDaLinguagem.UNOP) return false; else return op1<=op2; } }
package com.drzewo97.ballotbox.core.service.pollservice; import com.drzewo97.ballotbox.core.dto.polldto.PollDto; import com.drzewo97.ballotbox.core.model.poll.Poll; import com.drzewo97.ballotbox.core.model.poll.PollRepository; import com.drzewo97.ballotbox.core.model.poll.VotingMode; import com.drzewo97.ballotbox.core.model.user.User; import com.drzewo97.ballotbox.core.model.vote.VoteRepository; import com.drzewo97.ballotbox.core.service.userservice.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Optional; @Service public class PollServiceImpl implements PollService { @Autowired private UserService userService; @Autowired private PollRepository pollRepository; @Autowired private VoteRepository voteRepository; @Override public Boolean hasVoted(String username, Integer pollId) { // find user Optional<User> user = userService.findByUsername(username); if(user.isPresent()){ for(Poll poll : user.get().getPollsVoted()){ // Check if there is a poll of this id in user's pollsVoted if(poll.getId().equals(pollId)) return true; } } return false; } @Override public void save(PollDto pollDto, String creatorUsername) { // get user based on name of creatorUsername Optional<User> user = userService.findByUsername(creatorUsername); // Set all fields Poll poll = new Poll(); poll.setName(pollDto.getName()); poll.setDescription(pollDto.getDescription()); poll.setOpenFrom(pollDto.getOpenFrom()); poll.setOpenUntil(pollDto.getOpenUntil()); poll.setCandidatesCount(pollDto.getCandidatesCount()); poll.setWinningCandidatesCount(pollDto.getWinningCandidatesCount()); // Just to simplify, and not deal with enum in template form if(pollDto.getExactly()){ poll.setVotingMode(VotingMode.EXACTLY); } else{ poll.setVotingMode(VotingMode.AT_MOST); } poll.setPollType(pollDto.getPollType()); poll.setPollScope(pollDto.getPollScope()); switch (poll.getPollScope()){ case COUNTRY: poll.setCountry(pollDto.getCountry()); break; case DISTRICT: poll.setDistrict(pollDto.getDistrict()); break; case WARD: poll.setWard(pollDto.getWard()); break; } // username from security context - caller (PollCreateController) requires USER role, so it has to be authenticated previously // unless something happens between caller receiving request and program reaches this point poll.setCreator(user.get()); user.get().appendPollsCreated(poll); pollRepository.save(poll); } @Override public Boolean existsByName(String name) { return pollRepository.existsByName(name); } }
package org.corbin.common.repository; import org.corbin.common.base.dao.BaseRepository; import org.corbin.common.entity.UserActiveInfo; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; @Repository public interface UserActiveInfoRepository extends BaseRepository<UserActiveInfo, Long> { UserActiveInfo findByUserId(Long userId); @Transactional void deleteByUserId(Long userId); }
/* * 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 raytracing3; import java.awt.Color; /** * * @author ianmahoney */ public class Cube { public double height, width, depth; public Point3D point; public Color color; public Point3D[] vertex = new Point3D[8]; public Plane[] planes = new Plane[6]; public Cube(Point3D point, int height, int width, int depth, Color color) { this.point = point; this.height = height; this.width = width; this.depth = depth; this.color = color; //front bottom left vertex[0] = new Point3D(point.x, point.y, point.z); //front bottom right vertex[1] = new Point3D(point.x + width, point.y, point.z); //front top left vertex[2] = new Point3D(point.x, point.y + height, point.z); //front top right vertex[3] = new Point3D(point.x + width, point.y + height, point.z); //back bottom left vertex[4] = new Point3D(point.x, point.y, point.z + depth); //back bottom right vertex[5] = new Point3D(point.x + width, point.y, point.z + depth); //back top left vertex[6] = new Point3D(point.x, point.y + height, point.z + depth); //back top right vertex[7] = new Point3D(point.x + width, point.y + height, point.z + depth); //front planes[0] = new Plane(vertex[0], new Normal(0, 0, 1).Normalize(), new Color(15, 27, 64)); //right planes[1] = new Plane(vertex[1], new Normal(1, 0, 0).Normalize(), new Color(15, 27, 64)); //back planes[2] = new Plane(vertex[5], new Normal(0, 0, 1).Normalize(), new Color(15, 27, 64)); //top planes[3] = new Plane(vertex[2], new Normal(0, 1, 0).Normalize(), new Color(15, 27, 64)); //left planes[4] = new Plane(vertex[4], new Normal(1, 0, 0).Normalize(), new Color(15, 27, 64)); //bottom planes[5] = new Plane(vertex[0], new Normal(0, 1, 0).Normalize(), new Color(15, 27, 64)); } public double intersection(Ray ray) { //System.out.println("intersection test"); double min = (int) 1e10; Color minCol = new Color(0, 0, 0); for (int i = 0; i < planes.length; i++) { double t = planes[i].intersection(ray); // if (t != -1){ // System.out.println("miss : " +t); // return - 1; // // } // System.out.println("************ hit : " +t + "****************"); //double x = (t - 1) * ray.origin.x + t * ray.direction.x;//ray.origin.x + ray.direction.x * t;//(t - 1) * ray.origin.x + t * ray.direction.x; //double y = (t - 1) * ray.origin.y + t * ray.direction.y;//ray.origin.y + ray.direction.y * t;//(t - 1) * ray.origin.y + t * ray.direction.y; //double z = (t - 1) * ray.origin.z + t * ray.direction.z;//ray.origin.z + ray.direction.z * t;//(t - 1) * ray.origin.z + t * ray.direction.z; double x = ray.origin.x + ray.direction.x * t;//(t - 1) * ray.origin.x + t * ray.direction.x; double y = ray.origin.y + ray.direction.y * t;//(t - 1) * ray.origin.y + t * ray.direction.y; double z = ray.origin.z + ray.direction.z * t;//(t - 1) * ray.origin.z + t * ray.direction.z; // if (((i == 0) || (i == 2)) && (x > vertex[0].x) && (x < vertex[1].x) && (y > vertex[0].y) && (y < vertex[2].y) && (t < min)){ // min = t; // System.out.println("hit"); // } else if (((i == 1) || (i == 4)) && (z > vertex[1].z) && (z < vertex[5].z) && (y > vertex[1].y) && (y < vertex[3].y) && (t < min)){ // min = t; // System.out.println("hit"); // } else if (((i == 3) || (i == 5)) && (z > vertex[1].z) && (z < vertex[5].z) && (x > vertex[0].x) && (x < vertex[1].x) && (t < min)){ // min = t; // System.out.println("hit"); // } // if (min != (int) 1e10){ // return min; // } if ((i == 0) || (i == 2)) { //System.out.println("0 or 2: " + i + " @ " + t); if (((x > vertex[0].x) && (x < vertex[1].x)) && ((y > vertex[0].y) && (y < vertex[2].y))) { //System.out.println("inside box: " + x + ", " + y ); if (t < min) { min = t; minCol = getColor((int) t); } continue; } } else if ((i == 1) || (i == 4)) { //System.out.println("1 or 4: " + i + " @ " + t); if (((z > vertex[1].z) && (z < vertex[5].z)) && ((y > vertex[0].y) && (y < vertex[2].y))) { //System.out.println("inside box: " + x + ", " + y ); if (t < min) { min = t; minCol = getColor((int) t); } continue; } else { //System.out.println("outside box: " + x + ", " + y + " @ " + t ); //System.out.println("vertex [0].x = " + vertex[0].x+ ", " + "vertex [1].x = " + vertex[1].x+ ", " + "vertex [0].y = " + vertex[0].y+ ", " + "vertex [2].y = " + vertex[2].y); } } else if ((i == 3) || (i == 5)) { //System.out.println("3 or 5: " + i + " @ " + t); if (((x > vertex[0].x) && (x < vertex[1].x)) && ((z > vertex[1].z) && (z < vertex[5].z))) { //System.out.println("inside box: " + x + ", " + y ); if (t < min) { min = t; minCol = getColor((int) t); } continue; } else { //System.out.println("outside box: " + x + ", " + y + " @ " + t ); //System.out.println("vertex [0].x = " + vertex[0].x+ ", " + "vertex [1].x = " + vertex[1].x+ ", " + "vertex [0].y = " + vertex[0].y+ ", " + "vertex [2].y = " + vertex[2].y); } } } //System.out.println("miss"); return min; } public Color getColor(double t) { Color tempColor; int red, green, blue; final int DIST = 50; if (t > 0) { if (true) { return color; } if (color.getRed() - t * DIST >= 0) { red = (color.getRed() - (int) (t * DIST)); } else { red = 0; } if (color.getBlue() - t * DIST > 0) { blue = color.getBlue() - (int) (t * DIST); } else { blue = 0; } if (color.getGreen() - t * DIST > 0) { green = color.getGreen() - (int) (t * DIST); } else { green = 0; } //System.out.println(red + ", " + green + ", " + blue); tempColor = new Color(red, green, blue); } else { tempColor = new Color(0, 0, 0); } return tempColor; } }
package com.appfest.funkyfotos.config; /** * Created by kaushald on 22/01/17. */ public interface Constants { String FILE_PROVIDER_AUTHORITY = "com.appfest.funkyfotos.provider"; // google constants String GOOGLE_CLIENT_ID = "206905092794-p0pkgtdhsbvpu7jrlee5oe3np1qh4dkr.apps.googleusercontent.com"; //"560496245142-j6rabe001bm25r159m1ifft22iuc34lo.apps.googleusercontent.com"; int MIN_USERNAME_LENGTH = 6; int MIN_NAME_LENGTH = 5; int MIN_PASSWORD_LENGTH = 6; String LOGIN_IMAGE_URL = "https://firebasestorage.googleapis.com/v0/b/holycrab-528ac.appspot" + ".com/o/note_images%2FIMG_20161229_075229" + ".jpg?alt=media&token=0f798462-742f-492c-9f8e-69ff1101a6a6"; String USER_BASE = "users"; String REQUESTED_USER_BASE = "requested_users"; String UB_USERNAME = "username"; String UB_FCM_TOKEN = "fcmToken"; String UB_FIREBASE_UID = "firebaseUID"; String UB_FIREBASE_PIC = "firebasePicUrl"; String UB_USER_EMAIL = "userEmail"; String IMAGE_BUCKET = "funky-fotos.appspot.com"; String USER_IMAGE_FOLDER = "user_images"; // Image processing related int THUMB_SIZE = 144; String PICS_DB = "photos"; String PICS_DATE_TAKEN = "dateTaken"; String COMMENTS_DB = "comments"; String COMMENTS_TIMESTAMP = "timestamp"; String COMMENTS_ARTIFACT_ID = "artifactId"; String KEY_COMMENTS_COUNT = "commentsCount"; String LIKES_DB = "likes"; String LIKES_ARTIFACT_ID = "artifactId"; String LIKES_LIKEDBY_ID = "likedById"; String LIKES_LIKEDBY_NAME = "likedByName"; String LIKES_LIKEDBY_PIC = "likerPic"; String LIKES_LIKEDBY_DATE = "likedOn"; String LIKES_ARTIFACT_UNIQUEID = "likesUniqueIdentifier"; String POEMS_DB = "poems"; String POEMS_PUBLISH_DATE = "publishDate"; String[] funkySmileComments = {"Try again... still waiting for charming face", "Smile…It confuses people..!!", "Is that a smile ?? I don't think so", "My dog smiles better than that", "Don't ever do that again. I am begging you"}; String[] funkySadComments = {"Why so serious?", "What's with the face ?", "No poop today. Huh !!!", "Who died ?", "Told you NOT to watch twilight."}; }
package com.gtfs.dao.interfaces; import java.util.List; import com.gtfs.bean.RoleMst; public interface RoleMstDao { List<RoleMst> findAllActiveRole(); List<RoleMst> findRoleByRoleName(String roleName); RoleMst findRoleById(Long roleId); Boolean deleteRoleMst(Long roleId, Long userId); Boolean saveRoleMst(List<RoleMst> roleMstList); }
package com.java.smart_garage.models.dto; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; public class ManufacturerDto { @NotNull @Size(min = 2 , max = 20, message = "Manufacturer name must be between 2 and 20 characters.") private String manufacturerName; public ManufacturerDto() { } public void setManufacturerName(String manufacturerName) { this.manufacturerName = manufacturerName; } public String getManufacturerName() { return manufacturerName; } }
package org.newdawn.slick.font.effects; import java.awt.Color; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.newdawn.slick.UnicodeFont; import org.newdawn.slick.font.Glyph; public class ColorEffect implements ConfigurableEffect { private Color color = Color.white; public ColorEffect() {} public ColorEffect(Color color) { this.color = color; } public void draw(BufferedImage image, Graphics2D g, UnicodeFont unicodeFont, Glyph glyph) { g.setColor(this.color); g.fill(glyph.getShape()); } public Color getColor() { return this.color; } public void setColor(Color color) { if (color == null) throw new IllegalArgumentException("color cannot be null."); this.color = color; } public String toString() { return "Color"; } public List getValues() { List<ConfigurableEffect.Value> values = new ArrayList(); values.add(EffectUtil.colorValue("Color", this.color)); return values; } public void setValues(List values) { for (Iterator<ConfigurableEffect.Value> iter = values.iterator(); iter.hasNext(); ) { ConfigurableEffect.Value value = iter.next(); if (value.getName().equals("Color")) setColor((Color)value.getObject()); } } } /* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\org\newdawn\slick\font\effects\ColorEffect.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
package cn.chinaunicom.monitor.beans; import java.util.List; /** * Created by yfyang on 2017/8/11. */ public class DeployCategoryEntity { public String itemId; public String title; public List<AppbelongEntity> belongs; public DeployCategoryEntity(String itemId, String title) { this.itemId = itemId; this.title = title; } }
package com.tencent.mm.plugin.sns.ui; import com.tencent.mm.g.a.qe; import com.tencent.mm.sdk.b.b; import com.tencent.mm.sdk.b.c; class SnsTimeLineUI$2 extends c<qe> { final /* synthetic */ SnsTimeLineUI odw; SnsTimeLineUI$2(SnsTimeLineUI snsTimeLineUI) { this.odw = snsTimeLineUI; this.sFo = qe.class.getName().hashCode(); } public final /* synthetic */ boolean a(b bVar) { SnsTimeLineUI.a(this.odw).oeg.notifyVendingDataChange(); return false; } }
package steps; import cucumber.api.java.en.And; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; import org.junit.Assert; import pages.CadastroPage; import pages.PesquisaPage; import support.BaseSteps; public class PesquisaPageStepsTest extends BaseSteps { public static PesquisaPage pesquisaPage = new PesquisaPage(driver); @Given("^O usuario acessa o site sexyHOT$") public void o_usuario_acessa_o_site_sexyHOT ( ) throws Throwable { pesquisaPage.openPage(); } @Then("^e insere alguma palavra na barra de busca$") public void e_insere_alguma_palavra_na_barra_de_busca ( ) throws Throwable { pesquisaPage.clickSim(); pesquisaPage.inputPesquisa(); } @And("^Clico no botao buscar$") public void clico_no_botao_buscar ( ) throws Throwable { pesquisaPage.clickPesquisa(); } // @When("^a busca é realizada com sucesso$") // public void a_busca_é_realizada_com_sucesso (String value ) throws Throwable { // Assert.assertEquals(value, pesquisaPage.assertPesquisa()); // // } }
package com.tumit.util; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.sikuli.api.ScreenRegion; public class RobotLoggerImpl implements RobotLogger { private String outputDir; private StringBuilder logMessage; public RobotLoggerImpl(String outputDir) { this.outputDir = outputDir; } public void info(String message) { logMessage = new StringBuilder("*INFO* "); logMessage.append(message); System.out.println(logMessage.toString()); } @Override public void capture(ScreenRegion screenshort, File imageFile) throws IOException, InterruptedException { this.capture(screenshort, imageFile, null); } @Override public void capture(ScreenRegion screenshort, File imageFile, ScreenRegion matchScreen) throws IOException, InterruptedException { // copy expected image to output dir // write screenshort image to output dir File screenFile = new File(this.outputDir, "screenshort_" + +System.currentTimeMillis() + ".png"); ImageIO.write(screenshort.capture(), "png", screenFile); // copy image to output directory FileUtils.copyFileToDirectory(imageFile, new File(this.outputDir)); if (matchScreen != null) { // write actual image to output dir File actualFile = new File(this.outputDir, FilenameUtils.removeExtension(imageFile.getName()) + "_" + System.currentTimeMillis() + ".png"); ImageIO.write(matchScreen.capture(), "png", actualFile); // diff expected image and actual image to output dir this.info(ImageMagickUtil.compare(new File(this.outputDir), imageFile, actualFile)); } } }
/* * Copyright 2019 GcsSloop * * 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. * * Last modified 2019-05-09 02:18:47 * * GitHub: https://github.com/GcsSloop * WeiBo: http://weibo.com/GcsSloop * WebSite: http://www.gcssloop.com */ package com.gcssloop.pagelayoutmanager; import android.view.View; /** * Created by classichu on 2016/3/19. */ public abstract class OnItemClickListener { public boolean onItemLongClick(View view, int position) { return false; } public abstract void onItemClick(View view, int position); }
package org.newdawn.slick; import java.io.Serializable; import java.nio.FloatBuffer; import org.newdawn.slick.opengl.renderer.Renderer; import org.newdawn.slick.opengl.renderer.SGL; public class Color implements Serializable { private static final long serialVersionUID = 1393939L; protected transient SGL GL = Renderer.get(); public static final Color transparent = new Color(0.0F, 0.0F, 0.0F, 0.0F); public static final Color white = new Color(1.0F, 1.0F, 1.0F, 1.0F); public static final Color yellow = new Color(1.0F, 1.0F, 0.0F, 1.0F); public static final Color red = new Color(1.0F, 0.0F, 0.0F, 1.0F); public static final Color blue = new Color(0.0F, 0.0F, 1.0F, 1.0F); public static final Color green = new Color(0.0F, 1.0F, 0.0F, 1.0F); public static final Color black = new Color(0.0F, 0.0F, 0.0F, 1.0F); public static final Color gray = new Color(0.5F, 0.5F, 0.5F, 1.0F); public static final Color cyan = new Color(0.0F, 1.0F, 1.0F, 1.0F); public static final Color darkGray = new Color(0.3F, 0.3F, 0.3F, 1.0F); public static final Color lightGray = new Color(0.7F, 0.7F, 0.7F, 1.0F); public static final Color pink = new Color(255, 175, 175, 255); public static final Color orange = new Color(255, 200, 0, 255); public static final Color magenta = new Color(255, 0, 255, 255); public float r; public float g; public float b; public float a = 1.0F; public Color(Color color) { this.r = color.r; this.g = color.g; this.b = color.b; this.a = color.a; } public Color(FloatBuffer buffer) { this.r = buffer.get(); this.g = buffer.get(); this.b = buffer.get(); this.a = buffer.get(); } public Color(float r, float g, float b) { this.r = r; this.g = g; this.b = b; this.a = 1.0F; } public Color(float r, float g, float b, float a) { this.r = Math.min(r, 1.0F); this.g = Math.min(g, 1.0F); this.b = Math.min(b, 1.0F); this.a = Math.min(a, 1.0F); } public Color(int r, int g, int b) { this.r = r / 255.0F; this.g = g / 255.0F; this.b = b / 255.0F; this.a = 1.0F; } public Color(int r, int g, int b, int a) { this.r = r / 255.0F; this.g = g / 255.0F; this.b = b / 255.0F; this.a = a / 255.0F; } public Color(int value) { int r = (value & 0xFF0000) >> 16; int g = (value & 0xFF00) >> 8; int b = value & 0xFF; int a = (value & 0xFF000000) >> 24; if (a < 0) a += 256; if (a == 0) a = 255; this.r = r / 255.0F; this.g = g / 255.0F; this.b = b / 255.0F; this.a = a / 255.0F; } public static Color decode(String nm) { return new Color(Integer.decode(nm).intValue()); } public void bind() { this.GL.glColor4f(this.r, this.g, this.b, this.a); } public int hashCode() { return (int)(this.r + this.g + this.b + this.a) * 255; } public boolean equals(Object other) { if (other instanceof Color) { Color o = (Color)other; return (o.r == this.r && o.g == this.g && o.b == this.b && o.a == this.a); } return false; } public String toString() { return "Color (" + this.r + "," + this.g + "," + this.b + "," + this.a + ")"; } public Color darker() { return darker(0.5F); } public Color darker(float scale) { scale = 1.0F - scale; Color temp = new Color(this.r * scale, this.g * scale, this.b * scale, this.a); return temp; } public Color brighter() { return brighter(0.2F); } public int getRed() { return (int)(this.r * 255.0F); } public int getGreen() { return (int)(this.g * 255.0F); } public int getBlue() { return (int)(this.b * 255.0F); } public int getAlpha() { return (int)(this.a * 255.0F); } public int getRedByte() { return (int)(this.r * 255.0F); } public int getGreenByte() { return (int)(this.g * 255.0F); } public int getBlueByte() { return (int)(this.b * 255.0F); } public int getAlphaByte() { return (int)(this.a * 255.0F); } public Color brighter(float scale) { scale++; Color temp = new Color(this.r * scale, this.g * scale, this.b * scale, this.a); return temp; } public Color multiply(Color c) { return new Color(this.r * c.r, this.g * c.g, this.b * c.b, this.a * c.a); } public void add(Color c) { this.r += c.r; this.g += c.g; this.b += c.b; this.a += c.a; } public void scale(float value) { this.r *= value; this.g *= value; this.b *= value; this.a *= value; } public Color addToCopy(Color c) { Color copy = new Color(this.r, this.g, this.b, this.a); copy.r += c.r; copy.g += c.g; copy.b += c.b; copy.a += c.a; return copy; } public Color scaleCopy(float value) { Color copy = new Color(this.r, this.g, this.b, this.a); copy.r *= value; copy.g *= value; copy.b *= value; copy.a *= value; return copy; } } /* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\org\newdawn\slick\Color.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
package mensaje; public class MsjAvisarClienteAbandonoSala extends Mensaje { private static final long serialVersionUID = -8556787900292735591L; private String clienteNombre; public MsjAvisarClienteAbandonoSala(String user) { this.clienteNombre = user; this.clase = this.getClass().getSimpleName(); } @Override public void ejecutar() { } public String getClienteNombre() { return clienteNombre; } public void setClienteNombre(String clienteNombre) { this.clienteNombre = clienteNombre; } }
package vn.geekup.utils; import android.support.annotation.StringDef; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; public class Constants { public static final String ISO_8859_1 = "ISO_8859_1"; public static final String US_ASCII = "US_ASCII"; public static final String UTF_16 = "UTF_16"; public static final String UTF_16BE = "UTF_16BE"; public static final String UTF_16LE = "UTF_16LE"; public static final String UTF_8 = "UTF_8"; @Retention(RetentionPolicy.SOURCE) @StringDef({ISO_8859_1, US_ASCII, UTF_16, UTF_16BE, UTF_16LE, UTF_8}) public @interface Endcoding {} public static final String PERCENT_TAG = "%"; public static final String DASH_STRING = "--"; }
package com.vilio.plms.service.base; import com.vilio.plms.exception.ErrorException; import com.vilio.plms.glob.GlobDict; import com.vilio.plms.glob.ReturnCode; import com.vilio.plms.util.DateUtil; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; /** * 类名: RollbackAndRecomputationProxy<br> * 功能:回滚和重新计算切面类<br> * 版本: 1.0<br> * 日期: 2017年8月28日<br> * 作者: wangxf<br> * 版权:vilio<br> * 说明:<br> */ @Component public class RollbackAndRecomputationProxy { private static Logger logger = Logger.getLogger(RollbackAndRecomputationProxy.class); @Resource private CommonService commonService; @Resource private RollBackPaymentAndOverdueService rollBackPaymentAndOverdueService; @Resource private RecomputationPaymentAndOverdueService recomputationPaymentAndOverdueService; /** * 修改账务类标识(加锁) * * @throws Throwable */ public void updateAccountLockNoCheck() throws Throwable { //先进行账务类操作锁定操作 //更改系统表账户类操作锁定 int ret = commonService.setItemVal("ACCOUNT_LOCK", GlobDict.account_lock.getKey(), ""); if (ret == 0) { //其他进程在做账务类操作 throw new ErrorException(ReturnCode.ACCOUNT_LOCK, ""); } if (ret < 0) { throw new ErrorException(ReturnCode.SYSTEM_EXCEPTION, "系统异常"); } logger.info("执行修改账务类标识完成"); } /** * 修改账务类标识(加锁) * * @throws Throwable */ public void updateAccountLock() throws Throwable { //获取当前扣款和逾期系统参数,判断执行的日期是否等于当前日期,不等于,不能进行回滚重新计算操作 String payScheduleJob = commonService.getItemTime("PAY_SCHEDULE_JOB"); String calculateOverdueInterestJob = commonService.getItemTime("CALCULATE_OVERDUE_INTEREST_JOB"); //判断是否和当前日期相等 if (DateUtil.dateCompareNow(payScheduleJob) != 0) { //扣款日期不等于当前日期 throw new ErrorException(ReturnCode.SYSTEM_EXCEPTION, "扣款执行到的日期不等于当前日期,不能进行账务类操作"); } if (DateUtil.dateCompareNow(calculateOverdueInterestJob) != 0) { //扣款日期不等于当前日期 throw new ErrorException(ReturnCode.SYSTEM_EXCEPTION, "逾期执行到的日期不等于当前日期,不能进行账务类操作"); } //先进行账务类操作锁定操作 //更改系统表账户类操作锁定 int ret = commonService.setItemVal("ACCOUNT_LOCK", GlobDict.account_lock.getKey(), ""); if (ret == 0) { //其他进程在做账务类操作 throw new ErrorException(ReturnCode.ACCOUNT_LOCK, ""); } if (ret < 0) { throw new ErrorException(ReturnCode.SYSTEM_EXCEPTION, "系统异常"); } logger.info("执行修改账务类标识完成"); } /** * 修改账务类标识(解锁) * * @throws Throwable */ public void updateAccountUnLock() throws Throwable { //更改系统表账户类操作锁定 int ret = commonService.setItemVal("ACCOUNT_LOCK", GlobDict.account_unlock.getKey(), ""); if (ret == 0) { //其他进程在做账务类操作 throw new ErrorException(ReturnCode.SYSTEM_EXCEPTION, "不能重复解锁"); } if (ret < 0) { throw new ErrorException(ReturnCode.SYSTEM_EXCEPTION, "系统异常"); } logger.info("执行修改账务类标识完成"); } /** * 修改账务类标识(解锁) * * @throws Throwable */ public void updateAccountUnLockForParam(String rollBachDate, String contractCode, String batchCode) throws Throwable { updateAccountUnLock(); } /** * 回滚扣款和逾期(需要传两个参数,yyyy-MM-DD 回滚到哪一天,合同编码) * * @throws Throwable */ @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class) public void rollBackPaymentAndOverdue(String rollBachDate, String contractCode, String batchCode) throws Throwable { if (rollBachDate.length() != 10) { throw new ErrorException(ReturnCode.REQUIRED_FIELD_MISSING, "日期格式不正确"); } rollBackPaymentAndOverdueService.mainJob(rollBachDate, contractCode, batchCode); logger.info("回滚扣款和逾期完成"); } /** * 锁定标识、回滚扣款和逾期(需要传两个参数,yyyy-MM-DD 回滚到哪一天,合同编码) * * @throws Throwable */ @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class) public void accountLockRollBackPaymentAndOverdue(String rollBachDate, String contractCode, String batchCode) throws Throwable { updateAccountLock(); rollBackPaymentAndOverdue(rollBachDate, contractCode, batchCode); } /** * 解锁、重新计算扣款和逾期(需要传两个参数,yyyy-MM-DD 回滚到哪一天就传哪一天,方法里面自动加一天,合同编码) * * @throws Throwable */ @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class) public void accountUnLockRecomputationPaymentAndOverdue(String rollBachDate, String contractCode, String batchCode) throws Throwable { recomputationPaymentAndOverdue(rollBachDate, contractCode, batchCode); updateAccountUnLock(); } /** * 重新计算扣款和逾期(需要传两个参数,yyyy-MM-DD 回滚到哪一天就传哪一天,方法里面自动加一天,合同编码) * * @throws Throwable */ @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class) public void recomputationPaymentAndOverdue(String rollBachDate, String contractCode, String batchCode) throws Throwable { if (rollBachDate.length() != 10) { throw new ErrorException(ReturnCode.REQUIRED_FIELD_MISSING, "日期格式不正确"); } String paymentDate = DateUtil.getDaysDate2(rollBachDate, 1); recomputationPaymentAndOverdueService.mainJob(paymentDate, contractCode, batchCode); logger.info("重新计算扣款和逾期完成"); } }
package at.porscheinformatik.sonarqube.licensecheck.widget; import org.sonar.api.web.AbstractRubyTemplate; import org.sonar.api.web.Description; import org.sonar.api.web.RubyRailsWidget; import org.sonar.api.web.UserRole; @UserRole(UserRole.USER) @Description("Shows all licenses, which are used by the dependencies") public class UsedLicensesWidget extends AbstractRubyTemplate implements RubyRailsWidget { @Override public String getId() { return "usedLicenses"; } @Override public String getTitle() { return "Used Licenses"; } @Override protected String getTemplatePath() { return "/at/porscheinformatik/sonarqube/licensecheck/widget/usedlicenses_widget.html.erb"; } }
package com.pixietools; import java.io.*; //import java.util.*; //import pixietools.*; import java.nio.ByteBuffer; import java.nio.ByteOrder; /* This program reads the information about each buffer, event and channel hit * and stores them all in variables. These variables are used later in functions * to determine the energy and time of a channel hit; also other information such * as module number, channel number, etc. * Each function has a short descriptor of its purpose */ public class PixieBinFile { // set up to get file path, and use random access // so we can move around within the file private String _pixieFilePath = ""; private RandomAccessFile _pixieFile = null; private boolean _fileLoaded = false; // initialize all headers private BufferHeader _currBufferHeader = null; private EventHeader _currEventHeader = null; private ChannelHeader _currChannelHeader = null; // Mark / Roll back headers //private BufferHeader _markBufferHeader = null; private BufferHeader _markBufferHeader = new BufferHeader(); //private EventHeader _markEventHeader = null; private EventHeader _markEventHeader = new EventHeader(); //private ChannelHeader _markChannelHeader = null; private ChannelHeader _markChannelHeader = new ChannelHeader(); private long _markFilePosition = 0; PixieBinFile() { // Do nothing } PixieBinFile(String filePath) { // Overload constructor just in-case want to load this way _pixieFilePath = filePath; } private boolean loadFile() { // Check to see if file path has "something" if (_pixieFilePath == "") return false; // Create file object File f = new File(_pixieFilePath); // Check to see if file exists, if not return false if (!f.exists()) return false; // Create a random access file object, allows us to start at any point in file try { _pixieFile = new RandomAccessFile(f, "r"); } catch (FileNotFoundException e) { System.out.println("Error: FileNotFoundException in loadFile: " + e.getMessage()); return false; } return true; } public boolean open() { // First check to see if the file is already open if (_fileLoaded) return true; // If not, load file and return true if succeeds if (loadFile()) { _fileLoaded = true; return true; } else { _fileLoaded = false; return false; } } public boolean close() { // Check to see if file is open. // If so, close it gracefully and destroy the object if (_fileLoaded) { try { // initialize variables on current readings of headers _pixieFile.close(); _pixieFile = null; _fileLoaded = false; // set all headers to 0 _currBufferHeader = null; _currEventHeader = null; _currChannelHeader = null; } catch (IOException e) { System.out.println("Error: IOException in close: " + e.getMessage()); return false; } } return true; } public boolean isOpen() { // check if file is open and loaded return _fileLoaded; } public String getFilePath() { // gets file path from BinToAscii return _pixieFilePath; } // sets file path public void setFilePath(String filePath) { _pixieFilePath = filePath; } private boolean readBufferHeader(BufferHeader buffHead) { try { // read in all info in buffer header from start of binary position buffHead.binaryStartPosition = _pixieFile.getFilePointer(); // since in binary, reading in unsigned shorts in little endian buffHead.wordsInBuffer = readUShortLE(_pixieFile); buffHead.moduleNumber = readUShortLE(_pixieFile); buffHead.bufferFormat = readUShortLE(_pixieFile); buffHead.bufferTimeHi = readUShortLE(_pixieFile); buffHead.bufferTimeMid = readUShortLE(_pixieFile); buffHead.bufferTimeLo = readUShortLE(_pixieFile); } catch (IOException e) { System.out.println("Error: IOException in readBufferHeader: " + e.getMessage()); return false; } return true; } private boolean readEventHeader(EventHeader eventHead) { try { // find where file pointer is at current event eventHead.binaryStartPosition = _pixieFile.getFilePointer(); // read in three words in little endian (time, and hit pattern) // hit pattern gives what channel was hit, and possible coincidence // data if that is requested in Pixie eventHead.eventPattern = readUShortLE(_pixieFile); eventHead.eventTimeHi = readUShortLE(_pixieFile); eventHead.eventTimeLo = readUShortLE(_pixieFile); // Determine which channels were hit from event pattern if ((eventHead.eventPattern & 1) > 0) eventHead.channel0Hit = true; if ((eventHead.eventPattern & 2) > 0) eventHead.channel1Hit = true; if ((eventHead.eventPattern & 4) > 0) eventHead.channel2Hit = true; if ((eventHead.eventPattern & 8) > 0) eventHead.channel3Hit = true; } catch (IOException e) { System.out.println("Error: IOException in readEventHeader: " + e.getMessage()); return false; } return true; } private boolean readChannelHeader(ChannelHeader chanHead, int chanNumber) { // This function assumes we are reading a channel header for // compression mode 3. This will have to be modified if // a different mode is used. try { // read in all info in channel header chanHead.binaryStartPosition = _pixieFile.getFilePointer(); // read in channel number, fast trigger time and pulse height in little endian chanHead.channelNumber = chanNumber; chanHead.channelTrigTime = readUShortLE(_pixieFile); chanHead.channelEnergy = readUShortLE(_pixieFile); } catch (IOException e) { System.out.println("Error: IOException in readChannelHeader: " + e.getMessage()); return false; } return true; } public boolean moveFirstBuffer() { if (!_fileLoaded) return false; try { // Reset event and channel headers _currEventHeader = null; _currChannelHeader = null; // Move to beginning of stream _pixieFile.seek(0); // Read first buffer header _currBufferHeader = new BufferHeader(); readBufferHeader(_currBufferHeader); // Check to see if buffer is past end of file if ((_currBufferHeader.wordsInBuffer * 2) > _pixieFile.length()) { System.out.println("Error: words in first buffer exceed end of file!"); return false; } } catch (IOException e) { System.out.println("Error: IOException in moveFirstBuffer: " + e.getMessage()); return false; } return true; } public boolean moveNextBuffer() { if (!_fileLoaded) return false; try { // Reset event and channel headers _currEventHeader = null; _currChannelHeader = null; // calculate position of next buffer based on start position // and how where file started (*2 because each word is 2 bytes) long posNextBuffer = 0; posNextBuffer += _currBufferHeader.binaryStartPosition; posNextBuffer += _currBufferHeader.wordsInBuffer * 2; // Check to see if position is past end of file if ((posNextBuffer + 12) > _pixieFile.length()) { _currBufferHeader = null; return false; } // get to next buffer _pixieFile.seek(posNextBuffer); // Read buffer header _currBufferHeader = new BufferHeader(); readBufferHeader(_currBufferHeader); } catch (IOException e) { System.out.println("Error: IOException in moveNextBuffer: " + e.getMessage()); return false; } return true; } public boolean moveFirstEvent() { if (!_fileLoaded) return false; try { // Reset channel header _currChannelHeader = null; // Get position for first event long posFirstEvent = 0; posFirstEvent += _currBufferHeader.binaryStartPosition; posFirstEvent += 12; // Ignore first 6 words (buffer header) // Move to first event in buffer _pixieFile.seek(posFirstEvent); // Read first event // **add code here to check within buffer limit** _currEventHeader = new EventHeader(); readEventHeader(_currEventHeader); } catch (IOException e) { System.out.println("Error: IOException in moveFirstEvent: " + e.getMessage()); return false; } return true; } public boolean moveNextEvent() { if (!_fileLoaded) return false; try { // Reset channel header _currChannelHeader = null; // Get position for next event long posNextEvent = 0; posNextEvent += _currEventHeader.binaryStartPosition; posNextEvent += 6; // 3 words in event header posNextEvent += _currEventHeader.getChannelHitCount() * 4; // 2 Words per channel (Compression 3 Mode) // Check to see next event is in the buffer long bufferMax = _currBufferHeader.binaryStartPosition + (_currBufferHeader.wordsInBuffer * 2); if ((posNextEvent + 6) > bufferMax) { _currEventHeader = null; return false; } // Move to next event in buffer _pixieFile.seek(posNextEvent); // Read next event _currEventHeader = new EventHeader(); readEventHeader(_currEventHeader); } catch (IOException e) { System.out.println("Error: IOException in moveNextEvent: " + e.getMessage()); return false; } return true; } public boolean moveFirstChannel() { if (!_fileLoaded) return false; try { //System.out.println("got here"); // Get position for first channel in event long posFirstChannel = 0; if (_currEventHeader.channel0Hit) posFirstChannel = _currEventHeader.getChannel0Position(); else if (_currEventHeader.channel1Hit) posFirstChannel = _currEventHeader.getChannel1Position(); else if (_currEventHeader.channel2Hit) posFirstChannel = _currEventHeader.getChannel2Position(); else if (_currEventHeader.channel3Hit) posFirstChannel = _currEventHeader.getChannel3Position(); else return false; // should never get here // Move to first channel in event _pixieFile.seek(posFirstChannel); // Read first channel in event _currChannelHeader = new ChannelHeader(); if (_currEventHeader.channel0Hit) readChannelHeader(_currChannelHeader, 0); else if (_currEventHeader.channel1Hit) readChannelHeader(_currChannelHeader, 1); else if (_currEventHeader.channel2Hit) readChannelHeader(_currChannelHeader, 2); else if (_currEventHeader.channel3Hit) readChannelHeader(_currChannelHeader, 3); else return false; // should never get here } catch (IOException e) { System.out.println("Error: IOException in moveFirstChannel: " + e.getMessage()); return false; } return true; } public boolean moveNextChannel() { // move to next channel in event // checks to ensure file is loaded if (!_fileLoaded) return false; try { // Get position for next channel in event long posNextChannel = 0; int channelNumber = -1; if (_currEventHeader.channel0Hit && (_currEventHeader.getChannel0Position() > _currChannelHeader.binaryStartPosition)) { // should never hit channel 0 for moveNextChannel posNextChannel = _currEventHeader.getChannel0Position(); channelNumber = 0; } else if (_currEventHeader.channel1Hit && (_currEventHeader.getChannel1Position() > _currChannelHeader.binaryStartPosition)) { posNextChannel = _currEventHeader.getChannel1Position(); channelNumber = 1; } else if (_currEventHeader.channel2Hit && (_currEventHeader.getChannel2Position() > _currChannelHeader.binaryStartPosition)) { posNextChannel = _currEventHeader.getChannel2Position(); channelNumber = 2; } else if (_currEventHeader.channel3Hit && (_currEventHeader.getChannel3Position() > _currChannelHeader.binaryStartPosition)) { posNextChannel = _currEventHeader.getChannel3Position(); channelNumber = 3; } else return false; // Move to first channel in event _pixieFile.seek(posNextChannel); // Read next channel in event _currChannelHeader = new ChannelHeader(); readChannelHeader(_currChannelHeader, channelNumber); } catch (IOException e) { System.out.println("Error: IOException in moveNextChannel: " + e.getMessage()); return false; } return true; } public int getBufferModuleNumber() { // get module number (which pixie card being used) if (!_fileLoaded) return -1; // returns module number as integer return (int)_currBufferHeader.moduleNumber; } public double getBufferTime() { // calculating buffer time using words High, Mid, Low if (!_fileLoaded) return -1.0; // returns time at which buffer was created double highTime = _currBufferHeader.bufferTimeHi * (57.2662306133); double midTime = _currBufferHeader.bufferTimeMid * (0.0008738133); double lowTime = _currBufferHeader.bufferTimeLo * (0.0000000133); return highTime + midTime + lowTime; } public double getBufferTimeNs() { // This function converts the Seconds to Nanoseconds double bufferTimeS = getBufferTime(); // will never get a negative buffertime, so this means there's an error if (bufferTimeS == -1.0) return -1.0; return bufferTimeS * (1000000000.0); } public double getEventTime() { // calculating event time using buffer High, event high, event low if (!_fileLoaded) return -1.0; // convert buffer words over to actual time format double highTime = _currBufferHeader.bufferTimeHi * (57.2662306133); double midTime = _currEventHeader.eventTimeHi * (0.0008738133); double lowTime = _currEventHeader.eventTimeLo * (0.0000000133); // adding three words together to get absolute time stamp return highTime + midTime + lowTime; } public double getEventTimeNs() { // This function converts the Seconds to Nanoseconds double eventTimeS = getEventTime(); if (eventTimeS == -1.0) return -1.0; return eventTimeS * (1000000000.0); } public double getChannelFastTriggerTime() { // calculating event time using buffer High, event high, event low if (!_fileLoaded) return -1.0; double highTime = _currBufferHeader.bufferTimeHi * (57.2662306133); double midTime = _currEventHeader.eventTimeHi * (0.0008738133); double lowTime = _currChannelHeader.channelTrigTime * (0.0000000133); // see PixieDataCollection Guide for more info on difference // between FastTriggerTime and EventTime return highTime + midTime + lowTime; } public double getChannelFastTriggerTimeNs() { // This function converts the Seconds to Nanoseconds double channelTimeS = getChannelFastTriggerTime(); if (channelTimeS == -1.0) return -1.0; return channelTimeS * (1000000000.0); } public int getEventChannel() { // this function returns the event channel number if (!_fileLoaded) return -1; return _currChannelHeader.channelNumber; } public int getEventEnergy() { // this function returns the event energy reading if (!_fileLoaded) return -1; return _currChannelHeader.channelEnergy; } private int readUShortLE(RandomAccessFile _ranAccessFile) { // this function allows PixieBinFile to read the data in little endian (normal for Java) int returnValue = -1; try { // Read two bytes into byte array // We do it this way so we don't slam the garbage collector byte[] buffer = new byte[2]; int bytes = _ranAccessFile.read(buffer); // Check to see that it read all 2 bytes if (bytes != 2) throw new IOException("Unexpected End of Stream"); // ANDs every bit giving you the absolute value in bits // turning every negative number into the proper unsigned value returnValue = ByteBuffer.wrap(buffer).order(ByteOrder.LITTLE_ENDIAN).getShort() & 0xFFFF; } catch (IOException e) { System.out.println("Error: IOException in readUShortLittleEndian: " + e.getMessage()); return -1; } return returnValue; } // function to mark position of current event // so it can be returned to later public void markPosition() { try { _markBufferHeader.copy(_currBufferHeader); _markEventHeader.copy(_currEventHeader); _markChannelHeader.copy(_currChannelHeader); _markFilePosition = _pixieFile.getFilePointer(); } catch (IOException e) { System.out.println("Error in markPosition() " + e.getMessage()); } } // function to roll back to whatever position/event // was marked by markPosition function public void rollbackPosition() { try { _currBufferHeader.copy(_markBufferHeader); _currEventHeader.copy(_markEventHeader); _currChannelHeader.copy(_markChannelHeader); _pixieFile.seek(_markFilePosition); } catch (IOException e) { System.out.println("Error in rollbackPosition() " + e.getMessage()); } } }
package com.rc.portal.dao.impl; import java.sql.SQLException; import java.util.List; import com.ibatis.sqlmap.client.SqlMapClient; import com.rc.app.framework.webapp.model.page.PageManager; import com.rc.app.framework.webapp.model.page.PageWraper; import com.rc.portal.dao.TMemberReceiverLatLonDAO; import com.rc.portal.vo.TMemberReceiverLatLon; import com.rc.portal.vo.TMemberReceiverLatLonExample; public class TMemberReceiverLatLonDAOImpl implements TMemberReceiverLatLonDAO { private SqlMapClient sqlMapClient; public void setSqlMapClient(SqlMapClient sqlMapClient) { this.sqlMapClient = sqlMapClient; } public SqlMapClient getSqlMapClient() { return sqlMapClient; } public TMemberReceiverLatLonDAOImpl() { super(); } public TMemberReceiverLatLonDAOImpl(SqlMapClient sqlMapClient) { super(); this.sqlMapClient = sqlMapClient; } public int countByExample(TMemberReceiverLatLonExample example) throws SQLException { Integer count = (Integer) sqlMapClient.queryForObject("t_member_receiver_lat_lon.ibatorgenerated_countByExample", example); return count.intValue(); } public int deleteByExample(TMemberReceiverLatLonExample example) throws SQLException { int rows = sqlMapClient.delete("t_member_receiver_lat_lon.ibatorgenerated_deleteByExample", example); return rows; } public int deleteByPrimaryKey(Long id) throws SQLException { TMemberReceiverLatLon key = new TMemberReceiverLatLon(); key.setId(id); int rows = sqlMapClient.delete("t_member_receiver_lat_lon.ibatorgenerated_deleteByPrimaryKey", key); return rows; } public Long insert(TMemberReceiverLatLon record) throws SQLException { return (Long) sqlMapClient.insert("t_member_receiver_lat_lon.ibatorgenerated_insert", record); } public Long insertSelective(TMemberReceiverLatLon record) throws SQLException { return (Long) sqlMapClient.insert("t_member_receiver_lat_lon.ibatorgenerated_insertSelective", record); } public List selectByExample(TMemberReceiverLatLonExample example) throws SQLException { List list = sqlMapClient.queryForList("t_member_receiver_lat_lon.ibatorgenerated_selectByExample", example); return list; } public TMemberReceiverLatLon selectByPrimaryKey(Long id) throws SQLException { TMemberReceiverLatLon key = new TMemberReceiverLatLon(); key.setId(id); TMemberReceiverLatLon record = (TMemberReceiverLatLon) sqlMapClient.queryForObject("t_member_receiver_lat_lon.ibatorgenerated_selectByPrimaryKey", key); return record; } public int updateByExampleSelective(TMemberReceiverLatLon record, TMemberReceiverLatLonExample example) throws SQLException { UpdateByExampleParms parms = new UpdateByExampleParms(record, example); int rows = sqlMapClient.update("t_member_receiver_lat_lon.ibatorgenerated_updateByExampleSelective", parms); return rows; } public int updateByExample(TMemberReceiverLatLon record, TMemberReceiverLatLonExample example) throws SQLException { UpdateByExampleParms parms = new UpdateByExampleParms(record, example); int rows = sqlMapClient.update("t_member_receiver_lat_lon.ibatorgenerated_updateByExample", parms); return rows; } public int updateByPrimaryKeySelective(TMemberReceiverLatLon record) throws SQLException { int rows = sqlMapClient.update("t_member_receiver_lat_lon.ibatorgenerated_updateByPrimaryKeySelective", record); return rows; } public int updateByPrimaryKey(TMemberReceiverLatLon record) throws SQLException { int rows = sqlMapClient.update("t_member_receiver_lat_lon.ibatorgenerated_updateByPrimaryKey", record); return rows; } private static class UpdateByExampleParms extends TMemberReceiverLatLonExample { private Object record; public UpdateByExampleParms(Object record, TMemberReceiverLatLonExample example) { super(example); this.record = record; } public Object getRecord() { return record; } } public PageWraper selectByRepositoryByPage(TMemberReceiverLatLonExample example) throws SQLException { PageWraper pw=null; int count=this.countByExample(example); List list = sqlMapClient.queryForList("t_member_receiver_lat_lon.selectByExampleByPage", example); System.out.println("��Դ��ҳ��ѯlist.size="+list.size()); pw=PageManager.getPageWraper(example.getPageInfo(), list, count); return pw; } }
package ch.epfl.tchu.game; import ch.epfl.tchu.Preconditions; import ch.epfl.tchu.SortedBag; import java.util.*; /** * GameState class * Methods: playerState, currentPlayerState, topTickets, withoutTopTickets, topCard, * withoutTopCard, withMoreDiscardedCards, withCardsDeckRecreatedIfNeeded, withInitiallyChosenTickets, * withChosenAdditionalTickets, withDrawnFaceUpCard, withBlindlyDrawnCard, withClaimedRoute, lastTurnBegins, * forNextTurn * * @author Eduardo Neville (314667) */ public final class GameState extends PublicGameState { private final Deck<Ticket> tickets; private final Map<PlayerId, PlayerState> playerState; private final CardState privateCardState; private GameState(Map<PlayerId, PlayerState> playerState, PlayerId lastPlayer, Deck<Ticket> ticketsDeck, CardState privateCardState, PlayerId currentPlayerId) { super(ticketsDeck.size(), privateCardState, currentPlayerId, makePublic(playerState), lastPlayer); this.tickets = ticketsDeck; this.playerState = playerState; this.privateCardState = privateCardState; } /** * Initial static constructor that initializes the game * * @param tickets tickets in the deck * @param rng used to shuffle the tickets * @return The initial GameState at the beginning of the match */ public static GameState initial(SortedBag<Ticket> tickets, Random rng) { SortedBag<Card> withoutInitialCards = SortedBag.of(Constants.ALL_CARDS); List<Card> shuffleDeck = withoutInitialCards.toList(); Collections.shuffle(shuffleDeck); Deck<Card> theDeck = Deck.of(withoutInitialCards, rng); Map<PlayerId, PlayerState> initialMap = new HashMap<>(); initialMap.put(PlayerId.PLAYER_1, PlayerState.initial(theDeck.topCards(4))); theDeck = theDeck.withoutTopCards(4); initialMap.put(PlayerId.PLAYER_2, PlayerState.initial(theDeck.topCards(4))); theDeck = theDeck.withoutTopCards(4); List<PlayerId> listOfPlayers = new ArrayList<>(); listOfPlayers.add(PlayerId.PLAYER_1); listOfPlayers.add(PlayerId.PLAYER_2); Random random = new Random(); PlayerId randStartingPlayer = listOfPlayers.get(random.nextInt(listOfPlayers.size())); CardState privateCardState = CardState.of(theDeck); return new GameState(initialMap, null, Deck.of(tickets, rng), privateCardState, randStartingPlayer); } private static Map<PlayerId, PublicPlayerState> makePublic(Map<PlayerId, PlayerState> playerStateMap) { Map<PlayerId, PlayerState> playerStateTreeMap = new TreeMap<>(playerStateMap); PlayerState playerState1 = playerStateTreeMap.get(PlayerId.PLAYER_1); PlayerState playerState2 = playerStateTreeMap.get(PlayerId.PLAYER_2); PublicPlayerState publicPlayerState1 = new PublicPlayerState(playerState1.tickets().size(), playerState1.cards().size(), playerState1.routes()); PublicPlayerState publicPlayerState2 = new PublicPlayerState(playerState2.tickets().size(), playerState2.cards().size(), playerState2.routes()); Map<PlayerId, PublicPlayerState> publicPlayerStateMap = new TreeMap<>(); publicPlayerStateMap.put(PlayerId.PLAYER_1, publicPlayerState1); publicPlayerStateMap.put(PlayerId.PLAYER_2, publicPlayerState2); return publicPlayerStateMap; } /** * Returns the full playerState * * @param playerId Player in question * @return full playerState of playerId */ public PlayerState playerState(PlayerId playerId) { return playerState.get(playerId); } /** * Returns the full playerState of the currentPlayerId * * @return full playerState of currentplayerId */ public PlayerState currentPlayerState() { return playerState(currentPlayerId()); } /** * Returns the toptickets of the deck * * @param count # of tickets returned * @return # of tickets at the top that are being returned * @throws IllegalArgumentException thrown if count is smaller than 0 or tickets is smaller than count */ public SortedBag<Ticket> topTickets(int count) { Preconditions.checkArgument(count > 0 || tickets.size() > count); return tickets.topCards(count); } /** * Returns the deck without the toptickets of the deck * * @param count # of tickets that we remove * @return deck without the toptickets * @throws IllegalArgumentException thrown if count is smaller than 0 or tickets is smaller than count */ public GameState withoutTopTickets(int count) { Preconditions.checkArgument(count > 0 || tickets.size() > count); return new GameState(playerState, lastPlayer(), tickets.withoutTopCards(count), privateCardState, currentPlayerId()); } /** * Returns the top card of the deck * * @return top card of the deck * @throws IllegalArgumentException thrown if privateCardState is an empty deck */ public Card topCard() { Preconditions.checkArgument(!privateCardState.isDeckEmpty()); return privateCardState.topDeckCard(); } /** * Returns the deck without the top card * * @return Returns the deck without the top card * @throws IllegalArgumentException thrown if privateCardState is an empty deck */ public GameState withoutTopCard() { Preconditions.checkArgument(!privateCardState.isDeckEmpty()); return new GameState(playerState, lastPlayer(), tickets, privateCardState.withoutTopDeckCard(), currentPlayerId()); } /** * Returns the Gamestate with more discardedCards added to the deck * * @param discardedCards discardedCards in question * @return Gamestate with more discardedCards */ public GameState withMoreDiscardedCards(SortedBag<Card> discardedCards) { return new GameState(playerState, lastPlayer(), tickets, privateCardState.withMoreDiscardedCards(discardedCards), currentPlayerId()); } /** * Returns a deck of cards from discarded if deck of cards is empty * * @param rng random var needed to shuffle the cards * @return new deck of cards from shuffled discarded cards or the same gamestate */ public GameState withCardsDeckRecreatedIfNeeded(Random rng) { if (privateCardState.isDeckEmpty()) { return new GameState(playerState, lastPlayer(), tickets, privateCardState.withDeckRecreatedFromDiscards(rng), currentPlayerId()); } else return this; } /** * Added tickets to a player * * @param playerId player in question * @param chosenTickets tickets added * @return new GameState with added tickets to a player * @throws IllegalArgumentException thrown if the players ticket size is greater than 0 */ public GameState withInitiallyChosenTickets(PlayerId playerId, SortedBag<Ticket> chosenTickets) { Preconditions.checkArgument(playerState(playerId).tickets().size() < 1); Map<PlayerId, PlayerState> addedTickets = new TreeMap<>(playerState); addedTickets.put(playerId, playerState(playerId).withAddedTickets(chosenTickets)); return new GameState(addedTickets, lastPlayer(), tickets, privateCardState, currentPlayerId()); } //Block 2 of methods /** * Removed drawnTickets and added the chosenTickets to the player * * @param drawnTickets removed tickets * @param chosenTickets added tickets * @return gameState with removed drawnTickets and added the chosenTickets * @throws IllegalArgumentException thrown if drawnTicket doesn't contain chosenTickets */ public GameState withChosenAdditionalTickets(SortedBag<Ticket> drawnTickets, SortedBag<Ticket> chosenTickets) { Preconditions.checkArgument(drawnTickets.contains(chosenTickets)); Map<PlayerId, PlayerState> additionalTickets = new TreeMap<>(playerState); additionalTickets.put(currentPlayerId(), playerState(currentPlayerId()).withAddedTickets(chosenTickets)); return new GameState(additionalTickets, lastPlayer(), tickets.withoutTopCards(drawnTickets.size()), privateCardState, currentPlayerId()); } /** * Returns GameState with playerState changed to fit the card and privatecardState changed * * @param slot position of card swap * @return GameState with playerState changed to fit the card and privatecardState changed * @throws IllegalArgumentException thrown if we cannot draw cards */ public GameState withDrawnFaceUpCard(int slot) { Preconditions.checkArgument(canDrawCards()); var playerstatecopy = new HashMap<>(playerState); playerstatecopy.put(currentPlayerId(), playerState(currentPlayerId()).withAddedCard(privateCardState.faceUpCard(slot))); return new GameState(playerstatecopy, lastPlayer(), tickets, privateCardState.withDrawnFaceUpCard(slot), currentPlayerId()); } /** * Picked Card from deck to player * * @return player has a new card * @throws IllegalArgumentException thrown if we cannot draw cards */ public GameState withBlindlyDrawnCard() { Preconditions.checkArgument(canDrawCards()); Map<PlayerId, PlayerState> drawnCards = new TreeMap<>(playerState); drawnCards.put(currentPlayerId(), currentPlayerState().withAddedCard(topCard())); return new GameState(drawnCards, lastPlayer(), tickets, privateCardState.withoutTopDeckCard(), currentPlayerId()); } /** * Claimed route * * @param route route in question * @param cards cards used to claim the route * @return player has new route and dicards has new cards */ public GameState withClaimedRoute(Route route, SortedBag<Card> cards) { Map<PlayerId, PlayerState> withClaimedRoute = new TreeMap<>(playerState); withClaimedRoute.put(currentPlayerId(), playerState(currentPlayerId()).withClaimedRoute(route, cards)); return new GameState(withClaimedRoute, lastPlayer(), tickets, privateCardState.withMoreDiscardedCards(cards), currentPlayerId()); } /** * Asks were the last turn will begin * * @return will the last turn begin */ public boolean lastTurnBegins() { return lastPlayer() == null && currentPlayerState().carCount() <= 2; } /** * Makes last player begin * * @return returns player that begins? */ public GameState forNextTurn() { PlayerId lastPlayer1 = lastTurnBegins() ? currentPlayerId() : lastPlayer(); return new GameState(playerState, lastPlayer1, tickets, privateCardState, currentPlayerId().next()); } }
package com.github.abryb.bsm; class AppException extends Exception { AppException(String s, Exception e) { super(s, e); } AppException(Exception e) { super("Something went wrong. Totally unexpected error.", e); } }
package com.nitgar.axonsample.controller; /** * Created by anuraggupta on 27/03/17. */ public class HelloControllerTest { public void sayHello() throws Exception { } }
package com.github.ezauton.core.utils; import com.github.ezauton.core.actuators.Actuators; import com.github.ezauton.core.actuators.VelocityMotor; import com.github.ezauton.core.actuators.VoltageMotor; import com.github.ezauton.core.actuators.implementations.BaseSimulatedMotor; import com.github.ezauton.core.actuators.implementations.BoundedVelocityProcessor; import com.github.ezauton.core.actuators.implementations.RampUpVelocityProcessor; import com.google.common.util.concurrent.AtomicDouble; import org.junit.jupiter.api.Test; import java.util.concurrent.TimeUnit; import static org.junit.jupiter.api.Assertions.*; public class ActuatorsTest { @Test public void testSimpleVoltToVel() { AtomicDouble atomicDouble = new AtomicDouble(); VoltageMotor voltageMotor = atomicDouble::set; VelocityMotor velocityMotor = Actuators.roughConvertVoltageToVel(voltageMotor, 16); velocityMotor.runVelocity(16); assertEquals(1D, atomicDouble.doubleValue(), 1E-6); velocityMotor.runVelocity(20); assertEquals(1D, atomicDouble.doubleValue(), 1E-6); velocityMotor.runVelocity(8); assertEquals(0.5D, atomicDouble.doubleValue(), 1E-6); velocityMotor.runVelocity(0); assertEquals(0, atomicDouble.doubleValue(), 1E-6); velocityMotor.runVelocity(-8); assertEquals(-0.5D, atomicDouble.doubleValue(), 1E-6); velocityMotor.runVelocity(-16); assertEquals(-1D, atomicDouble.doubleValue(), 1E-6); velocityMotor.runVelocity(-20); assertEquals(-1D, atomicDouble.doubleValue(), 1E-6); } @Test public void testRampUpVelocityProcessor() { AtomicDouble velocity = new AtomicDouble(); VelocityMotor velocityMotor = velocity::set; ManualClock clock = new ManualClock(); RampUpVelocityProcessor velocityProcessor = new RampUpVelocityProcessor(velocityMotor, clock, 1); velocityProcessor.runVelocity(2); clock.addTime(1, TimeUnit.SECONDS); velocityProcessor.update(); assertEquals(1, velocity.doubleValue(), 1E-6); clock.addTime(1, TimeUnit.SECONDS); velocityProcessor.update(); assertEquals(2, velocity.doubleValue(), 1E-6); clock.addTime(1, TimeUnit.SECONDS); velocityProcessor.update(); assertEquals(2, velocity.doubleValue(), 1E-6); velocityProcessor.runVelocity(1); clock.addTime(990, TimeUnit.MILLISECONDS); velocityProcessor.update(); assertEquals(1.01D, velocity.doubleValue(), 1E-6); velocityProcessor.runVelocity(10); clock.addTime(990, TimeUnit.MILLISECONDS); velocityProcessor.update(); assertEquals(2D, velocity.doubleValue(), 1E-6); assertEquals(2D, velocityProcessor.getLastVelocity(), 1E-6); } @Test public void testBoundedVelocityProcessor() { AtomicDouble velocity = new AtomicDouble(); VelocityMotor velocityMotor = velocity::set; BoundedVelocityProcessor velocityProcessor = new BoundedVelocityProcessor(velocityMotor, 16); velocityProcessor.runVelocity(1); assertEquals(1, velocity.doubleValue(), 1E-6); velocityProcessor.runVelocity(-15); assertEquals(-15, velocity.doubleValue(), 1E-6); velocityProcessor.runVelocity(-16); assertEquals(-16, velocity.doubleValue(), 1E-6); velocityProcessor.runVelocity(16); assertEquals(16, velocity.doubleValue(), 1E-6); velocityProcessor.runVelocity(-17); assertEquals(-16, velocity.doubleValue(), 1E-6); velocityProcessor.runVelocity(18); assertEquals(16, velocity.doubleValue(), 1E-6); } @Test public void testBoundedVelocityProcessorNegMaxSpeed() { AtomicDouble velocity = new AtomicDouble(0); assertThrows(IllegalArgumentException.class, () -> new BoundedVelocityProcessor(velocity::set, -10)); } @Test public void testBaseSimulatedMotor() { AtomicDouble velocity = new AtomicDouble(); VelocityMotor velocityMotor = velocity::set; ManualClock clock = new ManualClock(); BaseSimulatedMotor simulatedMotor = new BaseSimulatedMotor(clock); simulatedMotor.runVelocity(1); clock.addTime(1, TimeUnit.SECONDS); assertEquals(1, simulatedMotor.getPosition(), 1E-6); assertEquals(1, simulatedMotor.getVelocity(), 1E-6); clock.addTime(1, TimeUnit.SECONDS); assertEquals(2, simulatedMotor.getPosition(), 1E-6); assertEquals(1, simulatedMotor.getVelocity(), 1E-6); simulatedMotor.runVelocity(2); clock.addTime(1, TimeUnit.SECONDS); assertEquals(4, simulatedMotor.getPosition(), 1E-6); simulatedMotor.runVelocity(3); clock.addTime(1, TimeUnit.SECONDS); assertEquals(7, simulatedMotor.getPosition(), 1E-6); simulatedMotor.setSubscribed(velocityMotor); simulatedMotor.runVelocity(2); assertEquals(2, velocity.doubleValue(), 1E-6); assertSame(velocityMotor, simulatedMotor.getSubscribed()); } }
package com.ifli.mbcp.vo; import java.util.Date; public class FundVO { private Long PK_FundID; private String created_by; private Date created_date; private String fundName; private String modified_by; private Date modified_Date; public Long getPK_FundID() { return PK_FundID; } public String getCreated_by() { return created_by; } public Date getCreated_date() { return created_date; } public String getFundName() { return fundName; } public String getModified_by() { return modified_by; } public Date getModified_Date() { return modified_Date; } public void setPK_FundID(Long pK_FundID) { PK_FundID = pK_FundID; } public void setCreated_by(String created_by) { this.created_by = created_by; } public void setCreated_date(Date created_date) { this.created_date = created_date; } public void setFundName(String fundName) { this.fundName = fundName; } public void setModified_by(String modified_by) { this.modified_by = modified_by; } public void setModified_Date(Date modified_Date) { this.modified_Date = modified_Date; } }