text
stringlengths
10
2.72M
package ch.bfh.bti7301.w2013.battleship.gui; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.ResourceBundle; import java.util.Timer; import java.util.TimerTask; import java.util.regex.Matcher; import java.util.regex.Pattern; import javafx.application.Platform; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Pos; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.ListView; import javafx.scene.control.TextField; import javafx.scene.effect.InnerShadow; import javafx.scene.input.MouseEvent; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.scene.shape.Circle; import javafx.scene.shape.Shape; import ch.bfh.bti7301.w2013.battleship.network.Connection; import ch.bfh.bti7301.w2013.battleship.network.ConnectionState; import ch.bfh.bti7301.w2013.battleship.network.DiscoveryListener; import ch.bfh.bti7301.w2013.battleship.network.NetworkInformation; import com.sun.javafx.collections.ObservableListWrapper; public class NetworkPanel extends VBox { private ObservableList<NetworkClient> opponents = new ObservableListWrapper<NetworkClient>( new LinkedList<NetworkClient>()); private Connection conn = Connection.getInstance(); private Map<String, NetworkClient> peers = new HashMap<>(); final TextField ipAddress = new TextField(); public NetworkPanel() { setSpacing(4); getChildren().add(getIpBox()); final ListView<NetworkClient> ips = new ListView<>(); conn.addDiscoveryListener(new DiscoveryListener() { @Override public void foundOpponent(final String ip, final String name) { // Ignore my own IPs if (NetworkInformation.getIntAddresses().contains(ip)) return; Platform.runLater(new Runnable() { @Override public void run() { NetworkClient nc = peers.get(ip); if (nc != null) { if (!nc.name.equals(name)) { opponents.remove(nc); nc.name = name; opponents.add(nc); } nc.seen(); } else { nc = new NetworkClient(ip, name); peers.put(ip, nc); opponents.add(nc); } } }); } }); ips.setItems(opponents); ips.setOnMouseClicked(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { ipAddress.setText(ips.getSelectionModel().getSelectedItem().ip); } }); getChildren().add(ips); Timer time = new Timer(); TimerTask task = new TimerTask() { final List<NetworkClient> toRemove = new LinkedList<>(); @Override public void run() { if (!toRemove.isEmpty()) return; for (NetworkClient opponent : opponents) { if (opponent.isStale()) { peers.remove(opponent.ip); toRemove.add(opponent); } } if (!toRemove.isEmpty()) { Platform.runLater(new Runnable() { @Override public void run() { opponents.removeAll(toRemove); toRemove.clear(); } }); } } }; time.schedule(task, 0, 2000); } private HBox getIpBox() { // Temporary input field to enter the opponent's final StateBox stateBox = new StateBox(); stateBox.update(conn.getConnectionState(), conn.getConnectionStateMessage()); getChildren().add(stateBox); final HBox ipBox = new HBox(); Matcher m = Pattern.compile("\\d+\\.\\d+\\.\\d+\\.").matcher( NetworkInformation.getIntAddresses().toString()); if (m.find()) ipAddress.setText(m.group()); ipBox.getChildren().add(ipAddress); final Button connect = new Button(ResourceBundle.getBundle( "translations").getString("connect")); Connection.getInstance().addConnectionStateListener( new GuiConnectionStateListenerAdapter() { @Override public void doStateChanged(ConnectionState newState, String msg) { stateBox.update(newState, msg); switch (newState) { case LISTENING: ipBox.setVisible(true); break; case CONNECTED: ipBox.setVisible(false); break; default: break; } } }); connect.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { Connection.getInstance().connectOpponent(ipAddress.getText()); System.out.println(ipAddress.getText()); } }); ipBox.getChildren().add(connect); return ipBox; } private class StateBox extends HBox { private Shape light; private Label text; private InnerShadow glow = new InnerShadow(); public StateBox() { setSpacing(4); setAlignment(Pos.CENTER_LEFT); light = new Circle(6); getChildren().add(light); text = new Label(); getChildren().add(text); } public void update(ConnectionState state, String msg) { switch (state) { case CLOSED: light.setFill(Color.GREY); light.setEffect(null); break; case CONNECTED: light.setFill(Color.GREENYELLOW); glow.setColor(Color.GREEN); light.setEffect(glow); break; case LISTENING: light.setFill(Color.YELLOW); glow.setColor(Color.ORANGE); light.setEffect(glow); break; default: light.setFill(Color.ORANGE); glow.setColor(Color.RED); light.setEffect(glow); } text.setText(msg); } } private class NetworkClient { String ip, name; long lastSeen; public NetworkClient(String ip, String name) { this.ip = ip; this.name = name; lastSeen = System.currentTimeMillis(); } @Override public String toString() { return name; } public void seen() { lastSeen = System.currentTimeMillis(); } public boolean isStale() { return System.currentTimeMillis() - lastSeen > 6000; } } }
/** * COPYRIGHT (C) 2013 KonyLabs. All Rights Reserved. * * @author rbanking */ package com.classroom.services.web.security; import java.util.UUID; import org.joda.time.LocalDateTime; import org.springframework.beans.factory.annotation.Value; import org.springframework.security.authentication.AuthenticationServiceException; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.CredentialsExpiredException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.util.Assert; import com.classroom.services.web.security.services.IUserSecurityService; /** * * @author mkol * */ public class RESTDaoAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider { @Value("${security.login.token.lifetime.hours}") private final int credentialsLifeHours = 24; private IUserSecurityService userSecurityService; /** * This is the method which actually performs the check to see whether the * user is indeed the correct user. * * @param userDetails * the user details * @param authentication * the authentication * @throws AuthenticationException * the authentication exception */ @Override protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { RESTUser user = (RESTUser) userDetails; boolean isCredentialsExpired = user.getSecurityTokenCreation() .isBefore(LocalDateTime.now().minusHours(credentialsLifeHours)); if (isCredentialsExpired) { throw new CredentialsExpiredException("Secure token has expired"); } } public Authentication authenticate(Authentication authentication) throws AuthenticationException { if(authentication == null || authentication.getPrincipal()==null){ return new UsernamePasswordAuthenticationToken(null, null, null); } Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication, messages.getMessage("AbstractUserDetailsAuthenticationProvider.onlySupports", "Only UsernamePasswordAuthenticationToken is supported")); // Determine username String username = (authentication.getPrincipal() == null) ? "NONE_PROVIDED" : authentication.getName(); boolean cacheWasUsed = true; UserDetails user = this.getUserCache().getUserFromCache(username); if (user == null) { cacheWasUsed = false; try { user = retrieveUser(username, (UsernamePasswordAuthenticationToken) authentication); } catch (UsernameNotFoundException notFound) { logger.debug("User '" + username + "' not found"); if (hideUserNotFoundExceptions) { throw new BadCredentialsException(messages.getMessage( "AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials")); } else { throw notFound; } } Assert.notNull(user, "retrieveUser returned null - a violation of the interface contract"); } try { this.getPreAuthenticationChecks().check(user); additionalAuthenticationChecks(user, (UsernamePasswordAuthenticationToken) authentication); } catch (AuthenticationException exception) { if (cacheWasUsed) { // There was a problem, so try again after checking // we're using latest data (i.e. not from the cache) cacheWasUsed = false; user = retrieveUser(username, (UsernamePasswordAuthenticationToken) authentication); getPreAuthenticationChecks().check(user); additionalAuthenticationChecks(user, (UsernamePasswordAuthenticationToken) authentication); } else { throw exception; } } getPreAuthenticationChecks().check(user); if (!cacheWasUsed) { this.getUserCache().putUserInCache(user); } Object principalToReturn = user; if (isForcePrincipalAsString()) { principalToReturn = user.getUsername(); } return createSuccessAuthentication(principalToReturn, authentication, user); } /** * Retrieve user. * * @param token * This is the security token that was generated by the user. * @param authentication * The authentication request, which subclasses <em>may</em> need * to perform a binding-based retrieval of the * <code>UserDetails</code> * @return the user information (never <code>null</code> - instead an * exception should the thrown) * @throws AuthenticationException * if the credentials could not be validated (generally a * <code>BadCredentialsException</code>, an * <code>AuthenticationServiceException</code> or * <code>UsernameNotFoundException</code>) */ @Override protected UserDetails retrieveUser(String token, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { UserDetails loadedUser; try { loadedUser = getUserSecurityService().getUserBySecurityToken( UUID.fromString(token)); } catch (UsernameNotFoundException notFound) { throw notFound; } catch (Exception repositoryProblem) { throw new AuthenticationServiceException( repositoryProblem.getMessage(), repositoryProblem); } if (loadedUser == null) { throw new AuthenticationServiceException( "UserSecurityService returned null, which is an interface contract violation"); } return loadedUser; } /* * (non-Javadoc) * * @see org.springframework.security.authentication.dao. * AbstractUserDetailsAuthenticationProvider#doAfterPropertiesSet() */ @Override protected void doAfterPropertiesSet() { Assert.notNull(this.userSecurityService, "A UserSecurityServiceImpl must be set"); } /** * Gets the user security service. * * @return the user security service */ public IUserSecurityService getUserSecurityService() { return userSecurityService; } /** * Sets the user security service. * * @param userSecurityService * the user security service */ public void setUserSecurityService(IUserSecurityService userSecurityService) { this.userSecurityService = userSecurityService; } }
package com.designurway.idlidosa.a.activity; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.widget.EditText; import android.widget.Toast; import com.designurway.idlidosa.R; import com.designurway.idlidosa.a.model.ErrorMessageModel; import com.designurway.idlidosa.a.retrofit.BaseClient; import com.designurway.idlidosa.a.retrofit.RetrofitApi; import com.designurway.idlidosa.a.utils.AndroidUtils; import com.designurway.idlidosa.a.utils.UtilConstant; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class ForgotPwdActivity extends AppCompatActivity { private static final String TAG ="ForgotPwdActivity" ; @BindView(R.id.new_pwd_et) EditText newPwdEt; @BindView(R.id.conf_password_et) EditText confPwdEt; String phoneNum; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_forgot_pwd); ButterKnife.bind(this); if (getIntent().hasExtra(UtilConstant.PHONE_FROM_ENTER_OTP)){ phoneNum=getIntent().getStringExtra(UtilConstant.PHONE_FROM_ENTER_OTP); } } @OnClick(R.id.change_pwd_btn) public void changePwd(){ String newPwd = newPwdEt.getText().toString().trim(); String confPwd = confPwdEt.getText().toString().trim(); if (!AndroidUtils.isNetworkAvailable(this)) { Toast.makeText(getApplicationContext(), this.getText(R.string.no_internet), Toast.LENGTH_SHORT).show(); } if (newPwd.isEmpty() && confPwd.isEmpty()) { Toast.makeText(this, this.getText(R.string.fill_credentials), Toast.LENGTH_SHORT).show(); } if (!newPwd.equals(confPwd)){ Toast.makeText(this, this.getText(R.string.password_mismatch), Toast.LENGTH_SHORT).show(); } else{ changePwdApi(newPwd); } } private void changePwdApi(String newPwd) { RetrofitApi retrofitApi = BaseClient.getClient().create(RetrofitApi.class); Call<ErrorMessageModel> call = retrofitApi.setCustomerForgotPwd(phoneNum,newPwd); Toast.makeText(this, phoneNum, Toast.LENGTH_SHORT).show(); call.enqueue(new Callback<ErrorMessageModel>() { @Override public void onResponse(Call<ErrorMessageModel> call, Response<ErrorMessageModel> response) { if (response.isSuccessful()) { if (response.body().getMessage().contains("password updated")) { Intent intent = new Intent(ForgotPwdActivity.this, MobileVerificationActivity.class); startActivity(intent); } else { Toast.makeText(ForgotPwdActivity.this, getString(R.string.failed_update), Toast.LENGTH_SHORT).show(); } } else{ Toast.makeText(ForgotPwdActivity.this, getString(R.string.failed_to_verify), Toast.LENGTH_SHORT).show(); } } @Override public void onFailure(Call<ErrorMessageModel> call, Throwable t) { Log.d(TAG, "onFailure" + t.getMessage()); } }); } }
package EmployeeForCompany.com; import java.util.Comparator; public class Employees implements Comparable<Employees>{ private String name; private int id; private String department; private int salary; private int experience; public Employees() { super(); name="AAshish"; id=12783; department="JAVA"; salary=1200000; experience=5; } public Employees(String name,int id,String department, int salary, int experience) { super(); this.name = name; this.id=id; this.department = department; this.salary = salary; this.experience = experience; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department; } public int getSalary() { return salary; } public void setSalary(int salary) { this.salary = salary; } public void setId(int id) { this.id =id; } public int getId() { return id; } public int getExperience() { return experience; } public void setExperience(int experience) { this.experience = experience; } @Override public int compareTo(Employees o) { return this.id-o.id; } }
package packageclass; import java.util.Scanner; public class Bai4 { public static void main(String[] args) { menu(); int a=2; Scanner s = new Scanner(System.in); // a = s.nextInt(); switch (a) { case 1: {PhuongTrinhBatMot(); break;} case 2: {PhuongTrinhBatHai(); break;} case 3: {TinhTienDien(); break;} case 4: { break;} } } public static void menu() { System.out.println("----Menu-----"); System.out.println("1. Giải phương trình bật nhất"); System.out.println("2. Giải phương trình bật hai"); System.out.println("3. Tính tiền điện"); System.out.println("4. Kết thúc"); } public static void PhuongTrinhBatMot() { Scanner s = new Scanner(System.in); double a; double b; double x; System.out.println("Nhập a"); a = s.nextInt(); System.out.println("Nhập b"); b = s.nextInt(); if (a==0) { if (b==0) { System.out.println("vô số nghiệm"); } else { System.out.println("vô nghiệm"); } } else { x =-b/a; System.out.println("Nhiệm x: " + x); } } public static void PhuongTrinhBatHai() { Scanner s= new Scanner(System.in); double a; double b; double c; double d; double x1; double x2; System.out.println("Nhập a: "); a = s.nextInt(); System.out.println("Nhập b: "); b = s.nextInt(); System.out.println("Nhập c: "); c = s.nextInt(); if (a==0) { if (b==0) { if (c==0) { System.out.println("Phương trình vô số nghiệm"); } else { System.out.println("Phương trình vô nghiệm"); } } else { x1 = -c/b; System.out.println("Phương trình có nghiệm: " + x1); } } else { d = Math.pow(b,2)-4*a*c; if (d<0) { System.out.println("Phương trình vô nghiệm"); } else if (d==0) { x1 = -b/(2*a); System.out.println("Phương trình có nghiệm kép: " + x1); } else { x1 = (-b+Math.sqrt(d))/ 2*a; x2 = (-b-Math.sqrt(d))/ 2*a; System.out.println("Phương trình có nghiệm x1: " + x1); System.out.println("Phương trình có nghiệm x2: " + x2); } } } public static void TinhTienDien() { Scanner s = new Scanner(System.in); int a; int b; int c; int d; System.out.println("Nhập số cũ"); a = s.nextInt(); System.out.println("Nhập số mới"); b = s.nextInt(); c = b - a; if (c < 50) { d = c*100; System.out.println("Tiền cần trả: " + d); } else { d = (c-50)*1200 + 50*1000; System.out.println("Tiền cần trả: " + d); } } }
package com.egame.beans; import org.json.JSONObject; import com.egame.utils.ui.IconBeanImpl; /** * @desc 大家还喜欢的实体类 * * @Copyright lenovo * * @Project EGame4th * * @Author zhangrh@lenovo-cw.com * * @timer 2012-1-15 * * @Version 1.0.0 * * @JDK version used 6.0 * * @Modification history none * * @Modified by none */ public class MoreLikeBean extends IconBeanImpl { private String gameId; private String gameName; public MoreLikeBean(JSONObject obj){ super(obj.optString("gamePic")+ "pic1.jpg"); this.gameId=obj.optString("gameId"); this.gameName=obj.optString("gameName"); } /** * @return 返回 gameId */ public String getGameId() { return gameId; } /** * @param 对gameId进行赋值 */ public void setGameId(String gameId) { this.gameId = gameId; } /** * @return 返回 gameName */ public String getGameName() { return gameName; } /** * @param 对gameName进行赋值 */ public void setGameName(String gameName) { this.gameName = gameName; } }
package com.feng.java; import com.feng.annotation.MyAnnotation; //@MyAnnotation //@MyAnnotation("000") @MyAnnotation(value = "abc") public class Goods implements Comparable { private int gid; private String gname; private Double price; public Goods(int gid, String gname, Double price) { this.gid = gid; this.gname = gname; this.price = price; } public Goods() { } public String getGname() { return gname; } public void setGname(String gname) { this.gname = gname; } public Double getPrice() { return price; } public void setPrice(Double price) { this.price = price; } @Override public String toString() { return "Goods{" + "gid=" + gid + ", gname='" + gname + '\'' + ", price=" + price + '}'; } public int getGid() { return gid; } public void setGid(int gid) { this.gid = gid; } @Override public int compareTo(Object o) { if (o instanceof Goods){ Goods goods = (Goods)o; if (this.price>goods.price){ return 1; }else if (this.price<goods.price){ return -1; }else{ return 0; } } return -2; } }
package myGame; import java.awt.Graphics; import java.awt.Rectangle; import java.awt.event.KeyEvent; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.JLayeredPane; public class Character { private int WIDTH = 30*Window.SIZE; private int HEIGHT = 54*Window.SIZE; static int X = 0; static int Y = 0; private static String path; private String caracImage; private int iniX = 0, iniY = 0, x = 150, y = 600, xa = 0, ya = 0, i = 0, hauteurSaut = 0, jumpSpeed=1, levelNumber = 0; double ySpeed=0, ySpeedX=-2490; private double step=0, step2=0; private long savedTime=0, savedTime2=0, savedTimeStart=0, savedTimeJump=0; private boolean compterHauteur = true, sauter = false, droite = true, gauche = false, bougerX, bougerY, animer = false, top=false, inertDroite=false, inertGauche=false, ladder=false, saveTime=true, startStep=true, allowJump=false; private BufferedImage img = null; private Rectangle[] rectList = new Rectangle[510], ladderList = new Rectangle[10], movingList = new Rectangle[20], movingList2 = new Rectangle[20]; public boolean isAnimer() { return animer; } public void setAnimer(boolean animer) { this.animer = animer; } public double getStep() { return step; } public void setStep(double step) { this.step = step; } public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } public int getXa() { return xa; } public int getYa() { return ya; } public void setYa(int ya) { this.ya = ya; } public void setXa(int xa) { this.xa = xa; } public int getWIDTH() { return WIDTH; } public void setWIDTH(int wIDTH) { WIDTH = wIDTH; } public int getHEIGHT() { return HEIGHT; } public void setHEIGHT(int hEIGHT) { HEIGHT = hEIGHT; } public String getCaracImage() { return caracImage; } public void setCaracImage(String caracImage) { this.caracImage = caracImage; } public Character(int x, int y, Rectangle[] rectList, Rectangle[] echelletList, Rectangle[] mouvantetList, Rectangle[] mouvantetList2, int levelNumber ) { this.x= x; this.y= y; this.iniX= x; this.iniY= y; this.rectList= rectList; this.ladderList= echelletList; this.movingList= mouvantetList; this.movingList2= mouvantetList2; this.levelNumber = levelNumber; } /*//////////////////////////////////////////////*/ /*////////// DEPLACEMENT /////////*/ public void move() { if(Main.SreenSize==1){path="small";step2=0.5;} else if(Main.SreenSize==2){path="big";step2=0;} if(caracImage!="grome"){ Character.X = x; Character.Y = y; } if(animer && startStep){step=100;startStep=false;} if(!animer)startStep=true; if( System.nanoTime() > savedTimeStart+1000000/Main.SreenSize){ savedTimeStart = System.nanoTime(); if(step>10)step-=5; } if(System.currentTimeMillis()> savedTime+10) { savedTime = System.currentTimeMillis(); bougerX=true; } else{bougerX=false;} if(System.nanoTime()> savedTimeJump+ySpeed) { savedTimeJump = System.nanoTime(); bougerY=true; } else{bougerY=false;} if(bougerY){y = y + ya;} /*JUMP FUNCTION*/ if(sauter && ySpeedX > -2800 && levelNumber!=9)ySpeedX-=10; else if(sauter && ySpeedX > -2800 && levelNumber==9)ySpeedX-=18; else if (ySpeedX < -2300) ySpeedX+=0.02; ySpeed = -(3-(Math.pow(ySpeedX, 2))/2); if (collisionD()&& !sauter && !ladder){ ya = 0; sauter=false; ySpeedX=-2600; if(top){ top=false; if(!animer)xa=0; else if(droite) xa=6; else if(gauche) xa=-6; inertDroite=false; inertGauche=false; } } if(top) { if(inertDroite)xa=6; else if(inertGauche)xa=-6;; } if(x+xa < 0 || x+xa > 935*Main.SreenSize)xa=0; if (collisionR()){ if(xa>0)xa=0; } if (collisionL()){ if(xa<0)xa=0; } if((!sauter && !collisionD()) && !ladder && !collisionE()){ ya = 8; } if(collisionT()){ sauter=false; } if(collisionMU() && Level.up && !sauter && ya<1 ){ya=-6;allowJump=true;} if(collisionMU() && ya != -1 && !sauter)ya=-6; if(bougerX){x = x + xa;} if(y <=hauteurSaut){sauter=false;} if(!collisionE())ladder=false; ////////////// DEAD /////////// if(Window.dead){ xa=0; x=iniX; y=iniY; } if(y>540*Main.SreenSize && caracImage!="grome"){y=-(500*Main.SreenSize);if(!Window.MUTE)Sound.DEAD.play();Window.dead=true;} } /*//////////////////////////////////////////////*/ /*////////// DETECTER TOUCHE /////////*/ public boolean isBougerX() { return bougerX; } public void setBougerX(boolean bougerX) { this.bougerX = bougerX; } public void keyReleased(KeyEvent e) { if(e.getKeyCode() == KeyEvent.VK_Q || e.getKeyCode() == KeyEvent.VK_D){xa=0;animer=false;} if (e.getKeyCode() == KeyEvent.VK_SPACE ) { compterHauteur = true; } if(!top){inertDroite=false;inertGauche=false;} } public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_Z) { if(collisionE()){ ya= -6; y = y + ya; ladder=true; } else ladder=false; } ///////////////// JUMP ///////////////// if (e.getKeyCode() == KeyEvent.VK_SPACE) { if(compterHauteur && (collisionD() || collisionE() || allowJump)){ sauter=true; if(!Window.MUTE)Sound.JUMP.play(); hauteurSaut = y-70*Main.SreenSize; compterHauteur=false; ySpeedX = -230; sauter=true; if(allowJump){jumpSpeed=2; ySpeed=ySpeed/2;} else jumpSpeed=1; allowJump=false; } if(y > hauteurSaut && sauter) { if (droite && animer)inertDroite=true; if (gauche && animer)inertGauche=true; top=true; ya=-10; } else if(y <=hauteurSaut) {sauter=false; } } if (e.getKeyCode() == KeyEvent.VK_Q) { if(!collisionM() || Level.up )xa = -6; else xa=-12; animer=true; gauche=true; droite=false; if(top){inertGauche=true; inertDroite=false;} if(y <=hauteurSaut) {sauter=false;} } if (e.getKeyCode() == KeyEvent.VK_D) { if(!collisionM() || Level.up )xa = 6; else xa=12; animer=true; droite=true; gauche=false; if(top){inertGauche=false; inertDroite=true;} if(y <=hauteurSaut) {sauter=false;} } } public boolean isDroite() { return droite; } public void setDroite(boolean droite) { this.droite = droite; } public boolean isGauche() { return gauche; } public void setGauche(boolean gauche) { this.gauche = gauche; } /*//////////////////////////////////////////////*/ /*////////// COLLISION BAS ///////////*/ private boolean collisionD() { int result=0; try{ for(i=0; i< rectList.length; i++){ if(i<rectList.length && rectList[i]!=null && rectList[i].getBounds().intersects(getBoundsD())){ result++; } } }catch(ArrayIndexOutOfBoundsException|NullPointerException e){System.out.println("Out of array");}; if(result==0)return(false); else return(true); } /*////////// COLLISION DROITE ///////////*/ private boolean collisionR() { int result=0; try{ for(i=0; i< rectList.length; i++){ if(i<rectList.length && rectList[i]!=null && rectList[i].getBounds().intersects(getBoundsR())){ result++; } } }catch(ArrayIndexOutOfBoundsException|NullPointerException e){System.out.println("Out of array");} if(result==0)return(false); else return(true); } /*////////// COLLISION GAUCHE ///////////*/ private boolean collisionL() { int result=0; try{ for(i=0; i< rectList.length; i++){ if(i<rectList.length && rectList[i]!=null && rectList[i]!=null && rectList[i].getBounds().intersects(getBoundsL())){ result++; } }; }catch(ArrayIndexOutOfBoundsException|NullPointerException e){System.out.println("Out of array");}; if(result==0)return(false); else return(true); } /*////////// COLLISION TOP ///////////*/ private boolean collisionT() { int result=0; try{ for(i=0; i< rectList.length; i++){ if(i+1<rectList.length && rectList[i]!=null && rectList[i].getBounds().intersects(getBoundsT())){ result++; } } }catch(ArrayIndexOutOfBoundsException|NullPointerException e){System.out.println("Out of array");}; if(result==0)return(false); else return(true); } /*////////// COLLISION ECHELLE ///////////*/ private boolean collisionE() { int result=0; try{ for(i=0; i< ladderList.length; i++){ if(i<ladderList.length && ladderList[i]!=null && ladderList[i].getBounds().intersects(getBoundsE())){ result++; } } }catch(ArrayIndexOutOfBoundsException|NullPointerException e){System.out.println("Out of array");}; if(result==0)return(false); else return(true); } /*//////////////////////////////////////////////*/ /*////// COLLISION PLAT MOUVANTE ////////*/ boolean collisionM() { int result=0; try{ for(i=0; i< movingList.length; i++){ if(movingList[i]!=null && movingList[i].getBounds().intersects(getBoundsD())){ result++; } } }catch(ArrayIndexOutOfBoundsException|NullPointerException e){System.out.println("Out of array");}; if(result==0)return(false); else return(true); } /*//////////////////////////////////////////////*/ /*////// COLLISION PLAT MOUVANTE UP ////////*/ boolean collisionMU() { int result=0; try{ for(i=0; i< movingList2.length; i++){ if(movingList2[i]!=null && movingList2[i].getBounds().intersects(getBoundsD())){ result++; } } }catch(ArrayIndexOutOfBoundsException|NullPointerException e){System.out.println("Out of array");}; if(result==0)return(false); else return(true); } /*//////////////////////////////////////////////*/ /*////// RECTANGLE DE COLLISION //////*/ private Rectangle getBoundsD() { return new Rectangle(x+5, y+HEIGHT+6, WIDTH-10 , 3); } private Rectangle getBoundsR() { return new Rectangle(x+WIDTH, y, 3 , HEIGHT); } private Rectangle getBoundsL() { return new Rectangle(x-1, y, 3 , HEIGHT-1); } private Rectangle getBoundsT() { return new Rectangle(x+5, y, WIDTH-10 , 1); } private Rectangle getBoundsE() { return new Rectangle(x+(WIDTH/3), y+HEIGHT, WIDTH/3 , 1); } public Rectangle getBoundsA() { return new Rectangle(x, y, WIDTH , HEIGHT); } /*//////////////////////////////////////////////*/ /*////// DESSINER PERSO //////*/ public void paint(Graphics g) { JLayeredPane EverythingButPlayer; EverythingButPlayer = new JLayeredPane(); long currentTimeMillis = System.currentTimeMillis(); if(saveTime){savedTime2 = currentTimeMillis;saveTime=false;} try { if(animer && (droite || gauche) && collisionD()){ if(droite && animer ){ if( currentTimeMillis > savedTime2+(720))img = ImageIO.read(new File("image/"+path+"/caractere/"+caracImage+"/droite/08.png")); else if(currentTimeMillis > savedTime2+(630))img = ImageIO.read(new File("image/"+path+"/caractere/"+caracImage+"/droite/07.png")); else if(currentTimeMillis > savedTime2+(540))img = ImageIO.read(new File("image/"+path+"/caractere/"+caracImage+"/droite/06.png")); else if(currentTimeMillis > savedTime2+(450))img = ImageIO.read(new File("image/"+path+"/caractere/"+caracImage+"/droite/05.png")); else if(currentTimeMillis > savedTime2+(360))img = ImageIO.read(new File("image/"+path+"/caractere/"+caracImage+"/droite/04.png")); else if(currentTimeMillis > savedTime2+(270))img = ImageIO.read(new File("image/"+path+"/caractere/"+caracImage+"/droite/03.png")); else if(currentTimeMillis > savedTime2+(180))img = ImageIO.read(new File("image/"+path+"/caractere/"+caracImage+"/droite/02.png")); else if(currentTimeMillis > savedTime2+(90))img = ImageIO.read(new File("image/"+path+"/caractere/"+caracImage+"/droite/01.png")); if(currentTimeMillis > savedTime2+(720))saveTime=true; } if(gauche && animer){ if(currentTimeMillis > savedTime2+(720))img = ImageIO.read(new File("image/"+path+"/caractere/"+caracImage+"/gauche/08.png")); else if(currentTimeMillis > savedTime2+(630))img = ImageIO.read(new File("image/"+path+"/caractere/"+caracImage+"/gauche/07.png")); else if(currentTimeMillis > savedTime2+(540))img = ImageIO.read(new File("image/"+path+"/caractere/"+caracImage+"/gauche/06.png")); else if(currentTimeMillis > savedTime2+(450))img = ImageIO.read(new File("image/"+path+"/caractere/"+caracImage+"/gauche/05.png")); else if(currentTimeMillis > savedTime2+(360))img = ImageIO.read(new File("image/"+path+"/caractere/"+caracImage+"/gauche/04.png")); else if(currentTimeMillis > savedTime2+(270))img = ImageIO.read(new File("image/"+path+"/caractere/"+caracImage+"/gauche/03.png")); else if(currentTimeMillis > savedTime2+(180))img = ImageIO.read(new File("image/"+path+"/caractere/"+caracImage+"/gauche/02.png")); else if(currentTimeMillis > savedTime2+(90))img = ImageIO.read(new File("image/"+path+"/caractere/"+caracImage+"/gauche/01.png")); if(currentTimeMillis > savedTime2+(720))saveTime=true; } } else if(sauter && droite)img = ImageIO.read(new File("image/"+path+"/caractere/"+caracImage+"/droite/jump.png")); else if(sauter && gauche)img = ImageIO.read(new File("image/"+path+"/caractere/"+caracImage+"/gauche/jump.png")); else if(droite){ if(currentTimeMillis > savedTime2+750)img = ImageIO.read(new File("image/"+path+"/caractere/"+caracImage+"/droite/st05.png")); else if(currentTimeMillis > savedTime2+600)img = ImageIO.read(new File("image/"+path+"/caractere/"+caracImage+"/droite/st04.png")); else if(currentTimeMillis > savedTime2+450)img = ImageIO.read(new File("image/"+path+"/caractere/"+caracImage+"/droite/st03.png")); else if(currentTimeMillis > savedTime2+300)img = ImageIO.read(new File("image/"+path+"/caractere/"+caracImage+"/droite/st02.png")); else if(currentTimeMillis > savedTime2+150)img = ImageIO.read(new File("image/"+path+"/caractere/"+caracImage+"/droite/st01.png")); if(currentTimeMillis > savedTime2+750)saveTime=true; } else if(gauche){ if(currentTimeMillis > savedTime2+750)img = ImageIO.read(new File("image/"+path+"/caractere/"+caracImage+"/gauche/st05.png")); else if(currentTimeMillis > savedTime2+600)img = ImageIO.read(new File("image/"+path+"/caractere/"+caracImage+"/gauche/st04.png")); else if(currentTimeMillis > savedTime2+450)img = ImageIO.read(new File("image/"+path+"/caractere/"+caracImage+"/gauche/st03.png")); else if(currentTimeMillis > savedTime2+300)img = ImageIO.read(new File("image/"+path+"/caractere/"+caracImage+"/gauche/st02.png")); else if(currentTimeMillis > savedTime2+150)img = ImageIO.read(new File("image/"+path+"/caractere/"+caracImage+"/gauche/st01.png")); if(currentTimeMillis > savedTime2+750)saveTime=true; } } catch (IOException e) { } if(img!=null)img.getGraphics(); if(img!=null)g.drawImage(img,x, y+5, EverythingButPlayer); } }
package Scope; /** * * @author YNZ */ public class LocalVar { static int i; public static void main(String[] args) { //int i=0; local var. must be init. before using it. //local var. hiding the class field i. //Well, this is a java feature. this is not an error. for (int i = 0; i < 10; i++) { //local var. i within scope of for loop. System.out.print(" " + Math.random()); } System.out.println(""); for (int i = 0; i < 10; i++) {//local var. i with scope of for loop. System.out.print(" " + Math.random()); } System.out.print("\n"); } public void m() { int d; //method variable(local var.) //d++, it must be init. before using it; otherwise it gives comipling error. { { } }; } public void m(int x) { int y = 0; if (true) { int z = 0; } else { int z = 100; } int z =300; //System.out.println(z); here z is outside its life span. } }
package com.yxkj.facexradix.star; public class MessageBean { String type; Object data; long timestmp; String sn; public String getSn() { return sn; } public void setSn(String sn) { this.sn = sn; } public long getTimestmp() { return timestmp; } public void setTimestmp(long timestmp) { this.timestmp = timestmp; } public MessageBean(String type, Object data, long timestmp) { this.type = type; this.data = data; this.timestmp = timestmp; } public MessageBean() { } public MessageBean(String type, Object data) { this.type = type; this.data = data; } public String getType() { return type; } public void setType(String type) { this.type = type; } public Object getData() { return data; } public void setData(Object data) { this.data = data; } }
package com.github.ofofs.jca.handler; /** * @author kangyonggan * @since 6/22/18 */ public interface LogHandler { /** * 打印方法入参 * * @param packageName 包名 * @param className 类名 * @param methodName 方法名 * @param args 方法的入参 */ void logBefore(String packageName, String className, String methodName, Object... args); /** * 打印方法出参和耗时 * * @param packageName 包名 * @param className 类名 * @param methodName 方法名 * @param startTime 开始时间 * @param returnValue 方法的返回值 * @return 返回方法的返回值 */ Object logAfter(String packageName, String className, String methodName, long startTime, Object returnValue); }
package com.example.ips.model; import java.util.Date; public class ServerplanPublicUse { private Integer id; private String server; private String application; private String memo; private Date createTime; public String getApplication() { return application; } public void setApplication(String application) { this.application = application; } private Date updateTime; private Integer createUser; private Integer updateUser; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getServer() { return server; } public void setServer(String server) { this.server = server == null ? null : server.trim(); } public String getMemo() { return memo; } public void setMemo(String memo) { this.memo = memo == null ? null : memo.trim(); } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } public Integer getCreateUser() { return createUser; } public void setCreateUser(Integer createUser) { this.createUser = createUser; } public Integer getUpdateUser() { return updateUser; } public void setUpdateUser(Integer updateUser) { this.updateUser = updateUser; } }
package com.zantong.mobilecttx.daijia.bean; import com.zantong.mobilecttx.base.bean.BaseResult; /** * Created by zhoujie on 2017/2/21. */ public class DaiJiaOrderDetailResult extends BaseResult { private DaiJiaOrderDetailBean data; public void setData(DaiJiaOrderDetailBean data) { this.data = data; } public DaiJiaOrderDetailBean getData() { return data; } public class DaiJiaOrderDetailBean { /** * 订单id */ String orderId; /** * 订单状态[派单中0|司机在途1|司机等待2|代驾中3|已完成4|已取消5|已预约6] */ String orderStatus; /** * 代驾客户 */ String name; /** * 代驾客户手机 */ String mobile; /** * 出发地址 */ String address; /** * 出发地址经度(百度坐标) */ double addressLng; /** * 出发地址纬度(百度坐标) */ double addressLat; /** * 订单创建时间,格式为2013-11-28 12:00:00 */ String createTime; /** * 订单取消时间,格式为2013-11-28 12:00:00 */ String cancelTime; /** * 要求到达时间,格式:20:30 */ String requestTime; /** * 系统自动派单时间,格式为2013-11-28 12:00:00 */ String assignTime; /** * 司机接单时间,格式为2013-11-28 12:00:00 */ String acceptTime; /** * 司机到达时间,格式为2013-11-28 12:00:00 */ String arriveTime; /** * 代驾开始时间,格式为2013-11-28 12:00:00 */ String beginTime; /** * 代驾结束时间,格式为2013-11-28 12:00:00 */ String endTime; /** * 行驶距离,公里 */ String distance; /** * 等候时间,分钟 */ String waitTime; /** * 订单金额,元 */ String amount; /** * 实际抵扣金额,元。如果创建订单时指定的是免除公里数,则会换算为实际的优惠金额 */ String amountCoupon; /** * 备注信息 */ String comment; /** * 司机工号 */ String driverNo; /** * 司机手机号码 */ String driverMobile; /** * 如果司机在途,则计算路程,米 */ String driverDistance; /** * 如果司机在途,则计算剩余到达时间,秒 */ String remainingTime; /** * 出发地址经度(百度坐标) */ String driverLng; /** * 出发地址纬度(百度坐标) */ String driverLat; public String getOrderId() { return orderId; } public void setOrderId(String orderId) { this.orderId = orderId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public double getAddressLng() { return addressLng; } public void setAddressLng(double addressLng) { this.addressLng = addressLng; } public double getAddressLat() { return addressLat; } public void setAddressLat(double addressLat) { this.addressLat = addressLat; } public String getCreateTime() { return createTime; } public void setCreateTime(String createTime) { this.createTime = createTime; } public String getCancelTime() { return cancelTime; } public void setCancelTime(String cancelTime) { this.cancelTime = cancelTime; } public String getRequestTime() { return requestTime; } public void setRequestTime(String requestTime) { this.requestTime = requestTime; } public String getAssignTime() { return assignTime; } public void setAssignTime(String assignTime) { this.assignTime = assignTime; } public String getAcceptTime() { return acceptTime; } public void setAcceptTime(String acceptTime) { this.acceptTime = acceptTime; } public String getArriveTime() { return arriveTime; } public void setArriveTime(String arriveTime) { this.arriveTime = arriveTime; } public String getBeginTime() { return beginTime; } public void setBeginTime(String beginTime) { this.beginTime = beginTime; } public String getEndTime() { return endTime; } public void setEndTime(String endTime) { this.endTime = endTime; } public String getDistance() { return distance; } public void setDistance(String distance) { this.distance = distance; } public String getWaitTime() { return waitTime; } public void setWaitTime(String waitTime) { this.waitTime = waitTime; } public String getAmount() { return amount; } public void setAmount(String amount) { this.amount = amount; } public String getAmountCoupon() { return amountCoupon; } public void setAmountCoupon(String amountCoupon) { this.amountCoupon = amountCoupon; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } public String getDriverNo() { return driverNo; } public void setDriverNo(String driverNo) { this.driverNo = driverNo; } public String getDriverMobile() { return driverMobile; } public void setDriverMobile(String driverMobile) { this.driverMobile = driverMobile; } public String getDriverDistance() { return driverDistance; } public void setDriverDistance(String driverDistance) { this.driverDistance = driverDistance; } public String getRemainingTime() { return remainingTime; } public void setRemainingTime(String remainingTime) { this.remainingTime = remainingTime; } public String getDriverLng() { return driverLng; } public void setDriverLng(String driverLng) { this.driverLng = driverLng; } public String getDriverLat() { return driverLat; } public void setDriverLat(String driverLat) { this.driverLat = driverLat; } public void setOrderStatus(String orderStatus) { this.orderStatus = orderStatus; } public String getOrderStatus() { return orderStatus; } } }
package edu.iu.P532.recieverclass; import java.awt.Color; import java.awt.Graphics; import edu.iu.P532.recieverclass.GameConstants; public class Ball { protected int ballposX ; protected int ballposY ; private int ballRadius; protected int ballXdir = GameConstants.BALL_SPEED_XDIR; protected int ballYdir = GameConstants.BALL_SPEED_XDIR; //Constructor for the Ball public Ball(int ballInitialPositionX, int ballInitialPositionY, int ballRadius) { this.ballposX = ballInitialPositionX; this.ballposY = ballInitialPositionY; this.ballRadius = ballRadius; } public int getBallXdir() { return ballXdir; } public void setBallXdir(int ballXdir) { this.ballXdir = ballXdir; } public int getBallYdir() { return ballYdir; } public void setBallYdir(int ballYdir) { this.ballYdir = ballYdir; } public int getBallposX() { return ballposX; } public void setBallposX(int ballposX) { this.ballposX = ballposX; } public int getBallposY() { return ballposY; } public void setBallposY(int ballposY) { this.ballposY = ballposY; } //Draws the Ball public void draw(Graphics g){ g.setColor(Color.RED); g.fillOval(ballposX, ballposY, ballRadius, ballRadius); } }
package com.santos.android.evenlychallenge.API; import android.app.Application; import android.content.Context; import android.support.v4.app.FragmentManager; import android.text.TextUtils; import android.util.Log; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.ImageLoader; import com.android.volley.toolbox.JsonArrayRequest; import com.android.volley.toolbox.Volley; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.santos.android.evenlychallenge.Activity.ChallengeLauncherActivity; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; /** * Created by Abel Cruz dos Santos on 16.08.2017. */ public class ClientSingleton extends Application { private static final String TAG = "ClientSingleton"; private static final String REQUEST_HEADER = "https://api.foursquare.com/v2/venues/search?ll="; private static final String CLIENT_ID = "05XL1PRM0WJWFWKMZ2ZF44DGK5UHQB3JAPRP4SNWVATDOUL5"; private static final String CLIENT_SECRET = "OR5RBTJKHM0LGCIPOFWJ4GSABL3KWT3Y212R5O0KQTER2XTR"; private static final String VENUE_DETAILS_REQUEST = "https://api.foursquare.com/v2/venues/"; private static final double LATITUDE = 52.500342; private static final double LONGITUDE = 13.425170; private static final int LIMIT = 10; private static final int RADIUS = 800; //in meters -> max 10000 private static ClientSingleton sClientSingleton; private RequestQueue mRequestQueue; private ImageLoader mImageLoader; private Context mContext; private ClientSingleton(Context context){ mContext = context; mRequestQueue = getRequestQueue(); } private List<Venue> mVenueList = new ArrayList<>(); @Override public void onCreate(){ super.onCreate(); sClientSingleton = this; } public static synchronized ClientSingleton getInstance(Context context){ if(sClientSingleton == null){ sClientSingleton = new ClientSingleton(context); } return sClientSingleton; } public RequestQueue getRequestQueue() { if (mRequestQueue == null) { mRequestQueue = Volley.newRequestQueue(mContext.getApplicationContext()); } return mRequestQueue; } /*public ImageLoader getImageLoader(){ getRequestQueue(); if(mImageLoader == null){ mImageLoader = new ImageLoader(this.mRequestQueue, new LruBitmapCache()); } return this.mImageLoader; }*/ public <T> void addToRequestQueue(Request<T> req, String tag) { // set the default tag if tag is empty req.setTag(TextUtils.isEmpty(tag) ? TAG : tag); getRequestQueue().add(req); } public <T> void addToRequestQueue(Request<T> req) { req.setTag(TAG); getRequestQueue().add(req); } public List<Venue> getVenueList() { return mVenueList; } public void setVenueList(List<Venue> venueList) { mVenueList = venueList; } public String getRequestUrl(){ Date currentTime = Calendar.getInstance().getTime(); String date = new SimpleDateFormat("yyyy/MM/dd").format(currentTime); String result = date.replaceAll("/", ""); Log.d(TAG, date); return REQUEST_HEADER + LATITUDE + "," + LONGITUDE + "&client_id=" + CLIENT_ID + "&client_secret=" + CLIENT_SECRET + "&v=" + result + "&radius=500" + "&sortByDistance=1&limit=50"; // } public String getVenueDetails(String venueId){ Date currentTime = Calendar.getInstance().getTime(); String date = new SimpleDateFormat("yyyy/MM/dd").format(currentTime); String result = date.replaceAll("/", ""); return VENUE_DETAILS_REQUEST + venueId + "?client_id=" + CLIENT_ID + "&client_secret=" + CLIENT_SECRET + "&v=" + result; } }
package org.onehippo.forge.konakart.plugins.rating; import org.apache.wicket.markup.html.basic.Label; import org.hippoecm.frontend.model.JcrNodeModel; import org.hippoecm.frontend.plugin.IPluginContext; import org.hippoecm.frontend.plugin.config.IPluginConfig; import org.hippoecm.frontend.service.IEditor; import org.hippoecm.frontend.service.render.RenderPlugin; import org.onehippo.forge.konakart.common.KKCndConstants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.jcr.Node; import javax.jcr.NodeIterator; import javax.jcr.RepositoryException; import javax.jcr.query.Query; import javax.jcr.query.QueryManager; import javax.jcr.query.QueryResult; /** * Rating Plugin to display readonly fields for Votes and Average Rating */ public class RatingPlugin extends RenderPlugin { private static Logger log = LoggerFactory.getLogger(RatingPlugin.class); private static final Logger LOGGER = LoggerFactory.getLogger(RatingPlugin.class); private static final long serialVersionUID = 1L; public RatingPlugin(IPluginContext context, IPluginConfig config) { super(context, config); final JcrNodeModel nodeModel = (JcrNodeModel) getModel(); Node productNode = nodeModel.getNode(); double avgRating = 0; long reviewCount = 0; try { Node parent = productNode.getParent().getParent(); if (parent.isNodeType("mix:referenceable")) { String query = "select * from konakart:review where konakart:reviewproductlink = '" + parent.getIdentifier() + "'"; QueryManager queryManager = productNode.getSession().getWorkspace().getQueryManager(); Query reviewsQuery = queryManager.createQuery(query, Query.SQL); QueryResult queryResult = reviewsQuery.execute(); long totalRating = 0L; final NodeIterator iterator = queryResult.getNodes(); while (iterator.hasNext()) { final Node review = iterator.nextNode(); reviewCount++; if (review.hasProperty(KKCndConstants.REVIEW_RATING)) { totalRating += review.getProperty(KKCndConstants.REVIEW_RATING).getLong(); } } if (reviewCount != 0) { avgRating = (double) totalRating / (double) reviewCount; } IEditor.Mode mode = IEditor.Mode.fromString(config.getString("mode", "view")); if (mode == IEditor.Mode.EDIT) { productNode.setProperty(KKCndConstants.REVIEW_RATING, avgRating); productNode.setProperty(KKCndConstants.REVIEW_VOTES, reviewCount); } } } catch (RepositoryException e) { LOGGER.error("Error occurred whilie initializing rating plugin: " + e.getMessage(), e); } add(new Label("avgRating", String.valueOf(avgRating))); add(new Label("reviewCount", String.valueOf(reviewCount))); } }
package model.data.rewardData; import component.DAO; public class AccidentInvestigationData{ // Component private DAO dao; // Constructor public AccidentInvestigationData() {this.dao = new DAO("AccidentInvestigation", "accidentInvestigationID", new Object[] {null, "", "", "", 0});} // Getter & Setter public String getScenario() {return this.dao.getString("scenario");} public String getDamage() {return this.dao.getString("damage");} public String getTreatment() {return this.dao.getString("treatment");} public int getTreatmentCost() {return this.dao.getInt("treatmentCost");} public void setScenario(String scenario) {this.dao.update("scenario", scenario);} public void setDamage(String damage) {this.dao.update("damage", damage);} public void setTreatment(String treatment) {this.dao.update("treatment", treatment);} public void setTreatmentCost(int treatmentCost) {this.dao.update("treatmentCost", treatmentCost);} }
package MinMax; import static org.junit.Assert.*; import org.junit.After; import org.junit.Before; import org.junit.Test; public class MinMaxTestCajaNegra { private MinMax mima; @Before //se aplica antes de cada test (creacion minmax) public void setUp(){ MinMax mima = new MinMax(); } @After //se aplica despues de cada test(eliminacion minmax) public void tearDown(){ mima=null; } @Test public void DatosNulos() { int[] Datos=null; assertEquals(null,mima.minMax(Datos)); } @Test public void DatosPositivos() { int Datos[]={1,2,3,4}; assertEquals(1,mima.minMax(Datos)[0]); assertEquals(4, mima.minMax(Datos)[1]); } @Test public void DatosNegativos() { int Datos[]= {-1,-2,-3,-4}; assertEquals(-4, mima.minMax(Datos)[0]); assertEquals(-1, mima.minMax(Datos)[1]); } @Test public void DatosConCeros() { int Datos[]={0,0}; assertEquals(0, mima.minMax(Datos)[0]); assertEquals(0, mima.minMax(Datos)[1]); } @Test public void DatosConOpuestos() { int Datos[]={1,-1}; assertEquals(-1,mima.minMax(Datos)[0]); assertEquals(1,mima.minMax(Datos)[1]); } @Test public void DatosConNumerosIguales() { int Datos[]={3,3}; assertEquals(3, mima.minMax(Datos)[0]); assertEquals(3, mima.minMax(Datos)[1]); } @Test public void DatosRepetidos() { int Datos[]={1,1,2,2,3,3}; assertEquals(1,mima.minMax(Datos)[0]); assertEquals(3,mima.minMax(Datos)[1]); } @Test public void DatosConUnSoloNumero() { int Datos[]={2}; assertEquals(2, mima.minMax(Datos)[0]); assertEquals(2, mima.minMax(Datos)[1]); } }
package com.justcode.hxl.viewutil.recycleview_util.layoutmanager.chipslayoutmanager.gravity; import com.justcode.hxl.viewutil.recycleview_util.layoutmanager.chipslayoutmanager.SpanLayoutChildGravity; public interface IGravityModifiersFactory { IGravityModifier getGravityModifier(@SpanLayoutChildGravity int gravity); }
/* * 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 domain; import java.sql.PreparedStatement; import java.util.Objects; /** * * @author Mihailo */ public class Production implements GenericEntity{ private ProductionCompany productionCompany; private Movie movie; public Production() { } public Production(ProductionCompany productionCompany, Movie movie) { this.productionCompany = productionCompany; this.movie = movie; } public ProductionCompany getProductionCompany() { return productionCompany; } public void setProductionCompany(ProductionCompany productionCompany) { this.productionCompany = productionCompany; } public Movie getMovie() { return movie; } public void setMovie(Movie movie) { this.movie = movie; } @Override public int hashCode() { int hash = 7; hash = 29 * hash + Objects.hashCode(this.productionCompany); hash = 29 * hash + Objects.hashCode(this.movie); return hash; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Production other = (Production) obj; if (!Objects.equals(this.productionCompany, other.productionCompany)) { return false; } if (!Objects.equals(this.movie, other.movie)) { return false; } return true; } @Override public String toString() { return "Production{" + "productionCompany=" + productionCompany + ", movie=" + movie + '}'; } @Override public String getTableName() { return "production"; } @Override public String getColumnNamesForInsert() { return "productioncompanyID, movieID"; } @Override public void getInsertValues(PreparedStatement statement) throws Exception{ statement.setLong(1, productionCompany.getProductionCompanyID()); statement.setLong(2, movie.getMovieID()); } @Override public void setId(Long id) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public int getColumnCount() { return 2; } @Override public String getColumnNamesForUpdate() { return ""; } @Override public String getConditionForUpdate() { return ""; } @Override public String getConditionForDelete() { return "movieID = " + movie.getMovieID(); } @Override public String getColumnNamesForSelect() { return "pc.name as pcname, pc.pcID"; } @Override public String getTableForSelect() { return "movie m JOIN production p ON (m.movieID = p.movieID) " + "JOIN productioncompany pc ON (pc.pcID = p.productioncompanyID)"; } @Override public String getConditionForSelect() { return "p.movieID = " + movie.getMovieID(); } @Override public String getConditionForSelectSpecific() { return ""; } @Override public String getAdditionalQueries() { return ""; } }
package BinarySearchTree; /*Objective is to get the smallest value. * Given tree: 20 30 40 50 60 70 80 Smallest Element is 20 * */ public class BinarySearchTreeSmallestElement { static Node root; class Node { int key; Node left, right; Node(int data) { key = data; left = right = null; } } BinarySearchTreeSmallestElement() { root= null; } void InsertNode(int data) { root = InsertNewNode(root, data); } Node InsertNewNode(Node root, int data) { if(root==null) { root = new Node(data); return root; } if(data < root.key) root.left = InsertNewNode(root.left, data); else if(data > root.key) root.right = InsertNewNode(root.right, data); return root; } void showTree() { printTree(root); } void printTree(Node root) { if(root!=null) { printTree(root.left); System.out.print(root.key+" "); printTree(root.right); } } int smallestElement() { int value; value = smallest(root); return value; } int smallest(Node root) { Node current = root; while(current.left != null) { current = current.left; } return current.key; } public static void main(String args[]) { BinarySearchTreeSmallestElement binarySearchTreeSmallestElement = new BinarySearchTreeSmallestElement(); binarySearchTreeSmallestElement.InsertNode(50); binarySearchTreeSmallestElement.InsertNode(30); binarySearchTreeSmallestElement.InsertNode(20); binarySearchTreeSmallestElement.InsertNode(40); binarySearchTreeSmallestElement.InsertNode(70); binarySearchTreeSmallestElement.InsertNode(60); binarySearchTreeSmallestElement.InsertNode(80); System.out.println("Given tree:"); binarySearchTreeSmallestElement.showTree(); System.out.println(""); int element = binarySearchTreeSmallestElement.smallestElement(); System.out.println("Smallest Element is "+ element); } }
package com.gaoshin.onsalelocal.osl.resource; import java.util.List; import java.util.Map; import junit.framework.Assert; import org.junit.Test; import com.gaoshin.onsalelocal.osl.entity.Account; import com.gaoshin.onsalelocal.osl.entity.User; import com.gaoshin.onsalelocal.osl.facebook.FacebookMe; import com.gaoshin.onsalelocal.osl.service.UserService; import com.gaoshin.onsalelocal.osl.service.impl.UserServiceImpl; import common.util.JacksonUtil; import common.util.web.SpringResourceTester; public class FacebookLoginTest extends SpringResourceTester { @Test public void test() throws Exception { UserService proxy = getSpringBean(UserService.class); UserServiceImpl userService = getTargetObject(proxy, UserServiceImpl.class); userService.setFacebookMe(new FacebookMe() { @Override public Map<String, String> me(String token) { if("kevin".equalsIgnoreCase(token)) { String data = "{\"data\":[{\"uid\":628729601,\"name\":\"Kevin Zhang\",\"username\":\"kevin.yj.zhang\",\"email\":null,\"first_name\":\"Kevin\",\"last_name\":\"Zhang\",\"middle_name\":\"\",\"hometown_location\":null,\"current_location\":{\"city\":\"Mountain View\",\"state\":\"California\",\"country\":\"United States\",\"zip\":\"\",\"id\":108212625870265,\"name\":\"Mountain View, California\"},\"pic_small\":\"https:\\/\\/fbcdn-profile-a.akamaihd.net\\/hprofile-ak-ash4\\/203197_628729601_1811472515_t.jpg\",\"pic_big\":\"https:\\/\\/fbcdn-profile-a.akamaihd.net\\/hprofile-ak-ash4\\/203197_628729601_1811472515_n.jpg\",\"pic_square\":\"https:\\/\\/fbcdn-profile-a.akamaihd.net\\/hprofile-ak-ash4\\/203197_628729601_1811472515_q.jpg\",\"pic\":\"https:\\/\\/fbcdn-profile-a.akamaihd.net\\/hprofile-ak-ash4\\/203197_628729601_1811472515_s.jpg\"}]}"; try { Map object = JacksonUtil.json2Object(data, JacksonUtil.getTypeRef()); List list = (List) object.get("data"); return (Map<String, String>) list.get(0); } catch (Exception e) { throw new RuntimeException(e); } } return null; } }); Account account = new Account(); String token = "kevin"; account.setToken(token ); User registered = getBuilder("/ws/user/facebook-login").post(User.class, account); Assert.assertEquals("Kevin", registered.getFirstName()); Assert.assertEquals("Zhang", registered.getLastName()); User me = getBuilder("/ws/user/me").get(User.class); Assert.assertEquals("Kevin", me.getFirstName()); Assert.assertEquals("Zhang", me.getLastName()); getBuilder("/ws/user/logout").post(" "); User u2 = getBuilder("/ws/user/facebook-login").post(User.class, account); Assert.assertEquals(registered.getId(), u2.getId()); } }
package com.product.controller; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.product.service.ProductService; import com.product.vo.ProductVo; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.*; import java.io.BufferedReader; import java.io.IOException; import java.io.PrintWriter; import java.sql.Timestamp; import java.util.HashMap; //@WebServlet(name = "ProductServlet",urlPatterns = {"/list"}) public class ProductServlet extends HttpServlet { private static final long serialVersionUID = 1L; // @Override protected void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { doGet(req, res); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException { req.setCharacterEncoding("UTF-8"); res.setContentType("text/plain; charset=UTF-8"); /* 接收json */ BufferedReader reader = req.getReader(); StringBuilder sb = new StringBuilder();// 接收使用者端傳來的JSON字串(body體裡的資料) String line; while ((line = reader.readLine()) != null){ sb = sb.append(line); } reader.close(); ProductVo vo = JSON.parseObject(String.valueOf(sb), ProductVo.class); String name = vo.getName(); // 取得請求參數 Integer price = vo.getPrice(); // 取得請求參數 Timestamp date = vo.getCreat_date(); // 取得請求參數 String imgPath = vo.getImg_path(); // 取得請求參數 String description = vo.getDescription(); // 取得請求參數 System.out.println("date=> " + date + "name=> " + name + "price=> " + price); // Integer price = null; ProductService service = new ProductService(); // 封裝錯誤訊息 HashMap<String, String> errorMsgs = new HashMap(); // PrintWriter out = res.getWriter(); // String name = req.getParameter("name"); // 取得請求參數 // String priceStr = req.getParameter("price"); // 取得請求參數 // Integer price = null; // Integer price = Integer.parseInt(req.getParameter("price")); // 取得請求參數 if(price == null) { errorMsgs.put("price", "產品售價不應為空"); } try { if(price < 0) { errorMsgs.put("price", "產品售價不得小於0"); } } catch (NumberFormatException e) { errorMsgs.put("price", "產品售價只能為數字"); } // String date = req.getParameter("date"); // 取得請求參數 // Map map1 = req.getParameterMap(); // System.out.println(map); // name // String regCh = "/^[\u4e00-\u9fa5]*$/g"; if(name == null || name.trim().isEmpty()){ errorMsgs.put("name", "產品名稱不應為空"); } else if (name.length() < 2){ errorMsgs.put("name", "產品名稱必須大於2個字"); } //description if(description == null || description.trim().isEmpty()){ errorMsgs.put("description", "產品描述不應為空"); } /* 先拿掉 date // date String dateReg = "([0-9]{4})[/]{1}([0-9]{1,2})[/]{1}([0-9]{1,2})$"; String[] valArr = date.split("/"); if(date.trim().isEmpty()){ errorMsgs.put("date", "日期不可空白"); }else if (!date.matches(dateReg)) { errorMsgs.put("date", "日期格式錯誤"); }else if (Integer.parseInt(valArr[1]) < 1 || Integer.parseInt(valArr[1]) > 12) { errorMsgs.put("date", "月份區間錯誤"); } else if (Integer.parseInt(valArr[2]) < 1 || Integer.parseInt(valArr[2]) > 31) { errorMsgs.put("date", "日期區間錯誤"); } */ JSONObject resJsonObject = new JSONObject(); HashMap<String, Object> data = new HashMap(); // 封裝到 Map 裡 data.put("name", name); data.put("price", price); data.put("date", date); data.put("description", description); // req.setAttribute("data", data); // 設定請求屬性 // req.setAttribute("price", price); // 設定請求屬性 // req.setAttribute("date", date); // 設定請求屬性 System.out.println(errorMsgs.size()); if (errorMsgs.size() > 0){ // req.setAttribute("errorMsgs", errorMsgs); // req.setAttribute("data", data); resJsonObject.put("code", "fail"); resJsonObject.put("data", data); resJsonObject.put("msg", errorMsgs); System.out.println("first"); // req.getRequestDispatcher("index.jsp").forward(req, res); return; } resJsonObject.put("code", "success"); resJsonObject.put("data", data); resJsonObject.put("msg", "商品新增成功"); /* * 返回json */ PrintWriter out = res.getWriter(); out.write(String.valueOf(resJsonObject)); // 轉字串輸出 out.close(); // ProductVo vo = new ProductVo(); // vo.setName(name); // vo.setPrice(price); // vo.setCreat_date(date); // 驗證過了就呼叫 service 層,導向產品列表頁 service.addProduct(vo); System.out.println("last"); // req.getRequestDispatcher("list.jsp").forward(req, res); } }
package inheritance2; public class DatabaseLogger extends Logger { public void MussBeDefined (){ System.out.println(" this metod muss be defined. Now we are in Databaselogger"); } @Override public void log () { System.out.println("Veritabanina Loglandi"); } }
package demo01.logger.impl; import demo01.logger.AbstractLogger; /** * @Description: * @Author: lay * @Date: Created in 19:59 2018/12/7 * @Modified By:IntelliJ IDEA */ public class ConsoleLogger extends AbstractLogger { public ConsoleLogger(int level) { this.level=level; } @Override protected void write(String message) { System.out.println("Standard Console::Logger: " + message); } }
package cn.kitho.core.utilService.weather.entity; import java.util.List; /** * Created by lingkitho on 2017/2/16. */ public class Weather { private List<Result> results; public List<Result> getResults() { return results; } public void setResults(List<Result> results) { this.results = results; } }
package com.zzp.nacos.service; /** * @Description commonService接口 * @Author Garyzeng * @since 2020.12.12 **/ public interface ICommonService { void asyncTest(); }
package com.diego.menuanddatastoragedemo; import android.content.Context; import android.content.DialogInterface; import android.content.SharedPreferences; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { TextView language; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); language = (TextView) findViewById(R.id.language); SharedPreferences sharedPreferences = MainActivity.this.getSharedPreferences("com.diego.menuanddatastoragedemo", Context.MODE_PRIVATE); String chosenLanguage = sharedPreferences.getString("language",""); if(chosenLanguage.equals("")) { new AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle("Which language do you want to use?") .setPositiveButton("English", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Toast.makeText(MainActivity.this, "English selected!", Toast.LENGTH_SHORT).show(); SharedPreferences sharedPreferences = MainActivity.this.getSharedPreferences("com.diego.menuanddatastoragedemo", Context.MODE_PRIVATE); sharedPreferences.edit().putString("language", "English").apply(); language.setText(sharedPreferences.getString("language", "")); } }) .setNegativeButton("Spanish", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Toast.makeText(MainActivity.this, "Spanish selected!", Toast.LENGTH_SHORT).show(); SharedPreferences sharedPreferences = MainActivity.this.getSharedPreferences("com.diego.menuanddatastoragedemo", Context.MODE_PRIVATE); sharedPreferences.edit().putString("language", "Spanish").apply(); language.setText(sharedPreferences.getString("language", "")); } }) .show(); } else { language.setText(sharedPreferences.getString("language", "")); } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater menuInflater = getMenuInflater(); menuInflater.inflate(R.menu.menu, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { super.onOptionsItemSelected(item); SharedPreferences sharedPreferences = MainActivity.this.getSharedPreferences("com.diego.menuanddatastoragedemo", Context.MODE_PRIVATE); switch (item.getItemId()){ case R.id.english: Toast.makeText(MainActivity.this, "English selected!", Toast.LENGTH_SHORT).show(); sharedPreferences.edit().putString("language", "English").apply(); language.setText(sharedPreferences.getString("language","")); return true; case R.id.spanish: Toast.makeText(MainActivity.this, "Spanish selected!", Toast.LENGTH_SHORT).show(); sharedPreferences.edit().putString("language", "Spanish").apply(); language.setText(sharedPreferences.getString("language","")); return true; default: return true; } } }
/* * Copyright (c) 2011, Paul Merlin. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.codeartisans.mojo.thirdparties; class ThirdPartyId { private final String classifier; private final String type; public ThirdPartyId( String classifier, String type ) { this.classifier = classifier; this.type = type; } public String getClassifier() { return classifier; } public String getType() { return type; } @Override public String toString() { return "{ classifier=" + classifier + " type=" + type + " }"; } @Override public boolean equals( Object obj ) { if ( obj == null ) { return false; } if ( getClass() != obj.getClass() ) { return false; } final ThirdPartyId other = ( ThirdPartyId ) obj; if ( ( this.classifier == null ) ? ( other.classifier != null ) : !this.classifier.equals( other.classifier ) ) { return false; } if ( ( this.type == null ) ? ( other.type != null ) : !this.type.equals( other.type ) ) { return false; } return true; } @Override public int hashCode() { int hash = 5; hash = 79 * hash + ( this.classifier != null ? this.classifier.hashCode() : 0 ); hash = 79 * hash + ( this.type != null ? this.type.hashCode() : 0 ); return hash; } }
package Concreate; import Abstract.BaseCampaignManager; import Adapters.SellerServiceAdapters; import Entities.Customer; import Entities.Games; public class CampainingManager extends BaseCampaignManager{ SellerServiceAdapters sellerServiceAdapters; public CampainingManager(SellerServiceAdapters sellerServiceAdapters) { this.sellerServiceAdapters = sellerServiceAdapters; } @Override public void campaignAdd(Games games, Customer customer) { super.campaignAdd(games, customer); } @Override public void campaignUpdate(Games games, Customer customer) { games.setPrice((int)this.sellerServiceAdapters.discountedPrice(games)); super.campaignUpdate(games, customer); } @Override public void campaignDelete(Games games, Customer customer) { super.campaignDelete(games, customer); } }
package com.lenovohit.ssm.treat.manager.impl; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import com.lenovohit.ssm.treat.dao.HisRestDao; import com.lenovohit.ssm.treat.manager.HisInpatientManager; import com.lenovohit.ssm.treat.model.Inpatient; import com.lenovohit.ssm.treat.model.InpatientBill; import com.lenovohit.ssm.treat.transfer.dao.RestListResponse; import com.lenovohit.ssm.treat.transfer.dao.RestRequest; import com.lenovohit.ssm.treat.transfer.manager.HisListResponse; public class HisInpatientManagerImpl implements HisInpatientManager { @Autowired private HisRestDao hisRestDao; // /** // * 住院患者信息查询(INP000004) // * 根据身份证号/住院号/住院流水号/状态查询住院患者信息 // * @param patient // * @return // */ // public HisEntityResponse getBaseInfo(Inpatient param){ // // Map<String, Object> reqMap = new HashMap<String,Object>(); // //入参字段映射 // reqMap.put("IdenNo", param.getIdenNo()); // reqMap.put("patientno", param.getPatientNo()); // reqMap.put("inpatientno", param.getInpatientno()); // reqMap.put("Status", param.getStatus()); // // HisEntityResponse response = hisRestDao.postForEntity("INP000004", reqMap); // Map<String, Object> resMap = response.getEntity(); // // if(null != resMap) { // //出参字段映射 // Inpatient inpatient = new Inpatient(); // inpatient.setInpatientno(object2String(resMap.get("inpatientno")));//TODO 病人编号 // inpatient.setPatientNo(object2String(resMap.get("patientno"))); // inpatient.setCardNo(object2String(resMap.get("cardno"))); // inpatient.setName(object2String(resMap.get("Name"))); // inpatient.setInDate(object2String(resMap.get("indate"))); // inpatient.setOutDate(object2String(resMap.get("outdate"))); // inpatient.setStatus(object2String(resMap.get("status"))); // inpatient.setSex(object2String(resMap.get("sex"))); // inpatient.setBedNo(object2String(resMap.get("bedno"))); // inpatient.setIdenNo(object2String(resMap.get("idenno"))); // inpatient.setMobile(object2String(resMap.get("mobile"))); // inpatient.setBirthday(object2String(resMap.get("birthday"))); // inpatient.setDeptNo(object2String(resMap.get("deptno"))); // inpatient.setDeptName(object2String(resMap.get("deptname"))); // inpatient.setInDiagnoseNo(object2String(resMap.get("indiagnoseno"))); // inpatient.setInDiagnose(object2String(resMap.get("indiagnose"))); // inpatient.setNurId(object2String(resMap.get("nurid"))); // inpatient.setNurName(object2String(resMap.get("nurname"))); // inpatient.setSelfBalance(object2String(resMap.get("selfbalance"))); // inpatient.setDrId(object2String(resMap.get("drid"))); // inpatient.setDrName(object2String(resMap.get("drname"))); // // response.setHisEntity(inpatient); // } // // return response; // } /** * 获取住院病人信息(INP0000041) * 根据住院唯一标识(住院ID),获取病人基本信息 * @param patient * @return */ public HisListResponse<Inpatient> getInpatientByInpatientId(Inpatient param){ Map<String, Object> reqMap = new HashMap<String,Object>(); //入参字段映射 reqMap.put("InpatientId", param.getInpatientId()); RestListResponse response = hisRestDao.postForList("INP0000041", RestRequest.SEND_TYPE_LOCATION, reqMap); HisListResponse<Inpatient> result = new HisListResponse<Inpatient>(response); List<Map<String, Object>> resMapList = response.getList(); List<Inpatient> resList = new ArrayList<Inpatient>(); Inpatient inpatient = null; if(null != resMapList) { for(Map<String, Object> resMap : resMapList){ //出参字段映射 inpatient = new Inpatient(); inpatient.setMedicalRecordId(object2String(resMap.get("MEDICALRECORDID"))); inpatient.setInpatientId(object2String(resMap.get("INPATIENTID"))); inpatient.setInpatientNo(object2String(resMap.get("InpatientNo"))); inpatient.setPatientNo(object2String(resMap.get("PATIENTNO"))); inpatient.setPatientName(object2String(resMap.get("PATIENTNAME"))); inpatient.setDeptId(object2String(resMap.get("DEPTID"))); inpatient.setDeptName(object2String(resMap.get("DEPTNAME"))); inpatient.setWardId(object2String(resMap.get("WARDID"))); inpatient.setWardName(object2String(resMap.get("WARDNAME"))); inpatient.setBedNo(object2String(resMap.get("BEDNO"))); inpatient.setHospitalArea(object2String(resMap.get("HOSPITALAREA"))); inpatient.setAdmission(object2String(resMap.get("ADMISSION"))); inpatient.setNursingLevel(object2String(resMap.get("NURSINGLEVEL"))); inpatient.setPayment(object2String(resMap.get("PAYMENT"))); inpatient.setInDate(object2String(resMap.get("ADMISSIONTIME"))); inpatient.setOutDate(object2String(resMap.get("DISCHARGEDDATE"))); inpatient.setDrId(object2String(resMap.get("PHYSICIANID"))); inpatient.setDrName(object2String(resMap.get("PHYSICIANNAME"))); inpatient.setNurId(object2String(resMap.get("NURSEID"))); inpatient.setNurName(object2String(resMap.get("NURSE1"))); inpatient.setInDiagnose(object2String(resMap.get("INDIAGNOSE"))); inpatient.setStatus(object2String(resMap.get("STATUSFLAG"))); resList.add(inpatient); } result.setList(resList); } return result; } /** * 获取住院病人信息(INP0000042) * 根据病人编号,获取住院病人基本信息 * @param patient * @return */ public HisListResponse<Inpatient> getInpatientByPatientNo(Inpatient param){ Map<String, Object> reqMap = new HashMap<String,Object>(); //入参字段映射 reqMap.put("PatientNo", param.getPatientNo()); RestListResponse response = hisRestDao.postForList("INP0000042", RestRequest.SEND_TYPE_LOCATION, reqMap); HisListResponse<Inpatient> result = new HisListResponse<Inpatient>(response); List<Map<String, Object>> resMapList = response.getList(); List<Inpatient> resList = new ArrayList<Inpatient>(); Inpatient inpatient = null; if(null != resMapList) { for(Map<String, Object> resMap : resMapList){ if(null != resMap.get("DISCHARGEDDATE") && !"".equals(resMap.get("DISCHARGEDDATE")) ){//只获取在院病人 continue; } //出参字段映射 inpatient = new Inpatient(); inpatient.setMedicalRecordId(object2String(resMap.get("MEDICALRECORDID"))); inpatient.setInpatientId(object2String(resMap.get("INPATIENTID"))); inpatient.setInpatientNo(object2String(resMap.get("INPATIENTNO"))); inpatient.setPatientNo(object2String(resMap.get("PATIENTNO"))); inpatient.setPatientName(object2String(resMap.get("PATIENTNAME"))); inpatient.setDeptId(object2String(resMap.get("DEPTID"))); inpatient.setDeptName(object2String(resMap.get("DEPTNAME"))); inpatient.setWardId(object2String(resMap.get("WARDID"))); inpatient.setWardName(object2String(resMap.get("WARDNAME"))); inpatient.setBedNo(object2String(resMap.get("BEDNO"))); inpatient.setHospitalArea(object2String(resMap.get("HOSPITALAREA"))); inpatient.setAdmission(object2String(resMap.get("ADMISSION"))); inpatient.setNursingLevel(object2String(resMap.get("NURSINGLEVEL"))); inpatient.setPayment(object2String(resMap.get("PAYMENT"))); inpatient.setInDate(object2String(resMap.get("ADMISSIONTIME"))); inpatient.setOutDate(object2String(resMap.get("DISCHARGEDDATE"))); inpatient.setDrId(object2String(resMap.get("PHYSICIANID"))); inpatient.setDrName(object2String(resMap.get("PHYSICIANNAME"))); inpatient.setNurId(object2String(resMap.get("NURSEID"))); inpatient.setNurName(object2String(resMap.get("NURSE1"))); inpatient.setInDiagnose(object2String(resMap.get("INDIAGNOSE"))); inpatient.setStatus(object2String(resMap.get("STATUSFLAG"))); resList.add(inpatient); } result.setList(resList); } return result; } /** * 3.20 HIS住院费用查询(INP0000161) * @param baseInfo * @param date * @return */ public HisListResponse<InpatientBill> getInpatientBill(Inpatient param){ Map<String, Object> reqMap = new HashMap<String, Object>(); //入参字段映射 reqMap.put("InpatientId", param.getInpatientId()); reqMap.put("BeginDate", param.getBeginDate()); //YYYY-MM-DD reqMap.put("EndDate", param.getEndDate());//YYYY-MM-DD // and jysj between to_date(:BeginDate,'yyyy-mm-dd hh24:mi:ss') and to_date(:EndDate,'yyyy-mm-dd hh24:mi:ss') RestListResponse response = hisRestDao.postForList("INP0000161", RestRequest.SEND_TYPE_LOCATION, reqMap); HisListResponse<InpatientBill> result = new HisListResponse<InpatientBill>(response); List<Map<String, Object>> resMaplist = response.getList(); List<InpatientBill> resList = new ArrayList<InpatientBill>(); InpatientBill inpatientBill = null; if(null != resMaplist){ for(Map<String, Object> resMap : resMaplist){ inpatientBill = new InpatientBill(); inpatientBill.setRecipeNo(object2String(resMap.get("RECIPENO"))); inpatientBill.setIndeptId(object2String(resMap.get("INDEPTID"))); inpatientBill.setIndeptName(object2String(resMap.get("IndeptName"))); inpatientBill.setDoctorId(object2String(resMap.get("DOCTORID"))); inpatientBill.setDoctorName(object2String(resMap.get("DOCTORNAME"))); inpatientBill.setItemId(object2String(resMap.get("ITEMID"))); inpatientBill.setItemName(object2String(resMap.get("ITEMNAME"))); inpatientBill.setFeeType(object2String(resMap.get("FEETYPE"))); inpatientBill.setDose(object2String(resMap.get("DOSE"))); inpatientBill.setFrequency(object2String(resMap.get("FREQUENCY"))); inpatientBill.setUsage(object2String(resMap.get("USAGE"))); inpatientBill.setDosage(object2String(resMap.get("DOSAGE"))); inpatientBill.setDosageSpec(object2String(resMap.get("DOSAGESPEC"))); inpatientBill.setItemPrice(object2String(resMap.get("ITEMPRICE"))); inpatientBill.setItemNum(object2String(resMap.get("ITEMNUM"))); inpatientBill.setItemSepc(object2String(resMap.get("ITEMSEPC"))); inpatientBill.setPaymentStatus(object2String(resMap.get("PAYMENTSTATUS"))); inpatientBill.setExecStatus(object2String(resMap.get("EXECSTATUS"))); inpatientBill.setPaymentTime(object2String(resMap.get("PAYMENTTIME"))); resList.add(inpatientBill); } } result.setList(resList); return result; } private String object2String(Object obj){ return obj==null ? "":obj.toString(); } }
package PageObjects; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import java.util.List; public class WebTablePrinting { public WebDriver driver; By rows = By.xpath("//table[@id='customers']/tbody/tr"); By coloumnHeader = By.xpath("//table[@id='customers']/tbody/tr/th"); public WebTablePrinting(WebDriver driver) { this.driver = driver; } public int rows() { return driver.findElements(rows).size(); } public int colomn() { return driver.findElements(coloumnHeader).size(); } public List<WebElement> ColomnHeader() { return driver.findElements(coloumnHeader); } public void TableData() { for (int i = 2; i <= rows(); i++) { for (int j = 1; j <= colomn(); j++) { By tData = By.xpath("//table[@id='customers']/tbody/tr[" + i + "]/td[" + j + "]"); String values = driver.findElement(tData).getText(); System.out.format("%-35s", values); } System.out.println(""); } } }
package cn.tedu.reivew; //本类用于练习多态 public class TestDome { public static void main(String[] args) { //5.创建一个多态对象进行测试 //继承+重写 & 父类引用指向子类对象 & 编译看左边,运行看右边 Fruite f=new Fruite();//纯纯的父类对象 Fruite f1=new Apple(); Fruite f2=new Lemon(); f.clean(); f1.clean(); f2.clean(); System.out.println(f.name); System.out.println(f1.name);//水果 System.out.println(f2.name);//水果 /*不管是父类还是子类对象,都可以调用getFruit * 原因;利用多态,将子类类型的对象看作父类类型*/ getFruite(f); Apple a=new Apple(); getFruite(a); Lemon l=new Lemon(); getFruite(l); } public static void getFruite(Fruite f){ f.clean(); } } //1.创建父类水果类 class Fruite{ String name="水果"; public void clean() { System.out.println("父类的clean方法"); } } //2.创建子类苹果 class Apple extends Fruite{ String name="苹果"; @Override public void clean() { System.out.println("苹果类的clean方法"); } } //3.创建子类柠檬 class Lemon extends Fruite{ String name="柠檬"; @Override public void clean() { System.out.println("柠檬类的clean方法"); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.inbio.ara.persistence.format; import java.util.Calendar; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import org.inbio.ara.persistence.LogGenericEntity; /** * * @author pcorrales */ @Entity @Table(name = "element_format") public class ElementFormat extends LogGenericEntity { @Id @Basic(optional = false) @Column(name = "element_format_id") private Long elementFormatId; @Basic(optional = false) @Column(name = "element_format_keyword") private String elementFormatKeyword; public ElementFormat() { } public ElementFormat(Long elementFormatId) { this.elementFormatId = elementFormatId; } public ElementFormat(Long elementFormatId, String elementFormatKeyword, Calendar creationDate, String createdBy, Calendar lastModificationDate, String lastModificationBy) { this.elementFormatId = elementFormatId; this.elementFormatKeyword = elementFormatKeyword; this.setCreatedBy(createdBy); this.setCreationDate(creationDate); this.setLastModificationBy(lastModificationBy); this.setLastModificationDate(lastModificationDate); } public Long getElementFormatId() { return elementFormatId; } public void setElementFormatId(Long elementFormatId) { this.elementFormatId = elementFormatId; } public String getElementFormatKeyword() { return elementFormatKeyword; } public void setElementFormatKeyword(String elementFormatKeyword) { this.elementFormatKeyword = elementFormatKeyword; } @Override public int hashCode() { int hash = 0; hash += (elementFormatId != null ? elementFormatId.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 ElementFormat)) { return false; } ElementFormat other = (ElementFormat) object; if ((this.elementFormatId == null && other.elementFormatId != null) || (this.elementFormatId != null && !this.elementFormatId.equals(other.elementFormatId))) { return false; } return true; } @Override public String toString() { return "org.inbio.ara.persistence.format.ElementFormat[elementFormatId=" + elementFormatId + "]"; } }
package com.softeem.dao; import java.util.List; import com.softeem.bean.GoodsInfoBean; public interface IGoodsInfoDao { /** * 新增 * @param info * @return */ int addGoodsInfo(GoodsInfoBean info); /** * 批量或单一删除 * @param gIDs * @return */ int delGoodsByID(String[] gIDs); /** * 更新商品信息 * @param info * @return */ int updateGoodsInfo(GoodsInfoBean info); /** * 根据ID查询单一商品 * @param gID * @return */ GoodsInfoBean queryGoodsByID(String gID); /** * 查询所有商品 * @return */ List<GoodsInfoBean> queryAllGoods(); }
package ru.itmo.ctlab.sgmwcs.graph; public class Node extends Unit { public Node(Node that) { super(that); } public Node(int num) { super(num); } @Override public String toString() { return "N(" + String.valueOf(num) + ")"; } }
package com.pisen.ott.launcher.movie; import java.util.ArrayList; import java.util.List; import android.os.Bundle; import android.os.Handler; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import com.pisen.ott.launcher.R; import com.pisen.ott.launcher.widget.CommonScaleFocusView; import com.qiyi.tv.client.feature.common.PageType; /** * @Description 专区 * @author hegang * */ public class MycenterFragment extends BaseFragment implements OnClickListener { private String TAG = MycenterFragment.class.getSimpleName(); private List<View> ivMediaList; private CommonScaleFocusView focusView; public MycenterFragment(Handler handler) { super(handler); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ivMediaList = new ArrayList<View>(); View view = inflater.inflate(R.layout.layout_movie_mycenter, container, false); ivMediaList.add(view.findViewById(R.id.movie_mycenter_history)); ivMediaList.add(view.findViewById(R.id.movie_mycenter_favorite)); ivMediaList.add(view.findViewById(R.id.movie_mycenter_offline)); for (View v : ivMediaList) { v.setOnClickListener(this); } focusView = (CommonScaleFocusView) view.findViewById(R.id.focusScrollView); return view; } @Override public void onClick(View view) { int pageType = -1; switch (view.getId()) { case R.id.movie_mycenter_history: pageType = PageType.PAGE_HISTORY; break; case R.id.movie_mycenter_favorite: pageType = PageType.PAGE_FAVORITE; break; case R.id.movie_mycenter_offline: pageType = PageType.PAGE_OFFLINE; break; } if (pageType != -1) { mQiyiManager.getQiyiClient().open(pageType); } } @Override public String getLogTag() { return TAG; } @Override public View getDefaultFocusView() { return ivMediaList.get(0); } }
package in.anandm.oj.repository.impl; import java.io.Serializable; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import com.googlecode.genericdao.dao.jpa.GenericDAOImpl; import com.googlecode.genericdao.search.jpa.JPASearchProcessor; public class JPABaseRepository<T, ID extends Serializable> extends GenericDAOImpl<T, ID> { @Override public void setSearchProcessor(JPASearchProcessor searchProcessor) { super.setSearchProcessor(searchProcessor); } @PersistenceContext @Override public void setEntityManager(EntityManager entityManager) { super.setEntityManager(entityManager); } }
package gov.nih.mipav.model.structures; import java.util.*; // update VOI event /** * presents an event to regard a changed VOI. Carries with it the changed VOIBase (the changed curve associated with * this VOI, and should be <i>in</i> that <code>VOI</code>), should the object announcing this change need to include * that information. * * <p>Future versions may include other information concerning the changed field of the Volume of Interest, itself.</p> * * <p>$Logfile: /mipav/src/gov/nih/mipav/model/structures/UpdateVOIEvent.java $ $Revision: 1 $ $Date: 8/08/02 10:05a $ * </p> */ public class UpdateVOIEvent extends EventObject { //~ Static fields/initializers ------------------------------------------------------------------------------------- /** Use serialVersionUID for interoperability. */ private static final long serialVersionUID = 8233713497226707057L; //~ Instance fields ------------------------------------------------------------------------------------------------ /** DOCUMENT ME! */ private VOIBase curve; /** DOCUMENT ME! */ private Object source; /** DOCUMENT ME! */ private boolean usedCurve = false; /** DOCUMENT ME! */ private VOI voi; //~ Constructors --------------------------------------------------------------------------------------------------- /** * A basic updateVOIevent. No information about the VOI updated can be taken if event is created with this creator. * * @param src DOCUMENT ME! */ public UpdateVOIEvent(Object src) { this(src, null); } /** * Creates a new UpdateVOIEvent object. * * @param src DOCUMENT ME! * @param changedVOI DOCUMENT ME! */ public UpdateVOIEvent(Object src, VOI changedVOI) { this(src, changedVOI, null); } /** * Creates a new UpdateVOIEvent object. * * @param src DOCUMENT ME! * @param changedVOI DOCUMENT ME! * @param changedCurve DOCUMENT ME! */ public UpdateVOIEvent(Object src, VOI changedVOI, VOIBase changedCurve) { super(src); source = src; voi = changedVOI; curve = changedCurve; // curve only has meaning if we actually // set the curve to something non null usedCurve = (curve == null) ? false : true; } //~ Methods -------------------------------------------------------------------------------------------------------- /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public VOIBase getChangedCurveOfInterest() { if (!usedCurve) { return null; } return curve; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public VOI getChangedVolumeOfInterest() { return voi; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public Object getSource() { return source; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public String toString() { return voi.toString(); } }
package FourthTask; import Enums.Groups; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Exam implements Runnable { private Teacher teacher; private Student student; public static void main(String[] args) { Teacher teacher1 = new Teacher("Maths"); Teacher teacher2 = new Teacher("Informatics"); Student student1 = new Student("Samat", "Kadyrov", Groups.GROUP_5); Student student2 = new Student("Ruslan", "Korchenov", Groups.GROUP_5); Exam exam1 = new Exam(teacher1); exam1.setStudent(student1); Exam exam2 = new Exam(teacher1); exam2.setStudent(student2); Exam exam3 = new Exam(teacher2); exam3.setStudent(student1); Exam exam4 = new Exam(teacher2); exam4.setStudent(student2); ExecutorService executor = Executors.newFixedThreadPool(4); executor.submit(exam1); executor.submit(exam2); executor.submit(exam3); executor.submit(exam4); } public Exam(Teacher teacher) { this.teacher = teacher; } public void setStudent(Student student) { this.student = student; } public void run() { synchronized (student) { teacher.examine(student); } } }
package com.github.skjolber.mockito.soap; import static com.github.skjolber.mockito.soap.SoapServiceFault.createFault; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.net.URL; import java.util.Arrays; import java.util.List; import javax.xml.namespace.QName; import org.apache.cxf.binding.soap.SoapFault; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.github.skjolber.bank.example.v1.BankCustomerServicePortType; import com.github.skjolber.bank.example.v1.BankException; import com.github.skjolber.bank.example.v1.BankRequestHeader; import com.github.skjolber.bank.example.v1.CustomerException; import com.github.skjolber.bank.example.v1.GetAccountsRequest; import com.github.skjolber.bank.example.v1.GetAccountsResponse; import com.github.skjolber.mockito.soap.PortManager; import com.github.skjolber.mockito.soap.SoapEndpointRule; import com.github.skjolber.shop.example.v1.ShopCustomerServicePortType; /** * Test with port reservations (as a {@linkplain ClassRule}. */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations={"classpath:/spring/beans.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD) @ActiveProfiles("dev2") public class BankCustomerSoapEndpointClassRuleTest { @Rule public ExpectedException exception = ExpectedException.none(); @ClassRule public static SoapEndpointRule soap = SoapEndpointRule.newInstance("myPort"); /** * Endpoint address (full url), typically pointing to localhost for unit testing, remote host otherwise. * For reserved ports also with the port name: http://localhost:${myPort}/selfservice/bank */ @Value("${bankcustomer.service}") private String bankCustomerServiceAddress; @Value("${shopcustomer.service}") private String shopCustomerServiceAddress; /** * Mock object proxied by SOAP service */ private BankCustomerServicePortType bankServiceMock; private ShopCustomerServicePortType shopServiceMock; /** * Business code which calls the SOAP service via an autowired client */ @Autowired private BankCustomerService bankCustomerService; @Before public void setup() throws Exception { Assert.assertFalse(PortManager.isPortAvailable(soap.getPort("myPort"))); assertThat(new URL(bankCustomerServiceAddress).getPort(), is(soap.getPort("myPort"))); assertThat(soap.getPorts().get("myPort"), is(soap.getPort("myPort"))); bankServiceMock = soap.mock(BankCustomerServicePortType.class, bankCustomerServiceAddress, Arrays.asList("classpath:wsdl/BankCustomerService.xsd")); shopServiceMock = soap.mock(ShopCustomerServicePortType.class, shopCustomerServiceAddress); } @After public void teardown() { soap.clear(); } /** * Webservice call which results in regular response returned to the client. */ @Test public void processNormalSoapCall() throws Exception { // add mock response GetAccountsResponse mockResponse = new GetAccountsResponse(); List<String> accountList = mockResponse.getAccount(); accountList.add("1234"); accountList.add("5678"); when(bankServiceMock.getAccounts(any(GetAccountsRequest.class), any(BankRequestHeader.class))).thenReturn(mockResponse); String customerNumber = "123456789"; // must be all numbers, if not schema validation fails String secret = "abc"; // actually do something GetAccountsResponse accounts = bankCustomerService.getAccounts(customerNumber, secret); ArgumentCaptor<GetAccountsRequest> argument1 = ArgumentCaptor.forClass(GetAccountsRequest.class); ArgumentCaptor<BankRequestHeader> argument2 = ArgumentCaptor.forClass(BankRequestHeader.class); verify(bankServiceMock, times(1)).getAccounts(argument1.capture(), argument2.capture()); GetAccountsRequest request = argument1.getValue(); assertThat(request.getCustomerNumber(), is(customerNumber)); BankRequestHeader header = argument2.getValue(); assertThat(header.getSecret(), is(secret)); assertThat(accounts.getAccount(), is(accountList)); } /** * Webservice call which results in soap fault being returned to the client. */ @Test public void processSoapCallWithException1() throws Exception { // add mock response GetAccountsResponse mockResponse = new GetAccountsResponse(); List<String> accountList = mockResponse.getAccount(); accountList.add("1234"); accountList.add("5678"); String errorCode = "myErrorCode"; String errorMessage = "myErrorMessage"; BankException bankException = new BankException(); bankException.setCode(errorCode); bankException.setMessage(errorMessage); SoapFault fault = createFault(bankException); when(bankServiceMock.getAccounts(any(GetAccountsRequest.class), any(BankRequestHeader.class))).thenThrow(fault); String customerNumber = "123456789"; String secret = "abc"; exception.expect(Exception.class); // actually do something bankCustomerService.getAccounts(customerNumber, secret); } @Test public void processSoapCallWithException2() throws Exception { // add mock response GetAccountsResponse mockResponse = new GetAccountsResponse(); List<String> accountList = mockResponse.getAccount(); accountList.add("1234"); accountList.add("5678"); String status = "DEAD"; CustomerException customerException = new CustomerException(); customerException.setStatus(status); SoapFault fault = createFault(customerException, new QName("http://soap.spring.example.skjolberg.com/v1", "customerException")); when(bankServiceMock.getAccounts(any(GetAccountsRequest.class), any(BankRequestHeader.class))).thenThrow(fault); String customerNumber = "123456789"; String secret = "abc"; exception.expect(Exception.class); // actually do something bankCustomerService.getAccounts(customerNumber, secret); } @Test public void processValidationException() throws Exception { // add mock response GetAccountsResponse mockResponse = new GetAccountsResponse(); List<String> accountList = mockResponse.getAccount(); accountList.add("1234"); accountList.add("5678"); when(bankServiceMock.getAccounts(any(GetAccountsRequest.class), any(BankRequestHeader.class))).thenReturn(mockResponse); String customerNumber = "abcdef"; // must be all numbers, if not schema validation fails String secret = "abc"; exception.expect(Exception.class); // actually do something bankCustomerService.getAccounts(customerNumber, secret); } }
package com.example.myplaces; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import android.view.Gravity; import android.view.View; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; public class RegisterUsers extends AppCompatActivity { EditText emailEditText,passwordEditText,repeatPasswordEditText; ProgressBar loading; private FirebaseDatabase mDataBase; private DatabaseReference mRef; private FirebaseAuth mAuth; public void switchToSignIn (View view) { Intent intent = new Intent(getApplicationContext(), MainActivity.class); startActivity(intent); } public void registerWithEmailAndPass(final String email, String password) { loading.setVisibility(View.VISIBLE); mAuth=FirebaseAuth.getInstance(); mAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(RegisterUsers.this,new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { Toast.makeText(getApplicationContext(),"User successfully created\nVerification email sent.",Toast.LENGTH_SHORT).show(); mAuth.getCurrentUser().sendEmailVerification(); UserModel user = new UserModel(); user.setEmail(mAuth.getCurrentUser().getEmail()); user.setNumLocationsAdded(0); user.setMarkerPriority(0); mDataBase = FirebaseDatabase.getInstance(); mRef = mDataBase.getReference("Users"); mRef.child(mAuth.getCurrentUser().getUid()).setValue(user); mAuth.signOut(); loading.setVisibility(View.INVISIBLE); }else { if (isValidEmailAddress(email)) { if (passwordEditText.length()<6) { Toast myToast = Toast.makeText(getApplicationContext(),"Password must contains \nat least 6 characters.",Toast.LENGTH_SHORT); } else { Toast.makeText(getApplicationContext(), "User already registred with \n"+email, Toast.LENGTH_SHORT).show(); } }else { Toast.makeText(getApplicationContext(), "Email not valid.", Toast.LENGTH_SHORT).show(); } loading.setVisibility(View.INVISIBLE); } } }); } public boolean passwordMatch (String pass1,String pass2 ) { if (pass1.equals(pass2)) { return true; }else { return false; } } public boolean isValidEmailAddress(String email) { String ePattern = "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$"; java.util.regex.Pattern p = java.util.regex.Pattern.compile(ePattern); java.util.regex.Matcher m = p.matcher(email); return m.matches(); } public void creatNewUser (View view) { isEmpty(); if (isEmpty()) { Toast.makeText(getApplicationContext(),"Plase fill all fields",Toast.LENGTH_SHORT).show(); } else { if (passwordMatch(passwordEditText.getText().toString(),repeatPasswordEditText.getText().toString())) { registerWithEmailAndPass(emailEditText.getText().toString(),passwordEditText.getText().toString()); }else { Toast.makeText(getApplicationContext(),"Password doesn't match!",Toast.LENGTH_SHORT).show(); } } } public boolean isEmpty () { if (TextUtils.isEmpty(emailEditText.getText()) || TextUtils.isEmpty(passwordEditText.getText()) || TextUtils.isEmpty(repeatPasswordEditText.getText())) { return true; }else { return false; } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register_users); emailEditText = (EditText) findViewById(R.id.emailEditText2); passwordEditText = (EditText) findViewById(R.id.passwordEditText); repeatPasswordEditText = (EditText) findViewById(R.id.passwordRepeatText); loading = (ProgressBar)findViewById(R.id.loadingProgressBar); loading.getIndeterminateDrawable().setColorFilter(0xFFD95642, android.graphics.PorterDuff.Mode.MULTIPLY); loading.setVisibility(View.INVISIBLE); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package hdfcraft.minecraft; import java.util.HashMap; import org.jnbt.CompoundTag; import org.jnbt.StringTag; import org.jnbt.Tag; import static hdfcraft.minecraft.Constants.*; /** * * @author pepijn */ public class Entity extends AbstractNBTItem { public Entity(String id) { super(new CompoundTag("", new HashMap<String, Tag>())); if (id == null) { throw new NullPointerException(); } setString(TAG_ID, id); setShort(TAG_FIRE, (short) -20); setShort(TAG_AIR, (short) 300); setBoolean(TAG_ON_GROUND, true); setPos(new double[] {0, 0, 0}); setRot(new float[] {0, 0}); setVel(new double[] {0, 0, 0}); } public Entity(CompoundTag tag) { super(tag); } public final String getId() { return getString(TAG_ID); } public final double[] getPos() { double[] list = getDoubleList(TAG_POS); return (list != null) ? list : new double[3]; } public final void setPos(double[] pos) { if (pos.length != 3) { throw new IllegalArgumentException(); } setDoubleList(TAG_POS, pos); } public final float[] getRot() { float[] list = getFloatList(TAG_ROTATION); return (list != null) ? list : new float[2]; } public final void setRot(float[] rot) { if (rot.length != 2) { throw new IllegalArgumentException(); } setFloatList(TAG_ROTATION, rot); } public final double[] getVel() { double[] list = getDoubleList(TAG_MOTION); return (list != null) ? list : new double[3]; } public final void setVel(double[] vel) { if (vel.length != 3) { throw new IllegalArgumentException(); } setDoubleList(TAG_MOTION, vel); } public static Entity fromNBT(Tag entityTag) { CompoundTag tag = (CompoundTag) entityTag; String id = ((StringTag) tag.getTag(TAG_ID)).getValue(); if (id.equals(ID_PLAYER)) { return new Player(tag); } else if (id.equals(ID_VILLAGER)) { return new Villager(tag); } else if (id.equals(ID_PAINTING)) { return new Painting(tag); } else { return new Entity(tag); } } private static final long serialVersionUID = 1L; }
package com.neu.spring.pojo; import java.util.HashSet; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.PrimaryKeyJoinColumn; import javax.persistence.SecondaryTable; import javax.persistence.Table; import javax.persistence.Transient; @Entity @Table(name="trader") @PrimaryKeyJoinColumn(name="user_ID") public class Trader extends UserAccount { // @Id // @GeneratedValue // @Column(name="traderId", unique = true, nullable = false) // private long traderId; @Column(name = "creditScore") private String creditScore; @OneToMany(fetch=FetchType.EAGER,mappedBy="trader") private Set<TradeOrder> tradeOrders = new HashSet<TradeOrder>(); // @OneToMany(fetch=FetchType.LAZY,mappedBy="traderstock") // private Set<TraderStock> traderStocks = new HashSet<TraderStock>(); @ManyToMany(fetch=FetchType.EAGER,cascade = CascadeType.ALL) @JoinTable(name = "trader_stock", joinColumns = { @JoinColumn(name = "traderId") }, inverseJoinColumns = { @JoinColumn(name = "stockId") }) private Set<StockInfo> stockInfos = new HashSet<StockInfo>(); public Trader() { } // public long getTraderId() { // return traderId; // } // public void setTraderId(long traderId) { // this.traderId = traderId; // } public Set<TradeOrder> getTradeOrders() { return tradeOrders; } public Set<StockInfo> getStockInfos() { return stockInfos; } public void setStockInfos(Set<StockInfo> stockInfos) { this.stockInfos = stockInfos; } public void addStockInfo(StockInfo stockInfo) { getStockInfos().add(stockInfo); } public void setTradeOrders(Set<TradeOrder> tradeOrders) { this.tradeOrders = tradeOrders; } public void addTradeOrders(TradeOrder tradeOrder) { getTradeOrders().add(tradeOrder); } //public Set<TraderStock> getTraderStocks() { // return traderStocks; //} //public void setTraderStocks(Set<TraderStock> traderStocks) { // this.traderStocks = traderStocks; //} //public void addTraderStocks(TraderStock traderStock) { // getTraderStocks().add(traderStock); //} public String getCreditScore() { return creditScore; } public void setCreditScore(String creditScore) { this.creditScore = creditScore; } }
/** * Sencha GXT 3.0.1 - Sencha for GWT * Copyright(c) 2007-2012, Sencha, Inc. * licensing@sencha.com * * http://www.sencha.com/products/gxt/license/ */ package com.sencha.gxt.desktopapp.client.canvas; import com.google.gwt.user.client.ui.HasWidgets; import com.sencha.gxt.desktopapp.client.DesktopBus; import com.sencha.gxt.desktopapp.client.event.PropertyEvent; import com.sencha.gxt.desktopapp.client.event.SelectFileModelEvent; import com.sencha.gxt.desktopapp.client.persistence.FileModel; import com.sencha.gxt.desktopapp.client.persistence.FileModel.FileType; public class CanvasPresenterImpl implements CanvasPresenter { private DesktopBus desktopBus; private CanvasView canvasView; public CanvasPresenterImpl(DesktopBus desktopBus) { this.desktopBus = desktopBus; } public DesktopBus getDesktopBus() { return desktopBus; } @Override public void go(HasWidgets hasWidgets) { hasWidgets.add(getCanvasView().asWidget()); } @Override public boolean isEnableCreate() { getCanvasView(); return true; } @Override public boolean isEnableDelete() { return true; } @Override public boolean isEnableEditName() { return true; } @Override public boolean isEnableOpen() { return true; } @Override public void onCollapse() { } @Override public void onCreate(FileType fileType) { } @Override public void onDelete() { } @Override public void onEditFileNameComplete(boolean isSaved) { } @Override public void onEditName() { } @Override public void onExpand() { } @Override public void onOpen() { } @Override public void onSelect(FileModel fileModel) { getDesktopBus().fireSelectFileModelEvent( new SelectFileModelEvent(fileModel)); } private CanvasView getCanvasView() { if (canvasView == null) { canvasView = new CanvasViewImpl(this); } return canvasView; } @Override public void onNewEllipse() { // TODO Auto-generated method stub } @Override public void onNewLine() { canvasView.onNewLine(); } @Override public void onHelp() { // TODO Auto-generated method stub } @Override public void onZoomin() { canvasView.onZoomin(); } @Override public void onZoomout() { canvasView.onZoomout(); } @Override public void onNewPloygon() { } @Override public void onDragEnd(String str) { getDesktopBus().firePropertyEvent(new PropertyEvent(str)); } }
package com.example.demo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Required; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; @Component @Scope(value="singleton") public class Testdude { private int age; @Value("${value.from.file}") private String valueFromFile; private int height; @Autowired @Qualifier("lap1") private Laptop lappy; @Autowired private Person person; public Person getPerson() { return person; } public void setPerson(Person person) { this.person = person; } public Laptop getLappy() { return lappy; } public void setLappy(Laptop lappy) { this.lappy = lappy; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Testdude() { super(); System.out.println("gdamn"); } public int getHeight() { return height; } public void setHeight(int height) { this.height = height; } // @Required public void ohyeah() { System.out.println("yes bro it works!"); System.out.println(valueFromFile); // lappy.show(); person.printo(); } }
/* * 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 threads; import bourserealtimeserver.ClientConecte; import bourserealtimeserver.ClientConnecte; import classes.Action; import classes.Change; import java.net.Socket; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** * * @author ammach */ public class ChangeThread extends Thread{ ArrayList<Object> changes; String data; Socket socket; public ChangeThread(Socket s,String data) { this.socket=s; this.data=data; this.start(); } @Override public void run() { super.run(); while (true) { try { changes=new ArrayList<Object>(); JSONObject jSONObject = new JSONObject(data); JSONObject list = jSONObject.getJSONObject("list"); JSONArray resources = list.getJSONArray("resources"); for (int i = 0; i < 4; i++) { JSONObject item = (JSONObject) resources.getJSONObject(i); JSONObject resource = item.getJSONObject("resource"); JSONObject fields = resource.getJSONObject("fields"); String name = fields.getString("name"); String price = fields.getString("price"); String utctime = fields.getString("utctime"); Change change=new Change(name, price, utctime); changes.add(change); System.out.println("name: " + name + " price: " + price + " utctime: " + utctime); } System.out.println(""); System.out.println(""); ClientConecte clientConnecte=new ClientConecte(); clientConnecte.connexion(socket.getInetAddress().getHostAddress().toString(), 40000); clientConnecte.envoiObject(changes); // clientConnecte.fermer(); this.sleep(10000); } catch (InterruptedException ex) { Logger.getLogger(ChangeThread.class.getName()).log(Level.SEVERE, null, ex); } catch (JSONException ex) { Logger.getLogger(ChangeThread.class.getName()).log(Level.SEVERE, null, ex); } } } }
package com.hackerank.algorithm.warmup; public class Employee implements Comparable<Employee>{ public int getNo() { return no; } public void setNo(int no) { this.no = no; } public String getName() { return name; } public void setName(String name) { this.name = name; } int no; String name; public Employee(int n,String s){ this.no=n; this.name=s; } @Override public int compareTo(Employee arg0) { return this.name.toUpperCase().compareTo(arg0.name.toUpperCase()); } }
/** * project name:ach * file name:TldIdentifyCodeServiceImpl * package name:com.cdkj.system.service.impl * date:2017-08-25 14:04 * author:yw * Copyright (c) CD Technology Co.,Ltd. All rights reserved. */ package com.cdkj.manager.msg.service.impl; import com.cdkj.common.base.service.impl.BaseServiceImpl; import com.cdkj.constant.MsgTmplConstant; import com.cdkj.constant.SysDictConstants; import com.cdkj.manager.msg.dao.MsgIdentifyCodeMapper; import com.cdkj.manager.msg.dao.MsgTemplateMapper; import com.cdkj.manager.msg.service.api.MsgIdentifyCodeService; import com.cdkj.manager.msg.service.api.SmsService; import com.cdkj.manager.system.dao.SysDictMapper; import com.cdkj.model.msg.pojo.MsgIdentifyCode; import com.cdkj.model.msg.pojo.MsgTemplate; import com.cdkj.util.*; import org.springframework.stereotype.Service; import org.springframework.util.ObjectUtils; import javax.annotation.Resource; import java.util.List; import java.util.Map; /** * description: 用户验证码管理实现层 * date: 2017-08-25 14:04 * * @author yw * @version 1.0 * @since JDK 1.8 */ @Service public class MsgIdentifyCodeServiceImpl extends BaseServiceImpl<MsgIdentifyCode, String> implements MsgIdentifyCodeService { // 验证码默认有效20分钟 private static Integer VALID_TIME = 20; // 验证码默认长度6个字符 private static Integer VALID_LENGTH = 6; // 验证码默认类型为'0':表示仅获得数字随机数 private static Integer VALID_TYPE = 0; @Resource private MsgIdentifyCodeMapper msgIdentifyCodeMapper; @Resource private MsgTemplateMapper msgTemplateMapper; @Resource private SysDictMapper sysDictMapper; @Resource private SmsService smsService; /** * 发送验证码 * * @param mobile 手机号码 * @return */ @Override public Map<String, Object> send(String sysAccount, String mobile) { MsgIdentifyCode msgIdentifyCode = new MsgIdentifyCode(); msgIdentifyCode.setId(UUIDGenerator.randomUUID()); msgIdentifyCode.setMobile(mobile); msgIdentifyCode.setSysAccount(sysAccount); msgIdentifyCode.setCreateDt(DateUtil.getNow()); msgIdentifyCode.setUpdateDt(DateUtil.getNow()); //获取随机码 //默认6位长度 int length = VALID_LENGTH; //默认类型'0':表示仅获得数字随机数 int type = VALID_TYPE; //默认20分钟有效时间 Integer validTime = VALID_TIME; MsgIdentifyCode otherIdentifyCode = msgIdentifyCodeMapper.selectByMobile(sysAccount, mobile); if (!ObjectUtils.isEmpty(otherIdentifyCode)) { long timeDiff = DateUtil.getTimeDiff(DateUtil.getNow(), otherIdentifyCode.getCreateDt(), DateUtil.DIFF_UNIT_MIN); if (timeDiff > validTime) { //如果过期了,则变更为失效 otherIdentifyCode.setEnabled((short) 0); msgIdentifyCodeMapper.updateByPrimaryKeySelective(otherIdentifyCode); } } msgIdentifyCode.setIdentifyCode(RandomValidateCode.CreateRadom(length, type)); int executeInt = msgIdentifyCodeMapper.insertSelective(msgIdentifyCode); /*数据操作成功,给用户发送短信*/ if (executeInt > 0) { sendMsg(msgIdentifyCode, validTime); } return ResultUtil.getResult("发送成功!"); } /** * 验证验证码 * * @param mobile 手机号码 * @param code 验证码 * @return */ @Override public boolean checkIdentifyCode(String sysAccount, String mobile, String code) { List<MsgIdentifyCode> list = msgIdentifyCodeMapper.listByMobile(sysAccount, mobile); if (list.isEmpty()) { return false; } for (MsgIdentifyCode item : list) { long timeDiff = DateUtil.getTimeDiff(DateUtil.getNow(), item.getCreateDt(), DateUtil.DIFF_UNIT_MIN); if (timeDiff > VALID_TIME) { //如果过期了,直接变更为失效, 且继续循环下一个 item.setEnabled((short) 0); msgIdentifyCodeMapper.updateByPrimaryKeySelective(item); } else { // 找到符合有效期的, 且需要进行验证码校验 if (item.getIdentifyCode().equals(code)) { item.setEnabled((short) 0); msgIdentifyCodeMapper.updateByPrimaryKeySelective(item); return true; } } } return false; } /** * 调用api,给用户发送短信code * * @param identifyCode */ private void sendMsg(MsgIdentifyCode identifyCode, Integer validTime) { String code = identifyCode.getIdentifyCode(); String mobile = identifyCode.getMobile(); String content = getSmsContent(identifyCode.getSysAccount(), validTime, code); Map<String, String> rtn = smsService.send(identifyCode.getSysAccount(), mobile, content); //短信发送类型 - SMS微服务 /*如果发送失败,则标记数据库,变更为失效*/ if ("-1".equals(rtn.get("resultCode"))) { identifyCode.setEnabled((short) 0); msgIdentifyCodeMapper.updateByPrimaryKeySelective(identifyCode); } } /** * 生成短信内容 * * @param validTime 短信有效时间 * @param code 短信验证码 * @return */ private String getSmsContent(String sysAccount, Integer validTime, String code) { MsgTemplate tmpl = msgTemplateMapper.selectByTemplateCode(sysAccount, MsgTmplConstant.MSG_TMPL_REG_LOG_IDENTIFY_CODE); return String.format(tmpl.getTmplBody(), code, validTime) + sysDictMapper.selectByGroupCode(sysAccount, SysDictConstants.GROUP_CODE.MSG_TYPE, SysDictConstants.MSG_TYPE.SMS_SIGN); } }
package com.xcafe.bank.service; import com.xcafe.bank.entity.Account; import com.xcafe.bank.service.repository.AccountRepository; public class SimpleBank implements Bank { private AccountNumberGenerator accountNumberGenerator; private AccountRepository accountRepository; public SimpleBank(AccountNumberGenerator accountNumberGenerator, AccountRepository accountsRepository) { this.accountNumberGenerator = accountNumberGenerator; this.accountRepository = accountsRepository; } @Override public Account createAccount() { Account account = new Account(accountNumberGenerator.getNext()); return accountRepository.save(account); } @Override public void makeDeposit(long amount, String accountNumber) { Account account = accountRepository.getByNumber(accountNumber); account.setBalance(account.getBalance() + amount); accountRepository.update(account); } @Override public Account getAccountDetails(String accountNumber) { return accountRepository.getByNumber(accountNumber); } }
package OOP.EX10_INTERFACES_AND_ABSTRACTION.E05_Тelephony; public interface Callable { String call(); }
package ALIXAR.U6_FICHEROS_TEXTO.T2.A3; import java.io.*; import java.sql.SQLOutput; import java.util.Scanner; public class Principal_A3 { public static void main(String[] args) { Scanner teclado = new Scanner(System.in); //CREO UN BUCLE EN EL CUAL INSERTO TANTOS NUMEROS ENTEROS POSITIVOS COMO QUIERA //Y FINALIZO INTRODUCIENDO UN NEGATIVO try { ObjectOutputStream flujo_salida; flujo_salida = new ObjectOutputStream(new FileOutputStream("C:\\Users\\daw1\\prog_daw1\\Programacion_Alixar\\src" + "\\ALIXAR\\U6_FICHEROS_TEXTO\\T2\\A3\\lista.dat")); int numero; do { System.out.println("Introduzca un numero entero positivo: "); numero = teclado.nextInt(); if (numero >= 0) { flujo_salida.writeInt(numero); } } while (numero >= 0); flujo_salida.close(); }catch (IOException e) { System.out.println("Error"); } //LEO TODOS LOS NUMEROS INSERTADOS EN EL FICHERO ANTERIOR //EMPLEANDO UN BUCLE INFINITO try { ObjectInputStream flujo_entrada; flujo_entrada = new ObjectInputStream(new FileInputStream("C:\\Users\\daw1\\prog_daw1\\Programacion_Alixar\\src" + "\\ALIXAR\\U6_FICHEROS_TEXTO\\T2\\A3\\lista.dat")); while (true) { System.out.println(flujo_entrada.readInt()); } }catch (EOFException ex) { System.out.println("Fin de fichero"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
package com.isteel.myfaceit.ui.favourites; import android.content.Context; import androidx.recyclerview.widget.LinearLayoutManager; import java.util.ArrayList; import dagger.Module; import dagger.Provides; @Module public class FavouritesModule { @Provides FavouritesAdapter provideGameAdapter() { return new FavouritesAdapter(new ArrayList<>()); } @Provides LinearLayoutManager provideLinearLayoutManager(Context context) { return new LinearLayoutManager(context); } }
/** * <copyright> * </copyright> * * $Id$ */ package simulator.srl.impl; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.impl.EFactoryImpl; import org.eclipse.emf.ecore.plugin.EcorePlugin; import simulator.srl.*; /** * <!-- begin-user-doc --> * An implementation of the model <b>Factory</b>. * <!-- end-user-doc --> * @generated */ public class ResultsFactoryImpl extends EFactoryImpl implements ResultsFactory { /** * Creates the default factory implementation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static ResultsFactory init() { try { ResultsFactory theResultsFactory = (ResultsFactory)EPackage.Registry.INSTANCE.getEFactory("srl"); if (theResultsFactory != null) { return theResultsFactory; } } catch (Exception exception) { EcorePlugin.INSTANCE.log(exception); } return new ResultsFactoryImpl(); } /** * Creates an instance of the factory. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ResultsFactoryImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EObject create(EClass eClass) { switch (eClass.getClassifierID()) { case ResultsPackage.RESULTS: return createResults(); case ResultsPackage.STIMULUS: return createStimulus(); case ResultsPackage.RESPONSE: return createResponse(); case ResultsPackage.ENVIRONMENTAL_CHANGE: return createEnvironmentalChange(); default: throw new IllegalArgumentException("The class '" + eClass.getName() + "' is not a valid classifier"); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Results createResults() { ResultsImpl results = new ResultsImpl(); return results; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Stimulus createStimulus() { StimulusImpl stimulus = new StimulusImpl(); return stimulus; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Response createResponse() { ResponseImpl response = new ResponseImpl(); return response; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EnvironmentalChange createEnvironmentalChange() { EnvironmentalChangeImpl environmentalChange = new EnvironmentalChangeImpl(); return environmentalChange; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ResultsPackage getResultsPackage() { return (ResultsPackage)getEPackage(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @deprecated * @generated */ @Deprecated public static ResultsPackage getPackage() { return ResultsPackage.eINSTANCE; } } //ResultsFactoryImpl
package algorithms.sorting.quick.partition; import org.apache.commons.lang3.tuple.Pair; /** * Created by Chen Li on 2018/2/1. */ public interface Partitioner<T> { /** * given an array, start index low, end index high( end index include), * partition the array into two or three parts, * return left middle index and right middle index * if right middle index = left middle +1, then partition the array into 2 parts, * if right middle index > left middle +1, then partition the array into 3 parts */ Pair<Integer, Integer> partition(T[] arr, int low, int high); }
package com.chisw.timofei.booking.accommodation.controller.dto; import lombok.*; /** * @author timofei.kasianov 10/2/18 */ @AllArgsConstructor @NoArgsConstructor @Getter @Setter @Builder public class AccommodationViewDTO { private String id; private long ratePerNightInCents; private String description; private String hostId; }
package _03_array_and_method.max_element_array_2d; import java.util.Scanner; public class MaxElementArray2D { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter row of matrix: "); int rowMatrix = scanner.nextInt(); System.out.print("Enter column of matrix: "); int colMatrix = scanner.nextInt(); double[][] matrix = new double[rowMatrix][colMatrix]; for (int row = 0; row < rowMatrix; row++) { for (int column = 0; column < colMatrix; column++) { System.out.print("Enter value of Matrix[" + row + "][" + column + "]: "); matrix[row][column] = scanner.nextDouble(); } } double valueMax = matrix[0][0]; int indexRowMax = 0; int indexColumn = 0; for (int row = 0; row < rowMatrix; row++) { for (int column = 0; column < colMatrix; column++) { System.out.print(matrix[row][column] + "\t"); if (matrix[row][column] > valueMax) { valueMax = matrix[row][column]; indexRowMax = row; indexColumn = column; } } System.out.println(); } System.out.println("Value max is: Matrix[" + indexRowMax + "][" + indexColumn + "] = " + valueMax); } }
package am.bizis.cds.dpfdp4; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Element; import am.bizis.cds.IVeta; /** * Záznam o příjmech a výdajích dle § 10 zákona * @author alex */ public class VetaJ implements IVeta { private String druh_prij10; private Kod10 kod10; private KodDrPrij10 kod_dr_prij10; private double prijmy10, rozdil10, vydaje10; /** * Vytvori vetu J s povinnymi polozkami * @param druh_prij10 Slovní popis druhu příjmu podle § 10 odst. 1 zákona * @param kod_dr_prij10 Kód * @param prijmy10 Příjmy * @param vydaje10 Výdaje * @throws IllegalArgumentException maximalni povolena velikost pro druh_prij10 je 50 */ public VetaJ(String druh_prij10,KodDrPrij10 kod_dr_prij10,double prijmy10,double vydaje10) throws IllegalArgumentException{ if(druh_prij10.length()>50) throw new IllegalArgumentException("maximalni povolena velikost pro druh_prij10 je 50"); this.druh_prij10=druh_prij10; this.kod_dr_prij10=kod_dr_prij10; this.prijmy10=prijmy10; this.vydaje10=vydaje10; } /** * @param druh_prij10 Slovní popis druhu příjmu podle § 10 odst. 1 zákona */ public void setDruhPrij10(String druh_prij10){ this.druh_prij10=druh_prij10; } /** * @param kod10 Kód * Přípustné symboly: P, S, Z. * Kód "P" vyplňte pouze v případě, že máte příjmy ze zemědělské výroby a uplatňujete výdaje procentem z příjmů (80%). * Pokud příjmy plynou z majetku, který je ve společném jmění manželů, uveďte kód "S". * Pokud příjmy plynou ze zdrojů v zahraničí, uveďte kód "Z". */ public void setKod10(Kod10 kod10){ this.kod10=kod10; } /** * @param kodDrPrij10 Označení druhu příjmů podle § 10 odst. 1 zákona * A – příležitostná činnost * B - prodej nemovitostí * C - prodej movitých věcí * D - prodej cenných papírů * E - příjmy z převodu podle § 10 odst. 1, písm. c) zákona * F - jiné ostatní příjmy */ public void setKodDrPrij10(KodDrPrij10 kodDrPrij10){ this.kod_dr_prij10=kodDrPrij10; } /** * @param prijmy10 Příjmy * Vyplňte ostatní příjmy podle § 10 zákona, které zahrnují příjmy ze zdrojů na území České republiky i příjmy ze * zdrojů v zahraničí, a to přepočtené na Kč způsobem popsaným výše. Podle § 10 odst. 1 zákona jsou za ostatní příjmy * považovány takové příjmy, při kterých dochází ke zvýšení majetku a nejedná se přitom o příjmy podle § 6 až § 9 * zákona. Každý jednotlivý druh příjmů se uvádí v tabulce samostatně. Jestliže jste ve zdaňovacím období prodal např. * dva obytné domy a současně několik cenných papírů, jedná se o dva druhy příjmů, z nichž se každý posuzuje samostatně. * Za příjem podle § 10 odst. 1 zákona se považuje i příjem odstupného za uvolnění bytu, u kterého nebyly splněny * podmínky pro osvobození od daně podle § 4 odst. 1 písm. u) zákona. */ public void setPrijmy10(double prijmy10){ this.prijmy10=prijmy10; } /** * @param vydaje10 Výdaje * Uveďte výdaje prokazatelně vynaložené na dosažení příjmů, a to ve skutečné výši. Pouze u zemědělské výroby je možno * uplatnit výdaje procentem z příjmů ve výši 80%. */ public void setVydaje10(double vydaje10){ this.vydaje10=vydaje10; } /* (non-Javadoc) * @see am.bizis.cds.dpfdp4.IVeta#getElement() */ @Override public Element getElement() throws ParserConfigurationException { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder=docFactory.newDocumentBuilder(); Document EPO=docBuilder.newDocument(); Element VetaJ=EPO.createElement("VetaJ"); VetaJ.setAttribute("druh_prij10", druh_prij10); if(kod10!=null)VetaJ.setAttribute("kod10",kod10.kod); VetaJ.setAttribute("kod_dr_prij10", kod_dr_prij10.kod); VetaJ.setAttribute("prijmy10",prijmy10+""); rozdil10=prijmy10-vydaje10; VetaJ.setAttribute("rozdil10",rozdil10+""); VetaJ.setAttribute("vydaje10", vydaje10+""); return VetaJ; } @Override /* (non-Javadoc) * @see am.bizis.cds.dpfdp4.IVeta#getMaxPocet() */ public int getMaxPocet() { return 99; } /* (non-Javadoc) * @see am.bizis.cds.dpfdp4.IVeta#getDependency() */ @Override public String[] getDependency() { return null; } /** * Vrati prijmy * @return prijmy */ public double getPrijmy10(){ return this.prijmy10; } /** * Vrati vydaje * @return vydaje */ public double getVydaje10(){ return this.vydaje10; } /** * Vrati rozdil mezi prijmy a vydaji * @return rozdil mezi prijmy a vydaji */ public double getRozdil10(){ return this.prijmy10-this.vydaje10; } @Override public String toString(){ return "VetaJ"; } }
package de.uniwue.jpp.deckgen.model; public class VictoryCard extends AbstractCard implements IVictoryCard { String name, description, extension; int cost,victoryPoints; public VictoryCard(String name, String description, String extension, int cost,int victoryPoints) { super(name, description, extension, cost); objectValidator.validate(victoryPoints); this.victoryPoints = victoryPoints; } @Override public int getVictoryPoints() { // TODO Auto-generated method stub return victoryPoints; } }
package pe.edu.upc.profile.services; import pe.edu.upc.profile.entities.Resident; import java.util.Optional; public interface ResidentService extends CrudService<Resident, Long> { Optional<Resident> auth(String email, String password); Optional<Integer> authToken(String token); }
package com.webstore.shoppingcart.controller.base; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ExceptionHandler; import com.webstore.shoppingcart.dto.response.ResponseDTO; import com.webstore.shoppingcart.exception.ServiceException; import com.webstore.shoppingcart.exception.handler.GeneralExceptionHandler; import com.webstore.shoppingcart.exception.handler.MethodArgumentNotValidExceptionHandler; import com.webstore.shoppingcart.exception.handler.ServiceExceptionHandler; public abstract class ControllerBase { private static final Logger LOG = LoggerFactory.getLogger(ControllerBase.class); @Autowired private MethodArgumentNotValidExceptionHandler methodArgumentNotValidExceptionHandler; @Autowired private ServiceExceptionHandler serviceExceptionHandler; @Autowired private GeneralExceptionHandler generalExceptionHandler; @ExceptionHandler(MethodArgumentNotValidException.class) public ResponseEntity<ResponseDTO<Object>> handleException(MethodArgumentNotValidException exception) { LOG.error("Error while validating the request.", exception); return methodArgumentNotValidExceptionHandler.handleException(exception); } @ExceptionHandler(ServiceException.class) public ResponseEntity<ResponseDTO<Object>> handleException(ServiceException exception) { LOG.error("Business error while processing the request.", exception); return serviceExceptionHandler.handleException(exception); } @ExceptionHandler(Exception.class) public ResponseEntity<ResponseDTO<Object>> handleException(Exception exception) { LOG.error("Unexpected error while processing the request.", exception); return generalExceptionHandler.handleException(exception); } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.csci360.alarmclock; import java.time.LocalTime; import java.time.format.DateTimeFormatter; /** * * @author baldy */ public class Alarm { private String timeOfAlarm; //if false play radio //if true play default alarm private Boolean playStockAlert = true; private String getCurrentTime(){ LocalTime currentTime = LocalTime.now(); DateTimeFormatter format = DateTimeFormatter.ofPattern("hh:mm a"); String text = currentTime.format(format); return text; } // Time must be in the following format // H:M A // Where H is any int between 1 & 12 inclusive // Where M is any int between 0 & 59 // Where A is either AM or PM public String getTimeOfAlarm(){ return timeOfAlarm; } public void setTimeOfAlarm(String t){ if(isValidTime(t)){ this.timeOfAlarm = t; } else System.out.println("Incorrect Time Format"); } public Boolean willPlayAlarm(){ return playStockAlert; } public void setStockAlert(Boolean pA){ this.playStockAlert = pA; } public Boolean shouldSoundAlert(){ return timeOfAlarm.equals(getCurrentTime()); } public void soundAlert() { System.out.println("Wake me up inside"); } public Boolean isValidTime(String time){ String delims = "[: ]"; String[] toke = time.split(delims); int h = Integer.parseInt(toke[0]); int m = Integer.parseInt(toke[2]); String a = toke[4]; if((h>12)||(h<1)){ return false; } else if((m>59)||(m<0)){ return false; } else if( !a.equals("AM")||!a.equals("PM")){ return false; } return true; } public static void main(String[] args) { //String dateOut; //dateOut = LocalDateTime.now().format(format); // LocalDateTime timeUnf = LocalDateTime.now(); // DateTimeFormatter formatter = DateTimeFormatter.ofPattern("hh:mm"); // LocalDateTime time = LocalDateTime.parse(timeUnf, formatter); //System.out.println(dateOut); //System.out.println(LocalDateTime.now().ofLocalizedTime()); // TODO code application logic here String input = "11:33 p"; DateTimeFormatter format = DateTimeFormatter.ofPattern("hh:mm a"); LocalTime time = LocalTime.parse(input, format); System.out.println(time); } }
package com.test; import java.util.BitSet; /** * Given a binary string S (a string consisting only of '0' and '1's) and a positive integer N, * 给一个字符串,有0和1组成 * * return true if and only if for every integer X from 1 to N, * the binary representation of X is a substring of S. * * 当字符串的子字符串,可以表示1-N的所有数时,返回true * * 解决方案:从后往前遍历,如果某个值未赋值,则赋值,最后校验是否全部为true即可 * * 特点:假设N 的大小 = 2^length + x, x <= 2^length时,只需要满足最后那一层的二进制,就满足所有的了。如果未满足,则失败 * 因此,只需要对最后 2^length个数字,进行赋值即可【即,二进制的长度为length、length+1】 * * 耗时 24ms,时间比较长 * * @author YLine * * 2019年5月31日 上午7:59:41 */ public class SolutionA { /** * 输入参数 N >= 1 * S >= 1 */ public boolean queryString(String S, int N) { if (N == 1) // N = 1,只考虑1 { for (int i = S.length() - 1; i >= 0; i--) { if (S.charAt(i) == '1') { return true; } } return false; } else if (N == 2) // N = 2, 只考虑10 { if (S.length() == 1) // 长度不够 { return false; } int value = getFirstValue(S, 2); if (value == 2) { return true; } for (int i = S.length() - 3; i >= 0; i--) { value >>= 1; value |= (S.charAt(i) == '1' ? 2 : 0); if (value == 2) { return true; } } return false; } else // N > 2的情况 { int index = 0; // index表示,N对应有几个'0'或'1' int temp = N; while (temp > 0) { index++; temp = (temp >> 1); } int start = (1 << (index - 2)) + 1; // 需要确定有的数据,的对应的开始值 System.out.println("N = " + N + ", index = " + index + ", start = " + start + ", end = " + N); if (S.length() < index) { return false; } int value = getFirstValue(S, index); Result result = new Result(start, N); result.addValue(value); int topValue = 1 << (index - 1); for (int i = S.length() - index - 1; i >= 0; i--) { value >>= 1; value |= (S.charAt(i) == '1' ? topValue : 0); result.addValue(value >> 1); // 前 length - 1个的情况 result.addValue(value); // length个 if (result.isTrue()) { return true; } } return false; } } /** * 求,某个字符串,倒数第几位,对应的值 * @param S 字符串 * @param length 最后长度 * @return 对应的int值 */ public int getFirstValue(String S, int length) { int lastIndex = S.length() - 1; int value = 0; for (int i = 0; i < length; i++) { if (S.charAt(lastIndex - i) == '1') { value |= (1 << i); } } return value; } public static class Result { private int sSize; // 当前数 private BitSet sBitSet; // 缓存 private int sStart; // 开始值 private int sEnd; // 结束值 private int sTotalCount; // 总数 public Result(int start, int end) { sStart = start; sEnd = end; sTotalCount = end - start + 1; sSize = 0; sBitSet = new BitSet(sTotalCount); } /** * 当前值 * @param value */ public void addValue(int value) { // 不在范围内,直接过滤 if (value < sStart || value > sEnd) { return; } int index = value - sStart; if (!sBitSet.get(index)) // 如果未添加过,则添加 { sSize++; sBitSet.set(index, true); } } /** * 判断最终结果 * @return true if 已经被填充满了 */ public boolean isTrue() { return sSize == sTotalCount; } } }
package com.xys.car.entity; import lombok.Data; import java.math.BigDecimal; import java.util.Date; @Data public class CarSelect { private String name; private BigDecimal pricestart; private BigDecimal priceend; private String type; private String brand; private String entity; private String color; private String caryear; private Integer pageNum; private Integer pageSize; }
package com.improving.bootcamp; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; public class ExampleServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/css"); PrintWriter out = resp.getWriter(); out.println("#sidebar { min-height: 100vh; background-color: lightgray; }"); out.println("#sidebar.active { margin-left: 250px; }"); out.println("#logo { width: 100px; }"); out.println("#logo img { width: 100px; margin: 10px auto 10px 40px; }"); } }
package com.sutran.client.util; import javax.xml.namespace.QName; public class SutranClientConstants { public static final QName SERVICE_NAME = new QName("http://wirelesscar.com/dynafleet/api", "DynafleetAPI"); /* * URL Webservice */ //public static final String WEBSERVICE_DYNAFLEET_URL = "https://api-preprod.dynafleetonline.com/wsdl"; public static final String WEBSERVICE_DYNAFLEET_URL = "https://api2.dynafleetonline.com/wsdl"; public static final String[] CONTEXT_PATHS = new String[] { "classpath:/META-INF/spring/sutranClientApplicationContext.xml", "classpath:/META-INF/spring/sutranClientApplicationContext-service.xml", "classpath:/META-INF/spring/sutranQuartzContext-config.xml"}; /** * Tiempo de inicio de un nuevo hilo, establecido a una hora */ public static final long TIEMPO_ESPERA_CONSUMO_WEBSERVICE_VEHICULO = new Long("3600000"); /** * Tiempo de espera de consumo entre cada 20 metodos */ public static final long TIEMPO_ESPERA_CONSUMO_WEBSERVICE_POR_METODO = new Long("10000"); /** * Tiempo de espera de consumo entre cada 20 inicios de sesion */ public static final long TIEMPO_ESPERA_CONSUMO_WEBSERVICE_POR_LOGIN = new Long("60000"); public static final short MAX_CANTIDAD_CONSUMOS_LOGIN = 19; public static final short MAX_CANTIDAD_CONSUMOS_METODO = 17; /** * Cero */ public final static String VALIDACION_CAMPO_OBLIGATORIO = "obligatorio"; public static final String ACTIVO = "1"; public static final String CADENA_CERO = "0"; public static final String CADENA_UNO = "1"; }
/* * 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 Projeto_v1; import java.util.ArrayList; /** * * @author Gabriel */ public class Disciplina { private String codigo; private int creditos; private ArrayList<Matricula> matriculas; public Disciplina(String codigo, int creditos){ this.codigo = codigo; this.creditos = creditos; } public void addMatricula(Matricula matricula){ this.matriculas.add(matricula); } public ArrayList<Estudante> getEstudantesMatriculados(){ ArrayList<Estudante> estudantes; estudantes = new ArrayList<>(); for(int i = 0; i < matriculas.size(); i++){ estudantes.add(matriculas.get(i).getEstudante()); } return estudantes; } }
/* * Created on Mar 18, 2007 * * * Window - Preferences - Java - Code Style - Code Templates */ package com.citibank.ods.persistence.pl.dao; import com.citibank.ods.entity.pl.BaseTplProductFamilyPrvtEntity; /** * @author leonardo.nakada * * * Preferences - Java - Code Style - Code Templates */ public interface BaseTplProductFamilyPrvtDAO { public BaseTplProductFamilyPrvtEntity find( BaseTplProductFamilyPrvtEntity baseTplProductFamilyPrvtEntity_ ); }
package com.example.andrew.pongdroid; import android.app.Activity; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Point; import android.graphics.Rect; import android.os.Message; import android.util.AttributeSet; import android.view.Display; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.os.Handler; import android.graphics.Point; import android.view.Display; import android.view.WindowManager; import android.widget.TextView; import android.widget.Toast; public class GameView extends SurfaceView implements SurfaceHolder.Callback { protected Thread gameViewThread; protected GameViewRunnable gameViewRunnable; // detects collisions protected GameViewHandler handler; protected Context context; protected SurfaceHolder surfaceHolder; protected boolean hasActiveHolder; protected Paint paint; protected int screenWidth; protected int screenHeight; private Game game; protected class GameViewHandler extends Handler { @Override public void handleMessage( Message inputMessage ){ if( inputMessage != null) { if (inputMessage.what == -1) { Toast.makeText( (Activity) getContext(), ( game.player1.getScore() > game.player2.getScore()) ? "You lose!" : game.player1.getScore() < game.player2.getScore() ? "You win!" : "Draw!", Toast.LENGTH_LONG ).show(); } } draw(); // update UI invalidate(); // mark current frame dirty } } public GameView(Context context, AttributeSet attrs) { super(context, attrs); this.surfaceHolder = getHolder(); this.surfaceHolder.addCallback(this); this.setFocusable(true); this.handler = new GameViewHandler(); this.context = context; this.paint = new Paint(); this.paint.setARGB(150, 0, 150, 0); // transparent green this.game = (Game)getContext(); // cache current game this.gameViewRunnable = new GameViewRunnable( handler, game ); this.gameViewThread = new Thread( gameViewRunnable ); // Cache screen size WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE); Display display = wm.getDefaultDisplay(); Point size = new Point(); display.getSize(size); screenWidth = size.x; screenHeight = size.y; } @Override public void surfaceCreated(SurfaceHolder holder) { game.initialize(); // default positions game.start(); // serve ball synchronized (this) { hasActiveHolder = true; this.notifyAll(); } if( !gameViewThread.isAlive() ) gameViewThread.start(); } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } @Override public void surfaceDestroyed(SurfaceHolder holder) { synchronized (this) { hasActiveHolder = false; this.notifyAll(); } gameViewRunnable.toggle(); } protected void draw() { synchronized ( this ) { if ( hasActiveHolder == true ) { try { Canvas canvas = surfaceHolder.lockCanvas(); // Draw background canvas.drawRGB( 255, 255, 255 ); // Draw score TextView tv = (TextView) ( (Activity) getContext() ).findViewById(R.id.score1); tv.setText( String.valueOf( game.getPlayer1().getScore() ) ); tv = (TextView) game.findViewById( R.id.score2 ); tv.setText(String.valueOf(game.getPlayer2().getScore())); // Draw timer tv = (TextView) ( (Activity) getContext() ).findViewById(R.id.clock); tv.setText( String.valueOf( (int)game.getMaxTime() - (int)game.getTime() / 1000 ) + "s"); tv.setTextColor(Color.GREEN); // Draw players canvas.drawRect( new Rect( game.getPlayer1().getX() - game.getPlayer1().getWidth()/2, game.getPlayer1().getY() + game.getPlayer1().getHeight()/2, game.getPlayer1().getX() + game.getPlayer1().getWidth()/2, game.getPlayer1().getY() - game.getPlayer1().getHeight()/2 ), paint ); canvas.drawRect( new Rect( game.getPlayer2().getX() - game.getPlayer2().getWidth()/2, game.getPlayer2().getY() + game.getPlayer2().getHeight()/2, game.getPlayer2().getX() + game.getPlayer2().getWidth()/2, game.getPlayer2().getY() - game.getPlayer2().getHeight()/2 ), paint ); // Draw ball canvas.drawRect( new Rect( game.getBall().getX() - game.getBall().getSize()/2, game.getBall().getY() + game.getBall().getSize()/2, game.getBall().getX() + game.getBall().getSize()/2, game.getBall().getY() - game.getBall().getSize()/2 ), paint ); surfaceHolder.unlockCanvasAndPost( canvas ); }catch(Exception e){ } } } } }
package urstory.ganada; /** * Created by urstory on 2016. 6. 30.. */ public class GanadaParser { }
package com.xwolf.eop.erp.dao; import com.xwolf.eop.erp.entity.Employees; public interface EmployeesMapper { int deleteByPrimaryKey(Integer eid); int insert(Employees record); int insertSelective(Employees record); Employees selectByPrimaryKey(Integer eid); int updateByPrimaryKeySelective(Employees record); int updateByPrimaryKey(Employees record); }
package ankang.springcloud.homework.common.service; import ankang.springcloud.homework.common.pojo.EmailMessage; import org.apache.commons.mail.EmailException; /** * @author: ankang * @email: dreedisgood@qq.com * @create: 2021-01-11 */ public interface EmailService { /** * 使用SMTP协议发送邮件 * * @param msg 邮件信息 * @throws EmailException 邮件发送失败异常 */ void sendWithSMTP(EmailMessage msg) throws EmailException; }
package ro.ase.cts.composite.program; import ro.ase.cts.composite.clase.CompositeAgentie; import ro.ase.cts.composite.clase.FilialaLeaf; public class Program { public static void main(String[]args) { CompositeAgentie agentie01=new CompositeAgentie(); CompositeAgentie agentie02=new CompositeAgentie(); CompositeAgentie agentie03=new CompositeAgentie(); FilialaLeaf filiala01=new FilialaLeaf("filiala01"); FilialaLeaf filiala02=new FilialaLeaf("filiala02"); FilialaLeaf filiala03=new FilialaLeaf("filiala03"); FilialaLeaf filiala04=new FilialaLeaf("filiala04"); agentie01.adaugaNod(filiala01); agentie01.adaugaNod(filiala02); agentie02.adaugaNod(filiala03); agentie03.adaugaNod(filiala04); agentie01.adaugaNod(agentie03); agentie01.afiseazaDescriere(); System.out.println(); agentie02.afiseazaDescriere(); agentie03.stergeNod(filiala04); agentie01.adaugaNod(filiala04); agentie01.stergeNod(agentie03); agentie01.afiseazaDescriere(); System.out.println(); agentie02.afiseazaDescriere(); } }
package com.employee_recognition.Controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.SessionAttribute; import org.springframework.web.bind.annotation.SessionAttributes; import com.employee_recognition.Entity.User; import com.employee_recognition.Service.AwardService; import com.employee_recognition.Service.UserService; @Controller @SessionAttributes({"userID","user"}) public class UserController { @Autowired private UserService userDAO; @Autowired private AwardService awardDAO; // User Main Page @GetMapping("/user") public String userMainPage(@SessionAttribute("userID") Long userID, Model model) { User currentUser = userDAO.getUserById(userID); model.addAttribute("user", currentUser); model.addAttribute("awards", currentUser.getUserAwards()); return "user"; } // User Update Page GET @RequestMapping(value = "/user/{userID}", method=RequestMethod.GET ) public String updateUserPage(@PathVariable("userID") Long userID, Model model) { User temp = userDAO.getUserById(userID); model.addAttribute("user", temp); return "user_update"; } // User Update Page POST @RequestMapping(value = "/user/{userID}", method=RequestMethod.POST) public String saveUserPage(@ModelAttribute("user") User user) { System.out.println(user.toString()); user = userDAO.saveUser(user,"USER"); return "redirect:/user"; } // Deleting an Award @RequestMapping(value="/delete_award") public String deleteAward(@RequestParam("id") Long id) { awardDAO.deleteAwardByID(id); return "redirect:/user"; } }
import java.util.Scanner; public class TopIntegers3 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String[] input = scanner.nextLine().split("\\s+"); int leftInt; int rightInt; for (int i = 0; i < input.length; i++) { boolean isTopInteger = true; leftInt = Integer.parseInt(input[i]); for (int j = i+1; j < input.length; j++) { rightInt = Integer.parseInt(input[j]); if (leftInt <= rightInt){ isTopInteger = false; } } if (isTopInteger){ System.out.print(leftInt + " "); } } } }
package dijkstra; import java.util.Scanner; /** * Created by Administrator on 2018/5/20. * 输入: * 5 * 50 * 30 5 * 100 20 50 * 10 x x 10 * <p> * 输出: * 35 * * @author danqiusheng */ public class DijkstraDemo3 { static int INF = Integer.MAX_VALUE;//(无法到达) public static void main(String[] args) { int get; Scanner read = new Scanner(System.in); int n = read.nextInt(); int[][] length = new int[n][n]; read.nextLine(); for (int i = 1; i < n; i++) { String[] data = read.nextLine().split(" "); for (int j = 0; j < i; j++) { if (Character.isDigit(data[j].toCharArray()[0])) {// 判断是否为数字 length[j][i] = length[i][j] = Integer.parseInt(data[j]); } else { length[j][i] = length[i][j] = INF; } } } int[] distance = new int[n]; boolean[] flag = new boolean[n]; dijkstra(0, length, distance, flag); } private static void dijkstra(int current, int[][] length, int[] distance, boolean[] flag) { for (int i = 0; i < distance.length; i++) { distance[i] = INF; } for (int i = 0; i < distance.length; i++) distance[i] = length[current][i]; // 当前访问 distance[current] = 0; flag[current] = true; int points = distance.length; int min; for (int i = 0; i < points; i++) { min = INF; // 找寻距离最短的点 for (int j = 0; j < points; j++) { if (!flag[j] && distance[j] < min) { min = distance[j]; current = j; } } flag[current] = true; // 设置这个距离1最短的点被选择 for (int k = 0; k < points; k++) // 获取这个最短的点到其他点的距离 if (!flag[k] && length[current][k] < INF) distance[k] = Math.min(distance[k], distance[current] + length[current][k]); } int total = 0; for (int i = 0; i < points; i++) total = Math.max(total, distance[i]); System.out.println(total); } }
/* * Copyright 2016 TeddySoft Technology. All rights reserved. * */ package tw.teddysoft.gof.Observer; public class DoorCommand implements Command { private Door door = null; public DoorCommand(String ipAddress){ this.door = new Door(ipAddress); } public DoorCommand(Door door){ this.door = door; } @Override public Result execute() { Result result = new Result(Status.OK); if ("open".equals(this.door.getDoorStatus())){ result.setStatus(Status.CRITICAL); result.setMessage("門被開啟"); } return result; } }
package com.stk123.task.strategy; import java.sql.Connection; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import com.stk123.model.Index; import com.stk123.model.K; import com.stk123.util.ServiceUtils; import com.stk123.common.util.EmailUtils; import com.stk123.task.tool.TaskUtils; public class Strategy6 extends Strategy { private final static String img = "iVBORw0KGgoAAAANSUhEUgAAAoUAAAEGCAYAAAAT5e8/AAAACXBIWXMAAA7EAAAOxAGVKw4bAAAAB3RJTUUH4AcPDQ4ApojDuQAAAAd0RVh0QXV0aG9yAKmuzEgAAAAMdEVYdERlc2NyaXB0aW9uABMJISMAAAAKdEVYdENvcHlyaWdodACsD8w6AAAADnRFWHRDcmVhdGlvbiB0aW1lADX3DwkAAAAJdEVYdFNvZnR3YXJlAF1w/zoAAAALdEVYdERpc2NsYWltZXIAt8C0jwAAAAh0RVh0V2FybmluZwDAG+aHAAAAB3RFWHRTb3VyY2UA9f+D6wAAAAh0RVh0Q29tbWVudAD2zJa/AAAABnRFWHRUaXRsZQCo7tInAAAgAElEQVR4nO3dX4gs2X0f8G/tzu5KXav1H2l3vZJiC9sk25ZtkcsEv+zNHQJ2YBJwpgkBK7TBL/ZTTCBkE/rKQQLffrAJwXlxLOchSRMwhMx9cebFcnKv50IImVywH9xLHhxI1lrJsqT1xtWKVuvpPHSf6lOnzzl1TtWpqlNV3w9cdrunurr6b337d/4lk8l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OZQo97tenlrnKZytMizesm8Tm3x1lYZCVtP7H6Lszp3CVDTq5boYComIiBqlmxIncoVQ3MP9DxRDIRERERE1Hgo50ISIiIiIGAqJiIiIiKGQiIiIiMBQSERERERgKCQiIiIiMBQSEREREbiiCREREdFgZXfuHF1nmsaGoZCIcj5fHkRE1A/q3IYmDIVEVOD65UFERMPCPoVERERExFBIRERERGw+JiIiIsqNuW81QyERERGRZKx9q9l8TEREREQMhURERETEUEhEREREYCgkIiIiIjAUEhEREREYComIiIgInJKGqBNjngeLiIjixFBI1JGxzoNFRERxYvMxERERETEUEhERERFDIREREdGgZVnmtB1DIRERERExFBIREREN1vU10jR12pShkIiIiIg4JQ0RERFRTELNZZtlGXD3rvP2DIVEREREkeliLls2HxMRERENTJZlzn0JBYZCIiIiImLzMREREVHfbaS5CLcAEgATz32wUkhEREREDIVEREREQyGqhFVE1Xwcagg2ERER0djUCYRAZKEQ6GYINhEREVGf2QJhlm2QpuU9DKMLhURERETkJtsPMDFWCK+fOAVCgH0KiYiIiPppv66xaT7CLNsAd99w3t0oK4XysG1h4jnBIxEREVFXfJewczHKUDgWHLjTDj7PRETUJrFaiW3sxRYJ0nSCzGN4BkPhwHHgTjv4PBMRUSy2SJBgiwn8WkEHGwpdqjd1h24TERERtalsTWMRCKsoDDR5c7NBl5fL+O4vffo0/6f+XQTC7f5fiOOP7XKZro9vaJdVobeP/fHwMi/zMi8P5bKq6/sv8+Zmgy0S50Bouv9kMplUi5MNyO7cOWqGq9o3y7avLMuOKoRbwJq8+yjk80lmVZ7nWF+bWI+LiCg0U4tiDN+DpmNQq4SH6zfaMDjZ9zt0fTy9aD4ONVrYNpdPmqb534cWDile4j0XegQZERGVG0J/8Hxi6uOo5M0pFA5iCpf9XD4AAM3jAQ5hsKy9nshFWb9W+X2WZRky8AcJERHpqVPQZNkGgPvE1C56USm0cRlQ4juXj6ga9uEEzelQ4ub8K/Tu3bxpADgOh5nyQ6YP702ioeH3LcVCVAd378lw78Heh0LAfuJ1m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te5xqM3mVPodez6VUBZOrj30JiL590OxB5iDGx59qmkV14a9sH9U/a8UfLmpIPNzH8dKh8uAtFlHiw1BIRBSxquHQWAkyVJnE5TRNC0GoqZAUKvwfHqdfHzRTs3uMITBWh/diMSQKurdggn7PgjB0DIVERBEx9VPWDbCxKasEVW1WNFWF/NlGix5Tw9ph7r7jKYGcmojvvnF8H/vbDG06p1DK+tDrfrCE7KNLzWMoJCKqKfSAM10zYH4fmkEGvk2H1vsuDT/HlTRTiKrTb011HEaTwijgKn3Ruu5CECtbKOZzNmwMhUTUC7GP9G/jZNnGfYR8nm0B0xgkjSNPx9OsG/t7XYfV1WFgKCSi3uhblaKvJ0rT8+wbVkI//r4+n1X07b1Ow8BQSEREzhhWiIbrma4PgIiIiIi6x1BIRERERAyFRERERMRQSERERERgKCQiIiIiMBQSERERERgKiYiIiAiaeQqrzDvlexvb9iHvv605tELef5XnJvTz6Sv0fYzlPRDrHG8xvJ6++wr9uaki1scZw/34iuG7s8r9hBTre72tz03X7/W23huxvW+TyWSy9d47EREREQ1K8nmAoZCIiIho5AqVwjc3G/zKpPlFx9u6Hx8xHhMQ53GFOKY3Nxs8wufDHNCInOHz2ue+6/fJ2O+fx8HjiPn+YziGsd9/X/x/4Lgo+dUaB+cAAAAASUVORK5CYII="; @Override public void run(Connection conn, String today) throws Exception { List<Index> results = new ArrayList<Index>(); for(Index index : indexs){ if(index.isStop(today))continue; K k = index.getK(today); if(k==null)continue; K yk = k.before(1); double ma10 = k.getMA(K.Close, 10); double ma20 = k.getMA(K.Close, 20); double ma60 = k.getMA(K.Close, 60); double yma20 = yk.getMA(K.Close, 20); double yma60 = yk.getMA(K.Close, 60); if(ma10 > ma20 && ma20>=yma20 && ma60<=yma60){ double times = k.getVolumeMA(5); if(k.isDecrementVolume(3) && times > 2){ K h5 = k.getKByHHV(5); if(!h5.getDate().equals(k.getDate())){ K kv5 = k.getKByHVV(5); K kv100 = k.getKByHVV(100); if(kv5.getVolumn()*1.2 >= kv100.getVolumn()){ //System.out.println(index.getCode()+","+index.getName()+",change="+index.changePercent); index.changePercent = times; results.add(index); } } } } } if(results.size() > 0){ Collections.sort(results, new Comparator<Index>(){ @Override public int compare(Index o1, Index o2) { int i = (int)((o2.changePercent - o1.changePercent)*10000); return i; }}); /*for(Index index : results){ System.out.println(index.getCode()+","+index.getName()+",change="+index.changePercent); } System.out.println(StkUtils.join(results, ","));*/ EmailUtils.sendAndReport("模型6-放量后连续3日缩量,个数:"+results.size()+",日期:"+today, "1.放量后缩量3日<br>"+ "2.近期放的大量和前面100日内放的大量基本持平或大于<br>"+ "3.20日均线持平或上升,60日均线下降或持平<br>"+ ServiceUtils.getImgBase64(img) + "<br><br>" + TaskUtils.createHtmlTable(today, results)); } } }
package org.camunda.bpm.engine.test.fluent; import org.camunda.bpm.engine.*; import org.camunda.bpm.engine.repository.ProcessDefinition; import org.camunda.bpm.engine.runtime.Job; import org.camunda.bpm.engine.runtime.ProcessInstance; import org.camunda.bpm.engine.task.Task; import org.camunda.bpm.engine.test.fluent.assertions.JobAssert; import org.camunda.bpm.engine.test.fluent.assertions.ProcessDefinitionAssert; import org.camunda.bpm.engine.test.fluent.assertions.ProcessInstanceAssert; import org.camunda.bpm.engine.test.fluent.assertions.TaskAssert; import org.fest.assertions.api.Assertions; /** * Class meant to statically access all * camunda BPM Process Engine Assertions. * * In your code use import static org.camunda.bpm.engine.test.fluent.ProcessEngineAssertions.*; * * @author Martin Schimak <martin.schimak@plexiti.com> */ public class ProcessEngineAssertions extends Assertions { private static ThreadLocal<ProcessEngine> processEngine = new ThreadLocal<ProcessEngine>(); protected ProcessEngineAssertions() {} public static ProcessEngine processEngine() { ProcessEngine processEngine = ProcessEngineAssertions.processEngine.get(); if (processEngine != null) return processEngine; throw new IllegalStateException(String.format("Call %s.init(ProcessEngine processEngine) first!", ProcessEngineAssertions.class.getSimpleName())); } public static void init(final ProcessEngine processEngine) { ProcessEngineAssertions.processEngine.set(processEngine); } public static ProcessDefinitionAssert assertThat(final ProcessDefinition actual) { return ProcessDefinitionAssert.assertThat(processEngine(), actual); } public static ProcessInstanceAssert assertThat(final ProcessInstance actual) { return ProcessInstanceAssert.assertThat(processEngine(), actual); } public static TaskAssert assertThat(final Task actual) { return TaskAssert.assertThat(processEngine(), actual); } public static JobAssert assertThat(final Job actual) { return JobAssert.assertThat(processEngine(), actual); } }
package com.daexsys.automata.world.terrain; import com.daexsys.automata.world.Chunk; import com.daexsys.automata.world.World; public class TerrainGenerator { private World world; public TerrainGenerator(World world) { this.world = world; } public World getWorld() { return world; } public void generate(Chunk chunk) { } }
package net.davoleo.javagui.forms.layouts; import javax.swing.*; import java.awt.*; public class FormGridLayout extends JFrame { public FormGridLayout() { this.setTitle("Grid Layout Example"); this.setSize(400, 300);; this.setLocation(200, 100); //Stores components in a grid-like fashion //Params: 4 and 2 refer to the number of rows and columns //Params 10 and 20 refer to the horizontal and vertical gap between components this.setLayout(new GridLayout(4, 2, 10, 20)); JButton b1 = new JButton("B1"); JButton b2 = new JButton("B2"); JButton b3 = new JButton("B3"); JButton b4 = new JButton("B4"); JButton b5 = new JButton("B5"); this.add(b1); this.add(b2); this.add(b3); this.add(b4); this.add(b5); } }
package com.wirelesscar.dynafleet.api.types; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for Api_DriverDataEntryTO complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="Api_DriverDataEntryTO"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="driverActivityType" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="endTime" type="{http://wirelesscar.com/dynafleet/api/types}Api_Date"/> * &lt;element name="originType" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="startTime" type="{http://wirelesscar.com/dynafleet/api/types}Api_Date"/> * &lt;element name="vehicleId" type="{http://wirelesscar.com/dynafleet/api/types}Api_VehicleId"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "Api_DriverDataEntryTO", propOrder = { "driverActivityType", "endTime", "originType", "startTime", "vehicleId" }) public class ApiDriverDataEntryTO { @XmlElement(required = true, nillable = true) protected String driverActivityType; @XmlElement(required = true, nillable = true) protected ApiDate endTime; @XmlElement(required = true, nillable = true) protected String originType; @XmlElement(required = true, nillable = true) protected ApiDate startTime; @XmlElement(required = true, nillable = true) protected ApiVehicleId vehicleId; /** * Gets the value of the driverActivityType property. * * @return * possible object is * {@link String } * */ public String getDriverActivityType() { return driverActivityType; } /** * Sets the value of the driverActivityType property. * * @param value * allowed object is * {@link String } * */ public void setDriverActivityType(String value) { this.driverActivityType = value; } /** * Gets the value of the endTime property. * * @return * possible object is * {@link ApiDate } * */ public ApiDate getEndTime() { return endTime; } /** * Sets the value of the endTime property. * * @param value * allowed object is * {@link ApiDate } * */ public void setEndTime(ApiDate value) { this.endTime = value; } /** * Gets the value of the originType property. * * @return * possible object is * {@link String } * */ public String getOriginType() { return originType; } /** * Sets the value of the originType property. * * @param value * allowed object is * {@link String } * */ public void setOriginType(String value) { this.originType = value; } /** * Gets the value of the startTime property. * * @return * possible object is * {@link ApiDate } * */ public ApiDate getStartTime() { return startTime; } /** * Sets the value of the startTime property. * * @param value * allowed object is * {@link ApiDate } * */ public void setStartTime(ApiDate value) { this.startTime = value; } /** * Gets the value of the vehicleId property. * * @return * possible object is * {@link ApiVehicleId } * */ public ApiVehicleId getVehicleId() { return vehicleId; } /** * Sets the value of the vehicleId property. * * @param value * allowed object is * {@link ApiVehicleId } * */ public void setVehicleId(ApiVehicleId value) { this.vehicleId = value; } }
package lru.cache.simulator; import java.awt.Panel; import java.util.Random; import javax.swing.JFrame; import javax.swing.SwingUtilities; /** * * @author HishamAhmed */ class Node{ Node prev; Node next; int pageNo; public Node(int pageNo){ this.prev = null; this.next = null; this.pageNo = pageNo; } } class Queue{ Node front, rear; int TotalFrames, count; public Queue(int NoOfFrames){ this.front = null; this.rear = null; this.count = 0; this.TotalFrames = NoOfFrames; } public boolean isEmpty(){ return this.rear == null; } public boolean isFull(){ return this.count == this.TotalFrames; } public Node dequeue(int val, int NoOfFrames){ Node current = null; if(isEmpty()){ return current; } if(this.front == this.rear){ this.front = null; } if(val == 0){ //MRU current = this.front; this.front = front.next; } if(val == 1){ //LRU this.rear = this.rear.prev; if(this.rear != null){ current = this.rear.next; this.rear.next = null; } } /* if(val == 2){ //RANDOM Random gen = new Random(); int value = gen.nextInt(NoOfFrames+1)+1; current = this.front; for(int i=0;i<value;i++){ current = current.next; } if(current != this.front) current.prev.next = current.next; else this.front = this.front.next; } */ this.count--; return current; } public void Enqueue(Hash h, int pageNo,int val,int NoOfFrames){ if(isFull()){ if(val == 0){ System.out.println("Deleting "+ this.rear.pageNo + " from cache"); h.QueArray[this.rear.pageNo] = null; } if(val == 1){ System.out.println("Deleting "+ this.front.pageNo + " from cache"); h.QueArray[this.front.pageNo] = null; } dequeue(val, NoOfFrames); /* if(val == 2){ h.QueArray[node.pageNo] = null; System.out.println("Deleting "+ node.pageNo + " from cache"); } */ } Node temp = new Node(pageNo); temp.next = this.front; if(isEmpty()){ this.rear = this.front = temp; } else{ this.front.prev = temp; this.front = temp; } h.QueArray[pageNo] = temp; this.count++; } public String printQueue(){ Node temp = this.front; String data = ""; System.out.print("Current Cache: "); for(int i=0;i<this.count;i++){ System.out.print(temp.pageNo + " "); data += temp.pageNo + "|"; temp = temp.next; } System.out.println(""); return data; } public void deleteQueue(){ this.front = this.rear = null; } } class Hash{ int capacity; Node[] QueArray; public Hash(int capacity){ this.capacity = capacity; this.QueArray = new Node[capacity]; for (int i=0;i<this.capacity;i++){ this.QueArray[i] = null; } } } public class LRUCacheSimulator { public Boolean getPage(Queue q, Hash h,int pageNumber,int value,int NoofFrames){ Node reqPage = h.QueArray[pageNumber]; if(reqPage == null){ System.out.println("MISS!!!"); q.Enqueue(h, pageNumber, value, NoofFrames); return false; } else { System.out.println("HIT!!!!"); if (reqPage != q.front){ reqPage.prev.next = reqPage.next; if (reqPage.next != null) reqPage.next.prev = reqPage.prev; if (reqPage == q.rear) { q.rear = reqPage.prev; q.rear.next = null; } reqPage.next = q.front; reqPage.prev = null; q.front.prev = reqPage; q.front = reqPage; } return true; } } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable(){ public void run() { JFrame frame = new JFrame("LRU Cache Simulator"); frame.setSize(500,450); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); JPanel panel = new JPanel(); frame.add(panel); frame.setSize(415,415); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }); } }
package payment.domain.model; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import lombok.Data; /** * @author claudioed on 26/06/17. Project docker-aws-devry */ @Data public class Order { String id; String customer; List<Item> items = new ArrayList<>(); String status; public boolean hasThreeElements(){ return this.items.size() == 3; } public BigDecimal amount(){ return items.stream().map(item -> item.getPrice().multiply(BigDecimal.valueOf(item.getQty()))).reduce(BigDecimal.ZERO, BigDecimal::add); } }
package naming; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SwingConstants; import extra.Constant; import middleware.Invoker; public class NamingServiceServer extends JPanel { private static final long serialVersionUID = 3658763986086752526L; public static void main(String [] args) { //Invoker for attending to requests NamingService naming_service_obj = new NamingService(); Invoker naming_service_invoker = new Invoker(naming_service_obj, Constant.NAMING_SERVER_PORT, Constant.NAMING_SERVER_PUBLIC_KEY, Constant.NAMING_SERVER_PRIVATE_KEY); //Window for Server controlling JLabel label1 = new JLabel("Naming Server Status"); label1.setText("NAMING SERVER IS ON PORT " + String.valueOf(naming_service_invoker.GetServicePort())); label1.setHorizontalAlignment(SwingConstants.CENTER); label1.setVerticalAlignment(SwingConstants.CENTER); JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300, 200); frame.setTitle("Naming Service Server"); frame.add(label1); frame.setVisible(true); //Server loop for responding to requests while(frame.isVisible()) { naming_service_invoker.Invoke(); } } }
package cn.ztuo.bitrade.job; import cn.ztuo.bitrade.dao.SellRobotOrderDao; import cn.ztuo.bitrade.entity.RobotOrder; import cn.ztuo.bitrade.entity.SellRobotOrder; import com.alibaba.fastjson.JSONObject; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.kafka.core.KafkaTemplate; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.util.List; @Component @Slf4j public class AicJob { @Autowired private SellRobotOrderDao sellRobotOrderDao; @Autowired private KafkaTemplate<String, String> kafkaTemplate; @Scheduled(fixedDelay = 1000*60) public void issueJob(){ //处理sellRobotOrder表里的数据,查询sellRobotOrder表里创建时间+系统参数小于等等钱时间的委托单 List<SellRobotOrder> sellRobotOrders = sellRobotOrderDao.getSellRobot(); log.info("扫描到有"+sellRobotOrders.size()+"条订单需要发布"); sellRobotOrders.forEach(sellRobotOrder -> { log.info("机器人发布买单"); //创建一个机器人订单 RobotOrder robotOrder = new RobotOrder(); //设置会员id robotOrder.setMemberId(sellRobotOrder.getMemberId()); //设置投入金额 robotOrder.setAmount(sellRobotOrder.getAmount()); //0为买 1为卖 robotOrder.setType(0); //买入的比率 robotOrder.setRate(sellRobotOrder.getRate()); //卖出的比率 robotOrder.setSellRate(sellRobotOrder.getBuyRate()); //设置卖出的机器人订单 robotOrder.setSellRobotOrderId(sellRobotOrder.getId()); kafkaTemplate.send("add-robot-buy-order", JSONObject.toJSONString(robotOrder)); log.info(" 推送至队列成功"); }); } }
package round01.java; /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Code02_Reverse_Linked_List { public ListNode reverseList(ListNode head) { ListNode cur = head; ListNode prev = null; while (cur != null) { ListNode tempNode = cur.next; cur.next = prev; prev = cur; cur = tempNode; } return prev; } static class ListNode { int val; ListNode next; ListNode(int x) { val = x; } @Override public String toString() { StringBuilder temp = new StringBuilder("[" + val); ListNode tempNode = next; while (tempNode != null) { temp.append(", ").append(tempNode.val); tempNode = tempNode.next; } temp.append("]"); return temp.toString(); } } public static void main(String[] args) { ListNode head = new ListNode(1); ListNode node1 = new ListNode(2); ListNode node2 = new ListNode(3); ListNode node3 = new ListNode(4); ListNode node4 = new ListNode(5); head.next = node1; node1.next = node2; node2.next = node3; node3.next = node4; System.out.println(head); ListNode result = new Code02_Reverse_Linked_List().reverseList(head); System.out.println(result); } }
package com.ideaheap.coalition; import java.util.Collections; import java.util.List; /** * The Phenotype * @author nwertzberger * */ public abstract class Coalition { public static final int SIZE_WEIGHT = 200; protected final Genome gene; protected final int coalitionSize; public Coalition(Genome gene, int coalitionSize) { this.gene = gene; this.coalitionSize = coalitionSize; } public String toString() { List<List<Integer>> codons = this.gene.activeCodons(); for (List<Integer> c : codons) Collections.sort(c); return codons.toString(); } public abstract Integer weight(); }
import java.lang.*; /** * The Song class represents a single recorded music track. * A song has a length in minutes and seconds, and also a title. * * @author Kody Dangtongdee * @version 1/28/2015 */ public class Song { /** * The name of this song. */ private String songTitle; /** * The duration of this song. */ private TimeDuration duration; private static String name; /** Construct a song from its title and duration. * @param title the name of the song * @param songLength the song length in seconds */ public Song(String title, int songLength) { songTitle = title; name = title; duration = new TimeDuration(songLength); } /** Construct a song from its title and duration. * @param title the name of the song * @param songMinutes the minutes portion of the song length * @param songSeconds the seconds part of the song length * @pre 0 <= songMinutes <= 999 * @pre 0 <= songSeconds <= 59 */ public Song(String title, int songMinutes, int songSeconds) { songTitle = title; duration = new TimeDuration(songMinutes, songSeconds); } /** * Factory method that builds a song using the given description. If the * description fails to parse correctly, the song's length is * set to 0:00 and the title to an empty string. * * @param description A string in the format "minutes:seconds name" where * minutes and seconds are integers, and name is a string. A single blank * separates the time from the song name. * @return Song created from the given description */ public static Song parseSong(String description) { Song song = null; //Song that will be made from the description try { String newSong = description.trim(); //Split the description around the semi-colon String[] parse = newSong.split(":"); //the first part of the split string is the minutes int minutes = Integer.parseInt(parse[0]); //1st 2 indexes of the parsed description int seconds = Integer.parseInt(parse[1].substring(0, 2)); //leaving the rest of the string to be used as the name //create the new song int subStart = 3; song = new Song(parse[1].substring(subStart), minutes, seconds); } //if the song was formatted incorrectly this exception may be thrown catch (NumberFormatException e) { //set the song to 0:00 and an empty string e.printStackTrace(); song = new Song("", 0); } return song; } /** * Compares this Song with the specified Object for equality. * * @param x Object to which this Song is to be compared. * @return <tt>true</tt> if and only if the specified Object is a * Song whose title and duration are equal to this Song. */ public boolean equals(Object x) { //If object x is a Song if (x instanceof Song) { //return whether or not this and x are equal return x != null && ((Song)x).songTitle.equals(this.songTitle) && ((Song)x).duration.equals(this.duration) && ((Song)x).toString().equals(this.toString()); } return false; } /** * Returns a printable representation of this song. * * @return song formatted as "MM:SS title". Examples:<br> * <code>0:55 Layla<br> * 1:23 Blackbird<br> * 11:42 Caravan<br> * 0:06 Shorty<br></code> */ public String toString() { String song = duration.toString() + " " + songTitle; return song; } /** * Returns the duration of this song. * * @return The duration of this song. */ public TimeDuration getDuration() { return duration; } /** * Accessor to the title of the song. * @return String the title of the song */ public String getName() { return name; } }
package com.example.ptljdf; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.Button; import android.widget.EditText; public class ConfirmActivity extends AppCompatActivity { private EditText nameEditText, phoneEditText, AddressEditText, cityEditText; private Button confirm_order; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_confirm); confirm_order=(Button)findViewById(R.id.confirm_order_button); nameEditText=(EditText) findViewById(R.id.shipment_name); nameEditText=(EditText) findViewById(R.id.shipment_phone); nameEditText=(EditText) findViewById(R.id.shipment_address); nameEditText=(EditText) findViewById(R.id.shipment_city); } }
package com.vicutu.persistence.dao; import java.util.List; import org.hibernate.criterion.DetachedCriteria; import com.vicutu.persistence.query.Pagination; public interface BasePaginationCriteriaDao<E> { List<E> queryByCriteria(DetachedCriteria detachedCriteria); int countByCriteria(DetachedCriteria detachedCriteria); Pagination<E> queryByCriteria(DetachedCriteria detachedCriteria, int start, int limit); List<E> queryByCriteria(Object condition); int countByCriteria(Object condition); Pagination<E> queryByCriteria(Object condition, int start, int limit); }
package com.citibank.ods.persistence.pl.dao; import java.util.Date; import com.citibank.ods.common.dataset.DataSet; import com.citibank.ods.common.exception.UnexpectedException; import com.citibank.ods.entity.pl.TplProductCorpHistEntity; public interface TplProductCorpHistDAO extends BaseTplProductCorpDAO { /** * Métodos Abstratos * */ public TplProductCorpHistEntity insert( TplProductCorpHistEntity tplProductCorpHistEntity_ ) throws UnexpectedException; public DataSet list( String prodCode_, Date refDate_); }
package pl.edu.agh.mwo.invoice; import java.math.BigDecimal; import java.util.Collection; import java.util.HashMap; import java.util.Map; import pl.edu.agh.mwo.invoice.product.Product; public class Invoice { private Map<Product, Integer> products = new HashMap<>(); public void addProduct(Product product) { this.addProduct(product,1); } public void addProduct(Product product, Integer quantity) { if(quantity == null || quantity < 1) { throw new IllegalArgumentException("Product quantity is invalid."); } this.products.put(product, quantity); } public BigDecimal getNetPrice() { BigDecimal sum = BigDecimal.ZERO; for (Product product: this.products.keySet()) { Integer quantity = this.products.get(product); sum = sum.add(product.getPrice().multiply(new BigDecimal(quantity))); } return sum; } public BigDecimal getTax() { BigDecimal sum = BigDecimal.ZERO; for (Product product: this.products.keySet()) { Integer quantity = this.products.get(product); sum = sum.add((product.getPriceWithTax().subtract(product.getPrice())).multiply(new BigDecimal(quantity))); } return sum; } public BigDecimal getGrossPrice() { BigDecimal sum = BigDecimal.ZERO; for (Product product: this.products.keySet()) { Integer quantity = this.products.get(product); sum = sum.add(product.getPriceWithTax().multiply(new BigDecimal(quantity))); } return sum; } }
import com.alibaba.com.caucho.hessian.io.HessianInput; import com.alibaba.com.caucho.hessian.io.HessianOutput; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Arrays; import object.User; /** * Created by 罗选通 on 2017/11/6. */ public class Test { @org.junit.Test public void test() { String s = "1-1,2-12,3-123,4-1234,5-12345"; String param1 = "2"; String param2 = "0"; String[] split = s.split(","); System.out.println(Arrays.toString(split)); boolean flag = false; for (int i = 0; i < split.length; i++) { String[] split1 = split[i].split("-"); String[] split2 = split1[1].split(""); if (split1[0].equals(param1)) { for (int j = 0; j < split2.length; j++) { if (split2[j].equals(param2)) { flag = true; break; } } } } System.out.println(flag); } @org.junit.Test public void arrays() { String[] s = new String[10]; Arrays.fill(s, 0, 9, "1"); Arrays.sort(s); System.out.println(Arrays.toString(s)); } /** * @Description java内置序列化,反序列化 * @Author 罗选通 * @Date 2017/11/7 20:14 * @method */ @org.junit.Test public void serialize() throws IOException, ClassNotFoundException { //定义字节数组输出流 ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); //对象输出流 ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream); User user = getUser(); //将对象写入到字节数组输出,进行序列化 objectOutputStream.writeObject(user); byte[] bytes = outputStream.toByteArray(); //字节数组输入流 ByteArrayInputStream arrayInputStream = new ByteArrayInputStream(bytes); ObjectInputStream objectInputStream = new ObjectInputStream(arrayInputStream); //执行反序列化,从流中读取数据 Object o = objectInputStream.readObject(); System.out.println(o.toString()); } public User getUser() { User user = new User(); user.setFullname("Luo xuantong"); user.setSalt("霄哥是个大傻"); return user; } @org.junit.Test public void hessian() throws IOException { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); HessianOutput hessianOutput = new HessianOutput(byteArrayOutputStream); hessianOutput.writeObject(getUser()); byte[] bytes = byteArrayOutputStream.toByteArray(); //hessian的反序列化读取对象 ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); HessianInput input = new HessianInput((inputStream)); Object o = input.readObject(); System.out.println(o.toString()); } @org.junit.Test public void finallyTest() { System.out.println("getValue()返回值为:" + getValue()); } // public static int getValue() { // try { // return 0; // } finally { // return 1; // } // } public static int getValue() { int i = 1; try { return i; } finally { i++; } } }
package com.lenovohit.ssm.payment.manager; import com.lenovohit.ssm.payment.model.Settlement; public abstract class BankPayManager implements PayBaseManager{ public abstract void queryCard(Settlement settlement); }
package com.allure.service.framework.exceprion; import lombok.Getter; import lombok.Setter; /** * Created by yang_shoulai on 7/21/2017. */ @Setter @Getter public class ApiException extends RuntimeException { private String msgCode; private Object[] msgArgs; public ApiException(String msgCode, Object... msgArgs) { this(msgCode, msgArgs, null); } public ApiException(String msgCode) { this(msgCode, null, null); } public ApiException(String msgCode, Object[] msgArgs, Throwable throwable) { super(throwable); this.msgCode = msgCode; this.msgArgs = msgArgs; } }
package com.arthur.bishi.bzhan; import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; /** * @description: * @author: arthurji * @date: 2021/9/13 18:58 * @modifiedBy: * @version: 1.0 */ public class No1 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); ArrayList<int[]> nums = new ArrayList<>(); while (scanner.hasNextLine()) { String temp = scanner.nextLine(); int[] t = Arrays.stream(temp.split("\\W+")).filter(s -> !s.isEmpty()).mapToInt(Integer::valueOf).toArray(); nums.add(t); } int[][] grid = nums.toArray(new int[0][0]); int ans = 0; for (int i = 0; i < grid.length; i++) { for (int j = 0; j < grid[i].length; j++) { ans = Math.max(ans, dfs(grid, i, j)); } } System.out.println(ans); ; } public static int dfs(int[][] grid, int i, int j) { if (i < 0 || j < 0 || i >= grid.length || j >= grid[i].length || grid[i][j] == 0) { return 0; } grid[i][j] = 0; return dfs(grid, i + 1, j) + dfs(grid, i - 1, j) + dfs(grid, i, j + 1) + dfs(grid, i, j - 1) + 1; } }
package denoflionsx.DenPipes.AddOns.Forestry.gui; import cpw.mods.fml.common.network.PacketDispatcher; import denoflionsx.DenPipes.AddOns.Forestry.PluginForestryPipes; import denoflionsx.DenPipes.AddOns.Forestry.gui.slot.DenSlot; import denoflionsx.DenPipes.AddOns.Forestry.gui.slot.SlotFake; import denoflionsx.DenPipes.AddOns.Forestry.net.Packets; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.client.renderer.texture.TextureMap; import net.minecraft.util.Icon; import net.minecraft.util.ResourceLocation; import org.lwjgl.opengl.GL11; public class GuiForestryPipe extends GuiContainer { public ContainerForestryPipe container; private ArrayList<DenSlot> totalSlots = new ArrayList(); public static final ResourceLocation bg = new ResourceLocation("@NAME@".toLowerCase().replace("-", "").concat(":") + "textures/gui/adv_apiarist_pipe_gui.png"); public GuiForestryPipe(ContainerForestryPipe par1Container) { super(par1Container); this.container = par1Container; this.xSize = 256; this.ySize = 256; try { for (Field f : par1Container.getClass().getDeclaredFields()) { if (f.getType().equals(DenSlot[].class)) { totalSlots.addAll(Arrays.asList((DenSlot[]) f.get(par1Container))); } } } catch (Throwable pokeball) { } } @Override public void updateScreen() { super.updateScreen(); //To change body of generated methods, choose Tools | Templates. } @Override protected void drawGuiContainerBackgroundLayer(float gameTicks, int mouseX, int mouseY) { mouseX -= guiLeft; mouseY -= guiTop; GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); mc.renderEngine.bindTexture(bg); drawTexturedModalRect(guiLeft, guiTop, 0, 0, xSize, ySize); GL11.glPushMatrix(); GL11.glTranslatef(guiLeft, guiTop, 0.0F); GL11.glPopMatrix(); } @Override protected void drawGuiContainerForegroundLayer(int x, int y) { try { for (DenSlot slot : this.totalSlots) { slot.doRendering(this); } this.container.lock.doRendering(this); this.container.clear.doRendering(this); } catch (Throwable t) { t.printStackTrace(); } } @Override public void drawScreen(int x, int y, float gameTicks) { try { super.drawScreen(x, y, gameTicks); x -= guiLeft; y -= guiTop; for (DenSlot s : this.totalSlots) { if (x >= s.getX() && x <= s.getX() + 16 && y >= s.getY() && y <= s.getY() + 16) { drawCreativeTabHoveringText(s.getTooltipText(this, PluginForestryPipes.keyMap.get(s.getKeyID())), x + this.guiLeft, y + this.guiTop); } } if (this.isSlotClicked(x, y, this.container.lock)) { drawCreativeTabHoveringText(this.container.lock.getTooltipText(this, null), x + this.guiLeft, y + this.guiTop); } if (this.isSlotClicked(x, y, this.container.clear)) { drawCreativeTabHoveringText(this.container.clear.getTooltipText(this, null), x + this.guiLeft, y + this.guiTop); } } catch (Throwable t) { t.printStackTrace(); } } @Override protected void mouseClicked(int x, int y, int button) { try { super.mouseClicked(x, y, button); x -= guiLeft; y -= guiTop; for (Object o : inventorySlots.inventorySlots) { if (o instanceof SlotFake) { SlotFake s = (SlotFake) o; if (x >= s.xDisplayPosition && x <= s.xDisplayPosition + 16 && y >= s.yDisplayPosition && y <= s.yDisplayPosition + 16) { PacketDispatcher.sendPacketToServer(Packets.Wrapper.createPacket(Packets.packet_FakeSlotChange, new Object[]{this.container.te.xCoord, this.container.te.yCoord, this.container.te.zCoord, s.slotNumber})); } } } for (DenSlot s : this.totalSlots) { if (isSlotClicked(x, y, s)) { PacketDispatcher.sendPacketToServer(Packets.Wrapper.createPacket(Packets.packet_FakeSlotSpeciesChange, new Object[]{this.container.te.xCoord, this.container.te.yCoord, this.container.te.zCoord, s.getSlotNumber(), button, s.getKeyID()})); } } if (this.isSlotClicked(x, y, this.container.lock)) { PacketDispatcher.sendPacketToServer(Packets.Wrapper.createPacket(Packets.packet_lock, new Object[]{this.container.te.xCoord, this.container.te.yCoord, this.container.te.zCoord, !this.container.logic.lock.isLocked})); } if (this.isSlotClicked(x, y, this.container.clear)) { PacketDispatcher.sendPacketToServer(Packets.Wrapper.createPacket(Packets.packet_clear, new Object[]{this.container.te.xCoord, this.container.te.yCoord, this.container.te.zCoord, true})); } } catch (Throwable t) { t.printStackTrace(); } } public boolean isSlotClicked(int x, int y, DenSlot s) { return x >= s.getX() && x <= s.getX() + 16 && y >= s.getY() && y <= s.getY() + 16; } public void drawIcon(Icon icon, int x, int y, int spriteSheet) { drawIcon(icon, x, y, spriteSheet, false); } public void drawIcon(Icon icon, int x, int y, int spriteSheet, boolean color) { if (spriteSheet == 0) { Minecraft.getMinecraft().renderEngine.bindTexture(TextureMap.locationBlocksTexture); } else { Minecraft.getMinecraft().renderEngine.bindTexture(TextureMap.locationItemsTexture); } if (!color) { GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0F); } drawTexturedModelRectFromIcon(x, y, icon, 16, 16); } }
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.servlet.function; import java.io.IOException; import java.net.InetSocketAddress; import java.net.URI; import java.nio.charset.Charset; import java.security.Principal; import java.time.Instant; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Optional; import java.util.OptionalLong; import java.util.function.Consumer; import jakarta.servlet.ServletException; import jakarta.servlet.http.Cookie; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpSession; import jakarta.servlet.http.Part; import org.springframework.core.ParameterizedTypeReference; import org.springframework.core.io.buffer.DataBuffer; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.HttpRange; import org.springframework.http.MediaType; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.server.PathContainer; import org.springframework.http.server.RequestPath; import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.CollectionUtils; import org.springframework.util.MultiValueMap; import org.springframework.validation.BindException; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.util.ServletRequestPathUtils; import org.springframework.web.util.UriBuilder; /** * Represents a server-side HTTP request, as handled by a {@code HandlerFunction}. * Access to headers and body is offered by {@link Headers} and * {@link #body(Class)}, respectively. * * @author Arjen Poutsma * @since 5.2 */ public interface ServerRequest { /** * Get the HTTP method. * @return the HTTP method as an HttpMethod enum value, or {@code null} * if not resolvable (e.g. in case of a non-standard HTTP method) */ HttpMethod method(); /** * Get the name of the HTTP method. * @return the HTTP method as a String * @deprecated in favor of {@link #method()} */ @Deprecated String methodName(); /** * Get the request URI. */ URI uri(); /** * Get a {@code UriBuilderComponents} from the URI associated with this * {@code ServerRequest}. * @return a URI builder */ UriBuilder uriBuilder(); /** * Get the request path. */ default String path() { return requestPath().pathWithinApplication().value(); } /** * Get the request path as a {@code PathContainer}. * @deprecated as of 5.3, in favor on {@link #requestPath()} */ @Deprecated default PathContainer pathContainer() { return requestPath(); } /** * Get the request path as a {@code PathContainer}. * @since 5.3 */ default RequestPath requestPath() { return ServletRequestPathUtils.getParsedRequestPath(servletRequest()); } /** * Get the headers of this request. */ Headers headers(); /** * Get the cookies of this request. */ MultiValueMap<String, Cookie> cookies(); /** * Get the remote address to which this request is connected, if available. */ Optional<InetSocketAddress> remoteAddress(); /** * Get the readers used to convert the body of this request. */ List<HttpMessageConverter<?>> messageConverters(); /** * Extract the body as an object of the given type. * @param bodyType the type of return value * @param <T> the body type * @return the body */ <T> T body(Class<T> bodyType) throws ServletException, IOException; /** * Extract the body as an object of the given type. * @param bodyType the type of return value * @param <T> the body type * @return the body */ <T> T body(ParameterizedTypeReference<T> bodyType) throws ServletException, IOException; /** * Bind to this request and return an instance of the given type. * @param bindType the type of class to bind this request to * @param <T> the type to bind to * @return a constructed and bound instance of {@code bindType} * @throws BindException in case of binding errors * @since 6.1 */ default <T> T bind(Class<T> bindType) throws BindException { return bind(bindType, dataBinder -> {}); } /** * Bind to this request and return an instance of the given type. * @param bindType the type of class to bind this request to * @param dataBinderCustomizer used to customize the data binder, e.g. set * (dis)allowed fields * @param <T> the type to bind to * @return a constructed and bound instance of {@code bindType} * @throws BindException in case of binding errors * @since 6.1 */ <T> T bind(Class<T> bindType, Consumer<WebDataBinder> dataBinderCustomizer) throws BindException; /** * Get the request attribute value if present. * @param name the attribute name * @return the attribute value */ default Optional<Object> attribute(String name) { Map<String, Object> attributes = attributes(); if (attributes.containsKey(name)) { return Optional.of(attributes.get(name)); } else { return Optional.empty(); } } /** * Get a mutable map of request attributes. * @return the request attributes */ Map<String, Object> attributes(); /** * Get the first parameter with the given name, if present. Servlet * parameters are contained in the query string or posted form data. * @param name the parameter name * @return the parameter value * @see HttpServletRequest#getParameter(String) */ default Optional<String> param(String name) { List<String> paramValues = params().get(name); if (CollectionUtils.isEmpty(paramValues)) { return Optional.empty(); } else { String value = paramValues.get(0); if (value == null) { value = ""; } return Optional.of(value); } } /** * Get all parameters for this request. Servlet parameters are contained * in the query string or posted form data. * @see HttpServletRequest#getParameterMap() */ MultiValueMap<String, String> params(); /** * Get the parts of a multipart request, provided the Content-Type is * {@code "multipart/form-data"}, or an exception otherwise. * @return the multipart data, mapping from name to part(s) * @throws IOException if an I/O error occurred during the retrieval * @throws ServletException if this request is not of type {@code "multipart/form-data"} * @since 5.3 * @see HttpServletRequest#getParts() */ MultiValueMap<String, Part> multipartData() throws IOException, ServletException; /** * Get the path variable with the given name, if present. * @param name the variable name * @return the variable value * @throws IllegalArgumentException if there is no path variable with the given name */ default String pathVariable(String name) { Map<String, String> pathVariables = pathVariables(); if (pathVariables.containsKey(name)) { return pathVariables().get(name); } else { throw new IllegalArgumentException("No path variable with name \"" + name + "\" available"); } } /** * Get all path variables for this request. */ Map<String, String> pathVariables(); /** * Get the web session for this request. Always guaranteed to * return an instance either matching to the session id requested by the * client, or with a new session id either because the client did not * specify one or because the underlying session had expired. Use of this * method does not automatically create a session. */ HttpSession session(); /** * Get the authenticated user for the request, if any. */ Optional<Principal> principal(); /** * Get the servlet request that this request is based on. */ HttpServletRequest servletRequest(); /** * Check whether the requested resource has been modified given the * supplied last-modified timestamp (as determined by the application). * If not modified, this method returns a response with corresponding * status code and headers, otherwise an empty result. * <p>Typical usage: * <pre class="code"> * public ServerResponse myHandleMethod(ServerRequest request) { * Instant lastModified = // application-specific calculation * return request.checkNotModified(lastModified) * .orElseGet(() -&gt; { * // further request processing, actually building content * return ServerResponse.ok().body(...); * }); * }</pre> * <p>This method works with conditional GET/HEAD requests, but * also with conditional POST/PUT/DELETE requests. * <p><strong>Note:</strong> you can use either * this {@code #checkNotModified(Instant)} method; or * {@link #checkNotModified(String)}. If you want to enforce both * a strong entity tag and a Last-Modified value, * as recommended by the HTTP specification, * then you should use {@link #checkNotModified(Instant, String)}. * @param lastModified the last-modified timestamp that the * application determined for the underlying resource * @return a corresponding response if the request qualifies as not * modified, or an empty result otherwise. * @since 5.2.5 */ default Optional<ServerResponse> checkNotModified(Instant lastModified) { Assert.notNull(lastModified, "LastModified must not be null"); return DefaultServerRequest.checkNotModified(servletRequest(), lastModified, null); } /** * Check whether the requested resource has been modified given the * supplied {@code ETag} (entity tag), as determined by the application. * If not modified, this method returns a response with corresponding * status code and headers, otherwise an empty result. * <p>Typical usage: * <pre class="code"> * public ServerResponse myHandleMethod(ServerRequest request) { * String eTag = // application-specific calculation * return request.checkNotModified(eTag) * .orElseGet(() -&gt; { * // further request processing, actually building content * return ServerResponse.ok().body(...); * }); * }</pre> * <p>This method works with conditional GET/HEAD requests, but * also with conditional POST/PUT/DELETE requests. * <p><strong>Note:</strong> you can use either * this {@link #checkNotModified(Instant)} method; or * {@code #checkNotModified(String)}. If you want to enforce both * a strong entity tag and a Last-Modified value, * as recommended by the HTTP specification, * then you should use {@link #checkNotModified(Instant, String)}. * @param etag the entity tag that the application determined * for the underlying resource. This parameter will be padded * with quotes (") if necessary. * @return a corresponding response if the request qualifies as not * modified, or an empty result otherwise. * @since 5.2.5 */ default Optional<ServerResponse> checkNotModified(String etag) { Assert.notNull(etag, "Etag must not be null"); return DefaultServerRequest.checkNotModified(servletRequest(), null, etag); } /** * Check whether the requested resource has been modified given the * supplied {@code ETag} (entity tag) and last-modified timestamp, * as determined by the application. * If not modified, this method returns a response with corresponding * status code and headers, otherwise an empty result. * <p>Typical usage: * <pre class="code"> * public ServerResponse myHandleMethod(ServerRequest request) { * Instant lastModified = // application-specific calculation * String eTag = // application-specific calculation * return request.checkNotModified(lastModified, eTag) * .orElseGet(() -&gt; { * // further request processing, actually building content * return ServerResponse.ok().body(...); * }); * }</pre> * <p>This method works with conditional GET/HEAD requests, but * also with conditional POST/PUT/DELETE requests. * @param lastModified the last-modified timestamp that the * application determined for the underlying resource * @param etag the entity tag that the application determined * for the underlying resource. This parameter will be padded * with quotes (") if necessary. * @return a corresponding response if the request qualifies as not * modified, or an empty result otherwise. * @since 5.2.5 */ default Optional<ServerResponse> checkNotModified(Instant lastModified, String etag) { Assert.notNull(lastModified, "LastModified must not be null"); Assert.notNull(etag, "Etag must not be null"); return DefaultServerRequest.checkNotModified(servletRequest(), lastModified, etag); } // Static methods /** * Create a new {@code ServerRequest} based on the given {@code HttpServletRequest} and * message converters. * @param servletRequest the request * @param messageReaders the message readers * @return the created {@code ServerRequest} */ static ServerRequest create(HttpServletRequest servletRequest, List<HttpMessageConverter<?>> messageReaders) { return new DefaultServerRequest(servletRequest, messageReaders); } /** * Create a builder with the status, headers, and cookies of the given request. * @param other the response to copy the status, headers, and cookies from * @return the created builder */ static Builder from(ServerRequest other) { return new DefaultServerRequestBuilder(other); } /** * Represents the headers of the HTTP request. * @see ServerRequest#headers() */ interface Headers { /** * Get the list of acceptable media types, as specified by the {@code Accept} * header. * <p>Returns an empty list if the acceptable media types are unspecified. */ List<MediaType> accept(); /** * Get the list of acceptable charsets, as specified by the * {@code Accept-Charset} header. */ List<Charset> acceptCharset(); /** * Get the list of acceptable languages, as specified by the * {@code Accept-Language} header. */ List<Locale.LanguageRange> acceptLanguage(); /** * Get the length of the body in bytes, as specified by the * {@code Content-Length} header. */ OptionalLong contentLength(); /** * Get the media type of the body, as specified by the * {@code Content-Type} header. */ Optional<MediaType> contentType(); /** * Get the value of the {@code Host} header, if available. * <p>If the header value does not contain a port, the * {@linkplain InetSocketAddress#getPort() port} in the returned address will * be {@code 0}. */ @Nullable InetSocketAddress host(); /** * Get the value of the {@code Range} header. * <p>Returns an empty list when the range is unknown. */ List<HttpRange> range(); /** * Get the header value(s), if any, for the header of the given name. * <p>Returns an empty list if no header values are found. * @param headerName the header name */ List<String> header(String headerName); /** * Get the first header value, if any, for the header for the given name. * <p>Returns {@code null} if no header values are found. * @param headerName the header name * @since 5.2.5 */ @Nullable default String firstHeader(String headerName) { List<String> list = header(headerName); return list.isEmpty() ? null : list.get(0); } /** * Get the headers as an instance of {@link HttpHeaders}. */ HttpHeaders asHttpHeaders(); } /** * Defines a builder for a request. */ interface Builder { /** * Set the method of the request. * @param method the new method * @return this builder */ Builder method(HttpMethod method); /** * Set the URI of the request. * @param uri the new URI * @return this builder */ Builder uri(URI uri); /** * Add the given header value(s) under the given name. * @param headerName the header name * @param headerValues the header value(s) * @return this builder * @see HttpHeaders#add(String, String) */ Builder header(String headerName, String... headerValues); /** * Manipulate this request's headers with the given consumer. * <p>The headers provided to the consumer are "live", so that the consumer can be used to * {@linkplain HttpHeaders#set(String, String) overwrite} existing header values, * {@linkplain HttpHeaders#remove(Object) remove} values, or use any of the other * {@link HttpHeaders} methods. * @param headersConsumer a function that consumes the {@code HttpHeaders} * @return this builder */ Builder headers(Consumer<HttpHeaders> headersConsumer); /** * Add a cookie with the given name and value(s). * @param name the cookie name * @param values the cookie value(s) * @return this builder */ Builder cookie(String name, String... values); /** * Manipulate this request's cookies with the given consumer. * <p>The map provided to the consumer is "live", so that the consumer can be used to * {@linkplain MultiValueMap#set(Object, Object) overwrite} existing cookies, * {@linkplain MultiValueMap#remove(Object) remove} cookies, or use any of the other * {@link MultiValueMap} methods. * @param cookiesConsumer a function that consumes the cookies map * @return this builder */ Builder cookies(Consumer<MultiValueMap<String, Cookie>> cookiesConsumer); /** * Set the body of the request. * <p>Calling this methods will * {@linkplain org.springframework.core.io.buffer.DataBufferUtils#release(DataBuffer) release} * the existing body of the builder. * @param body the new body * @return this builder */ Builder body(byte[] body); /** * Set the body of the request to the UTF-8 encoded bytes of the given string. * <p>Calling this methods will * {@linkplain org.springframework.core.io.buffer.DataBufferUtils#release(DataBuffer) release} * the existing body of the builder. * @param body the new body * @return this builder */ Builder body(String body); /** * Add an attribute with the given name and value. * @param name the attribute name * @param value the attribute value * @return this builder */ Builder attribute(String name, Object value); /** * Manipulate this request's attributes with the given consumer. * <p>The map provided to the consumer is "live", so that the consumer can be used * to {@linkplain Map#put(Object, Object) overwrite} existing attributes, * {@linkplain Map#remove(Object) remove} attributes, or use any of the other * {@link Map} methods. * @param attributesConsumer a function that consumes the attributes map * @return this builder */ Builder attributes(Consumer<Map<String, Object>> attributesConsumer); /** * Add a parameter with the given name and value. * @param name the parameter name * @param values the parameter value(s) * @return this builder */ Builder param(String name, String... values); /** * Manipulate this request's parameters with the given consumer. * <p>The map provided to the consumer is "live", so that the consumer can be used to * {@linkplain MultiValueMap#set(Object, Object) overwrite} existing cookies, * {@linkplain MultiValueMap#remove(Object) remove} cookies, or use any of the other * {@link MultiValueMap} methods. * @param paramsConsumer a function that consumes the parameters map * @return this builder */ Builder params(Consumer<MultiValueMap<String, String>> paramsConsumer); /** * Set the remote address of the request. * @param remoteAddress the remote address * @return this builder */ Builder remoteAddress(InetSocketAddress remoteAddress); /** * Build the request. * @return the built request */ ServerRequest build(); } }
package com.g74.rollersplat.controller.states; import com.g74.rollersplat.controller.command.StateController; import com.g74.rollersplat.viewer.game.WinViewer; import com.g74.rollersplat.viewer.gui.GUI; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import java.io.IOException; import static org.junit.jupiter.api.Assertions.*; public class LosingStateTest { private GUI gui; private StateController controller; private LosingState losestate; @BeforeEach void setUp() throws IOException { gui = Mockito.mock(GUI.class); controller = new StateController(gui); losestate = new LosingState(gui); } @Test void run() throws IOException, InterruptedException { int result =losestate.run(controller); assertEquals(1,controller.getLevelNum()); assertEquals(0, result); result = losestate.run(controller); assertEquals(1,controller.getLevelNum()); assertEquals(0, result); } @Test void setState(){ losestate.setState(GUI.POSITION.NONE, controller); assertTrue(controller.getState() instanceof PlayingState); } }