text
stringlengths
10
2.72M
package com.tencent.mm.app; import android.os.Bundle; import com.tencent.mm.splash.SplashFallbackActivity; public class WeChatSplashFallbackActivity extends SplashFallbackActivity { protected void onCreate(Bundle bundle) { super.onCreate(bundle); setContentView(2130905065); } }
import java.util.Scanner; public class ConstructPyramid { public static void main(String[] args) { Scanner scanner=new Scanner(System.in); System.out.print("Give Pyramid Level:"); Integer input=scanner.nextInt(); Integer n=2,num; for (int i=0;i<input;i++){ System.out.println(); for (int blank=0;blank<input-i-1;blank++) System.out.print(" "); for (int j=0;j<=i;j++){ num=n*(2*n-1); n+=2; int numSpaces=getDigitCount(num); if (numSpaces<5){ while(numSpaces!=5){ System.out.print("0"); numSpaces++; } } System.out.print(num); if (j<i) System.out.print(" "); } } } private static int getDigitCount(Integer num) { int count=0; while(num!=0){ num/=10; count++; } return count; } }
package device.linux.instamsg; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import common.instamsg.driver.DataLogger; import common.instamsg.driver.FileUtils; import common.instamsg.driver.Log; import config.DeviceConstants; public class DeviceDataLogger extends DataLogger { String DATA_FILE_NAME = DeviceConstants.SENSEGROW_FOLDER + "data.txt"; /** * This method initializes the data-logger-interface for the device. */ public void initDataLogger() { } /** * This method saves the record on the device. * * If and when the device-storage becomes full, the device MUST delete the oldest record, and instead replace * it with the current record. That way, we will maintain a rolling-data-logger. */ public void saveRecordToPersistentStorage(String record) { FileUtils.appendLine(DATA_LOGGING_ERROR, DATA_FILE_NAME, record); } /** * The method returns the next available record. * If a record is available, following must be done :: * * 1) * The record must be deleted from the storage-medium (so as not to duplicate-fetch this record later). * * 2) * Then actually return the record. * * Obviously, there is a rare chance that step 1) is finished, but step 2) could not run to completion. * That would result in a data-loss, but we are ok with it, because we don't want to send duplicate-records to InstaMsg-Server. * * We could have done step 2) first and then step 1), but in that scenario, we could have landed in a scenario where step 2) * was done but step 1) could not be completed. That could have caused duplicate-data on InstaMsg-Server, but we don't want * that. * * * One of the following statuses must be returned :: * * a) * SUCCESS, if a record is successfully returned. * * b) * FAILURE, if no record is available. */ public String getNextRecordFromPersistentStorage() { String data = null; String temp = null; BufferedReader configReader = null; try { configReader = new BufferedReader(new FileReader(DATA_FILE_NAME)); } catch (FileNotFoundException e) { Log.errorLog(DATA_LOGGING_ERROR + "Data file [" + DATA_FILE_NAME + "] does not exist."); return null; } FileUtils.createEmptyFile(DATA_LOGGING_ERROR, FileUtils.TEMP_FILE_NAME); boolean lineRead = false; while(true) { try { temp = configReader.readLine(); } catch (IOException e) { Log.errorLog(DATA_LOGGING_ERROR + "Error occurred while reading config .. not continuing .."); FileUtils.cleanFileReader(DATA_LOGGING_ERROR, configReader); return null; } if(temp != null) { if(temp.length() > 0) { if(lineRead == false) { data = temp; lineRead = true; } else { FileUtils.appendLine(DATA_LOGGING_ERROR, FileUtils.TEMP_FILE_NAME, temp); } } else { break; } } else { break; } } FileUtils.cleanFileReader(DATA_LOGGING_ERROR, configReader); new File(FileUtils.TEMP_FILE_NAME).renameTo(new File(DATA_FILE_NAME)); return data; } }
import java.util.TreeMap; public class bai_2 { public static void main(String[] args) { TreeMap<Integer, Integer> tree = new TreeMap<>(); System.out.println(order(tree, 2, 0, 0)); System.out.println(order(tree, 1, 20, 14)); System.out.println(order(tree, 1, 30, 3)); System.out.println(order(tree, 2, 0, 0)); System.out.println(order(tree, 1, 10, 99)); System.out.println(order(tree, 3, 0, 0)); System.out.println(order(tree, 2, 0, 0)); System.out.println(order(tree, 2, 0, 0)); System.out.println(order(tree, 0, 0, 0)); } public static String order(TreeMap<Integer, Integer> tree, int choice, int id, int order) { String result; switch (choice) { case 1: tree.put(order, id); result = "Guest " + id + " add to queue"; break; case 2: if (!tree.isEmpty()) { result = "Serve first guest: " + tree.firstEntry().getValue(); tree.remove(tree.firstKey()); } else return "No guest in queue"; break; case 3: if (!tree.isEmpty()) { result = "Serve last guest: "+ tree.lastEntry().getValue(); tree.remove(tree.lastKey()); } else return "No guest in queue"; break; default: return "0"; } return result; } }
package com.smartwerkz.bytecode.classfile; import java.io.DataInputStream; import java.io.IOException; /** * <pre> * CONSTANT_Fieldref_info { * u1 tag; * u2 class_index; * u2 name_and_type_index; * } * </pre> * * @author mhaller */ public class ConstantMethodrefInfo { private int classIndex; private int nameAndTypeIndex; public ConstantMethodrefInfo(DataInputStream dis) throws IOException { classIndex = dis.readUnsignedShort(); nameAndTypeIndex = dis.readUnsignedShort(); } @Override public String toString() { return "Class->"+classIndex + " Method->"+nameAndTypeIndex; } public int getClassIndex() { return classIndex; } public int getNameAndTypeIndex() { return nameAndTypeIndex; } }
package stopThatFire.gameComponents; import java.awt.Graphics2D; import java.awt.geom.AffineTransform; import java.util.ArrayList; import stopThatFire.game.GameGUI; import stopThatFire.game.GameGUI.Graphic; import stopThatFire.utils.Pos; import stopThatFire.utils.Size; public class Drawable extends Box2D { public final static int DRAWABLE_zindexIntervalH = 1000; public final static String DRAWABLE_textureDefault = "none"; private static ArrayList<Drawable> drawables = new ArrayList<Drawable>(); private float zindex; private String texture; //------ Constructors Drawable ------// public Drawable() { super(); this.zindex = 0; this.texture = DRAWABLE_textureDefault; } public Drawable(Pos pos, Size size, String texture, float zindex) { super(pos, size); this.zindex = zindex; this.texture = texture; } //------ Getters/Setters Drawable ------// public float getZindex() {return this.zindex;} public void setZindex(float zindex) {this.zindex = zindex;} public float getZ() {return this.zindex*DRAWABLE_zindexIntervalH + this.pos.y;} public String getTexture() {return this.texture;} public void setTexture(String texture) {this.texture = texture;} public static ArrayList<Drawable> getDrawables() {return drawables;} //------ Methods Drawable ------// //partition function of quickSort() private static int partition(ArrayList<Drawable> array, int begin, int end) { int pivot = end; int counter = begin; for (int i = begin; i < end; i++) { if (array.get(i).getZ() <= array.get(pivot).getZ()) { Drawable temp = array.get(counter); array.set(counter, array.get(i)); array.set(i, temp); counter++; } } Drawable temp = array.get(pivot); array.set(pivot, array.get(counter)); array.set(counter, temp); return counter; } //sort [ArrayList<Drawable>] according to element's zIndex private static void quickSort(ArrayList<Drawable> array, int begin, int end) { if (end < begin) return; int pivot = partition(array, begin, end); quickSort(array, begin, pivot-1); quickSort(array, pivot+1, end); } //add this [Drawable] to [ArrayList<Drawable>], this list will be used to draw all Drawable when repaint() will be call public void draw() { Drawable.drawables.add(this); } //apply sort on [ArrayList<Drawable>] according to element's zIndex public static void applyZindex() { quickSort(Drawable.drawables, 0, Drawable.drawables.size()-1); } //draw this [Drawable] on screen public void drawApply(Graphic g, Graphics2D g2d, GameGUI window) { Drawable drawable = (Drawable)this; AffineTransform transform = new AffineTransform(); transform.translate(drawable.getPos().x-drawable.getSize().w/2, drawable.getPos().y-drawable.getSize().h/2); transform.scale(drawable.getSize().w/window.getTextures().get(drawable.getTexture()).getWidth(), drawable.getSize().h/window.getTextures().get(drawable.getTexture()).getHeight()); g2d.drawImage(window.getTextures().get(drawable.getTexture()), transform, g); } }
package com.FCI.SWE.Services; import static org.testng.Assert.assertEquals; import javax.ws.rs.FormParam; import javax.ws.rs.POST; import javax.ws.rs.Path; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import org.testng.annotations.Test; import com.FCI.SWE.Models.Page; import com.FCI.SWE.Models.UserEntity; import com.FCI.SWE.Services.Service; public class ServiceTest { Service serv = new Service(); /*** Passed ***/ @Test public void addAllFriendRequestsService() throws ParseException { String test = serv.addAllFriendRequestsService("b"); JSONParser parser = new JSONParser(); Object obj = parser.parse(test); JSONObject object = (JSONObject) obj; boolean ok = false; String requestResponse = "All users those sent you request became friends with you now\n" + " congrats ya user ya zeft 7abibi :D \n " + "in-shaa-el-Allah el phase gaya ha5alek te5tar el sadek ely enta bet7ebo :DxD "; if (object.get("requestResponse").equals(requestResponse)); ok = true; assertEquals( ok , true); ///Not exist user test = serv.addAllFriendRequestsService("notExist"); parser = new JSONParser(); obj = parser.parse(test); object = (JSONObject) obj; ok = false; if (object.get("requestResponse").equals("Failed")); ok = true; assertEquals( ok , true); } /***Failed***/ ///as not totaly implemented @Test public void createPostService() { } /*** Passed ***/ @Test public void loginService() throws ParseException { String test = serv.loginService("a" , "WrongPass"); JSONParser parser = new JSONParser(); Object obj = parser.parse(test); JSONObject object = (JSONObject) obj; assertEquals( object.get("Status") , "Failed"); test = serv.loginService("" , ""); parser = new JSONParser(); obj = parser.parse(test); object = (JSONObject) obj; assertEquals( object.get("Status") , "Failed"); test = serv.loginService("a" , "a"); parser = new JSONParser(); obj = parser.parse(test); object = (JSONObject) obj; assertEquals( object.get("Status") , "OK"); } /*** Passed ***/ @Test public void registrationService() throws ParseException { String test = serv.registrationService("a" , "a" , "a"); JSONParser parser = new JSONParser(); Object obj = parser.parse(test); JSONObject object = (JSONObject) obj; assertEquals( object.get("Status") , "Failed"); test = serv.registrationService("a" , "validEmail" , "a"); parser = new JSONParser(); obj = parser.parse(test); object = (JSONObject) obj; assertEquals( object.get("Status") , "OK"); test = serv.registrationService("" , "" , ""); parser = new JSONParser(); obj = parser.parse(test); object = (JSONObject) obj; assertEquals( object.get("Status") , "Failed"); } /*** Passed ***/ @Test public void sendFriendRequestService() throws ParseException { String isFriends = "Request denied as you are actually friends"; String done = "Request has been sent successfully ya user ya 7abibi ^__^ :D "; String notFound = "Request denied as this user not found ."; String addUrSelf = "Request denied as you can`t add yourself ."; String test = serv.sendFriendRequestService("a" , "a"); JSONParser parser = new JSONParser(); Object obj = parser.parse(test); JSONObject object = (JSONObject) obj; assertEquals( object.get("requestResponse") , addUrSelf); test = serv.sendFriendRequestService("a" , "b"); parser = new JSONParser(); obj = parser.parse(test); object = (JSONObject) obj; assertEquals( object.get("requestResponse") , isFriends); test = serv.sendFriendRequestService("a" , "osama"); parser = new JSONParser(); obj = parser.parse(test); object = (JSONObject) obj; assertEquals( object.get("requestResponse") , done); test = serv.sendFriendRequestService("a" , "notExistUser"); parser = new JSONParser(); obj = parser.parse(test); object = (JSONObject) obj; assertEquals( object.get("requestResponse") , notFound); } /*** Passed ***/ @Test public void sendNewMessageService() throws ParseException { String toURself = "Request denied as you can`t send message to yourself ."; String notFound = "Request denied as this user not found ."; String notFriends = "Request denied as you are not friends"; String done = "Request has been sent successfully"; String test = serv.sendNewMessageService("a" , "a" , "message1"); JSONParser parser = new JSONParser(); Object obj = parser.parse(test); JSONObject object = (JSONObject) obj; assertEquals( object.get("requestResponse") , toURself); test = serv.sendNewMessageService("a" , "notExistUSer" , "message2"); parser = new JSONParser(); obj = parser.parse(test); object = (JSONObject) obj; assertEquals( object.get("requestResponse") , notFound); test = serv.sendNewMessageService("a" , "osama" , "message3"); parser = new JSONParser(); obj = parser.parse(test); object = (JSONObject) obj; assertEquals( object.get("requestResponse") , notFriends); test = serv.sendNewMessageService("a" , "b" , "message4"); parser = new JSONParser(); obj = parser.parse(test); object = (JSONObject) obj; assertEquals( object.get("requestResponse") , done); } /*** Failed ***/ /// not implemented yet @Test public void showUserTimelineService() { } }
package com.facebook.react.flat; import com.facebook.react.uimanager.LayoutShadowNode; import com.facebook.react.uimanager.ReactShadowNode; import com.facebook.react.views.textinput.ReactTextInputManager; public class RCTTextInputManager extends ReactTextInputManager { public RCTTextInput createShadowNodeInstance() { return new RCTTextInput(); } public Class<RCTTextInput> getShadowNodeClass() { return RCTTextInput.class; } } /* Location: C:\Users\august\Desktop\tik\df_rn_kit\classes.jar.jar!\com\facebook\react\flat\RCTTextInputManager.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
/* * Have worker as food running away from you and they will sence you when you are 5 tiles away from them, they will also drop bombs on a random generated number from 1- 50 every tile they travel and if the number maches with the set number they will drop it, and the bomb will go after 3 seconds and does nothing or go when the snake head enters the same tile. And stun you for 2 seconds. Also safe zone if we get there. Homework for Alex - get image for workers - get image for bombs V - get sounds for events - drop bomb - bomb explode - eating - game end - game start - background music - grid shrink - think about worker movement - randomly drop bombs (need ArralyList for bombs, and way yo create them - draw bombs in paint method - think about score - think about thinking - think about Mr. Lawrence being unhappy when you are not assertive and doing work - design menu - think about drawing snake a different, more exciting way - think about difficult progression... */ package snakez; import audio.AudioPlayer; import environment.Environment; import grid.Grid; import images.ResourceTools; import java.awt.Color; import java.awt.Graphics; import java.awt.Image; import java.awt.Point; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.util.ArrayList; /** * * @author alextsai */ class Forest extends Environment implements MoveValidatorIntf, CellDataProviderIntf { private Grid grid; private Cobra hydra; private Image forest; private ArrayList<GridItem> workers; private ArrayList<GridItem> bombs; public Forest() { this.setBackground(ResourceTools.loadImageFromResource("snakez/mumbai.png")); forest = ResourceTools.loadImageFromResource("snakez/forest.jpg"); grid = new Grid(50, 30, 20, 20, new Point(10, 50), Color.BLACK); // grid.setPosition(new Point((this.getWidth() - this.getGridWidth())/2, (this.getHeight() - this.getGridHeigth())/2)); hydra = new Cobra(Direction.RIGHT, grid, this); workers = new ArrayList<>(); // workers.add(new GridItem()); } @Override public void initializeEnvironment() { } int counter; int moveDelay = 0; int moveDelayLimit = 1; int workerTimer = 0; int workerTimerLimit = 30; int workerLimit = 15; @Override public void timerTaskHandler() { if (hydra != null) { if (moveDelay >= moveDelayLimit) { hydra.move(); moveDelay = 0; } else { moveDelay++; } } if (grid != null) { if (workerTimer < workerTimerLimit) { workerTimer++; } else if (!hydra.isStopped()) { workers.add(new GridItem(getRandomBoundaryPoint(), GridItem.ITEM_TYPE_WORKER, this)); //if we reach the worker limit, then shrink grid and reset workers (eliminate them) if (workers.size() >= workerLimit) { grid.setColumns(grid.getColumns() - 1); grid.setRows(grid.getRows() - 1); grid.setPosition(new Point((this.getWidth() - this.getGridWidth()) / 2, (this.getHeight() - this.getGridHeigth()) / 2)); workers.clear(); } workerTimer = 0; } } } private Point getRandomBoundaryPoint() { double random = Math.random(); int x, y; if (random <= .25) { // scenario #1 left column of grid x = 0; y = (int) (Math.random() * grid.getRows()); } else if (random <= .5) { // scenario #2 rightmost column of grid x = grid.getColumns() - 1; y = (int) (Math.random() * grid.getRows()); } else if (random <= .75) { // scenario #3 top row of grid x = (int) (Math.random() * grid.getColumns()); y = 0; } else { // scenario #4 bottom row of grid x = (int) (Math.random() * grid.getColumns()); y = grid.getRows() - 1; } return new Point(x, y); } @Override public void keyPressedHandler(KeyEvent e) { // System.out.println("Key Event" + e.getKeyChar()); // System.out.println("Key Event" + e.getKeyCode()); if (e.getKeyCode() == KeyEvent.VK_LEFT) { hydra.setDirection(Direction.LEFT); hydra.move(); } else if (e.getKeyCode() == KeyEvent.VK_UP) { hydra.setDirection(Direction.UP); hydra.move(); } else if (e.getKeyCode() == KeyEvent.VK_RIGHT) { hydra.setDirection(Direction.RIGHT); hydra.move(); } else if (e.getKeyCode() == KeyEvent.VK_DOWN) { hydra.setDirection(Direction.DOWN); hydra.move(); } else if (e.getKeyCode() == KeyEvent.VK_SPACE) { AudioPlayer.play("/snakez/mp5_smg.wav"); } } @Override public void keyReleasedHandler(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_A) { System.out.println("Realse LEFT!!!!!"); } else if (e.getKeyCode() == KeyEvent.VK_W) { System.out.println("Realse UP!!!!!"); } else if (e.getKeyCode() == KeyEvent.VK_D) { System.out.println("Realse RIGHT!!!!!"); } else if (e.getKeyCode() == KeyEvent.VK_S) { System.out.println("Realse Down!!!!!"); } else if (e.getKeyCode() == KeyEvent.VK_P) { System.out.println("PAUSED!!!!!"); hydra.stop(); } else if (e.getKeyCode() == KeyEvent.VK_G) { System.out.println("GO!!!!!"); hydra.go(); } } @Override public void environmentMouseClicked(MouseEvent e) { System.out.println("mouse clicked at " + e.getPoint()); System.out.println("mouse clicked in cell" + grid.getCellLocationFromSystemCoordinate(e.getPoint())); } private int getGridHeigth() { return grid.getCellHeight() * grid.getRows(); } private int getGridWidth() { return grid.getCellWidth() * grid.getColumns(); } @Override public void paintEnvironment(Graphics graphics) { if (forest != null) { graphics.drawImage(forest, grid.getPosition().x, grid.getPosition().y, getGridWidth(), getGridHeigth(), this); } if (grid != null) { grid.paintComponent(graphics); } if (hydra != null) { hydra.draw(graphics); } if (workers != null) { for (GridItem worker : workers) { worker.draw(graphics); } } } //<editor-fold defaultstate="collapsed" desc="MoveValidatorIntf Methods"> @Override public Point validateMove(Point proposedLocation) { if (proposedLocation.x < 0) { hydra.stop(); System.out.println("Game Over"); } else if (proposedLocation.y < 0) { hydra.stop(); System.out.println("Game Over"); } else if (proposedLocation.x > grid.getColumns()) { hydra.stop(); System.out.println("Game Over"); } else if (proposedLocation.y > grid.getRows()) { hydra.stop(); System.out.println("Game Over"); } return proposedLocation; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="CellDataProviderIntf Methods"> @Override public int getCellWidth() { return grid.getCellWidth(); } @Override public int getCellHeight() { return grid.getCellHeight(); } @Override public int getSystemCoordX(int x, int y) { return grid.getCellSystemCoordinate(x, y).x; } @Override public int getSystemCoordY(int x, int y) { return grid.getCellSystemCoordinate(x, y).y; } //</editor-fold> }
/** * Copyright (c) 2013 Johannes Dillmann, Zuse Institute Berlin * * Licensed under the BSD License, see LICENSE file for details. * */ package org.xtreemfs.dir; import java.io.IOException; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.Map.Entry; import java.util.SortedMap; import java.util.TreeMap; import org.xtreemfs.babudb.BabuDBFactory; import org.xtreemfs.babudb.api.database.Database; import org.xtreemfs.babudb.api.database.ResultSet; import org.xtreemfs.babudb.api.exception.BabuDBException; import org.xtreemfs.common.HeartbeatThread; import org.xtreemfs.common.config.ServiceConfig; import org.xtreemfs.common.statusserver.StatusServerHelper; import org.xtreemfs.common.statusserver.StatusServerModule; import org.xtreemfs.dir.data.AddressMappingRecord; import org.xtreemfs.dir.data.AddressMappingRecords; import org.xtreemfs.dir.data.ConfigurationRecord; import org.xtreemfs.dir.data.ServiceRecord; import org.xtreemfs.foundation.VersionManagement; import org.xtreemfs.foundation.buffer.BufferPool; import org.xtreemfs.foundation.buffer.ReusableBuffer; import org.xtreemfs.foundation.logging.Logging; import org.xtreemfs.foundation.util.OutputUtils; import org.xtreemfs.osd.vivaldi.VivaldiNode; import org.xtreemfs.pbrpc.generatedinterfaces.DIR.ServiceStatus; import org.xtreemfs.pbrpc.generatedinterfaces.DIR.ServiceType; import org.xtreemfs.pbrpc.generatedinterfaces.DIRServiceConstants; import org.xtreemfs.pbrpc.generatedinterfaces.GlobalTypes.KeyValuePair; import org.xtreemfs.pbrpc.generatedinterfaces.GlobalTypes.VivaldiCoordinates; import com.sun.net.httpserver.HttpExchange; /** * Serves a simple HTML status page with DIR stats. */ public class StatusPage extends StatusServerModule { private DIRRequestDispatcher master; private final DIRConfig config; private final String statusPageTemplate; /** * Time after a service, which has not send a heartbeat signal, will be displayed as not available * (default: 10 min). */ private final static int SERVICE_TIMEOUT = 600000; private enum Vars { MAXMEM("<!-- $MAXMEM -->"), FREEMEM("<!-- $FREEMEM -->"), AVAILPROCS("<!-- $AVAILPROCS -->"), BPSTATS("<!-- $BPSTATS -->"), PORT("<!-- $PORT -->"), DEBUG("<!-- $DEBUG -->"), NUMCON("<!-- $NUMCON -->"), PINKYQ("<!-- $PINKYQ -->"), NUMREQS("<!-- $NUMREQS -->"), TIME("<!-- $TIME -->"), TABLEDUMP("<!-- $TABLEDUMP -->"), PROTOVERSION("<!-- $PROTOVERSION -->"), VERSION("<!-- $VERSION -->"), DBVERSION("<!-- $DBVERSION -->"); private String template; Vars(String template) { this.template = template; } public String toString() { return template; } }; public StatusPage(DIRConfig config) { StringBuffer sb = StatusServerHelper.readTemplate("org/xtreemfs/dir/templates/status.html"); if (sb == null) { statusPageTemplate = "<h1>Template was not found, unable to show status page!</h1>"; } else { statusPageTemplate = sb.toString(); } this.config = config; } @Override public String getDisplayName() { return "DIR Status Summary"; } @Override public String getUriPath() { return "/"; } @Override public boolean isAvailableForService(ServiceType service) { return service == ServiceType.SERVICE_TYPE_DIR; } @Override public void initialize(ServiceType service, Object serviceRequestDispatcher) { assert (service == ServiceType.SERVICE_TYPE_DIR); master = (DIRRequestDispatcher) serviceRequestDispatcher; } @Override public void shutdown() { } @Override public void handle(HttpExchange httpExchange) throws IOException { ResultSet<byte[], byte[]> addrMapsIter = null; ResultSet<byte[], byte[]> servRegIter = null; ResultSet<byte[], byte[]> confIter = null; try { // NOTE(jdillmann): Access to the database is not synchronized. This might result in reading stale data. final Database database = master.getDirDatabase(); assert (statusPageTemplate != null); long time = System.currentTimeMillis(); addrMapsIter = database.prefixLookup(DIRRequestDispatcher.INDEX_ID_ADDRMAPS, new byte[0], null).get(); StringBuilder dump = new StringBuilder(); dump.append("<br><table width=\"100%\" frame=\"box\"><td colspan=\"2\" class=\"heading\">Address Mapping</td>"); dump.append("<tr><td class=\"dumpTitle\">UUID</td><td class=\"dumpTitle\">mapping</td></tr>"); while (addrMapsIter.hasNext()) { Entry<byte[], byte[]> e = addrMapsIter.next(); AddressMappingRecords ams = new AddressMappingRecords(ReusableBuffer.wrap(e.getValue())); final String uuid = new String(e.getKey()); dump.append("<tr><td class=\"uuid\">"); dump.append(uuid); dump.append("</td><td class=\"dump\"><table width=\"100%\"><tr>"); dump.append("<tr><td><table width=\"100%\">"); long version = 0; for (AddressMappingRecord am : ams.getRecords()) { dump.append("<tr><td class=\"mapping\">"); String endpoint = am.getUri() + " (" + am.getProtocol() + "," + am.getAddress() + "," + am.getPort() + ")"; dump.append(endpoint); dump.append("</td><td class=\"mapping\">"); dump.append(am.getMatch_network()); dump.append("</td><td class=\"mapping\">"); dump.append(am.getTtl_s()); dump.append("</td></tr>"); version = am.getVersion(); } dump.append("</table></td></tr>"); dump.append("<td class=\"version\">version: <b>"); dump.append(version); dump.append("</b></td></tr></table>"); } dump.append("</td></tr></table>"); addrMapsIter.free(); servRegIter = database.prefixLookup(DIRRequestDispatcher.INDEX_ID_SERVREG, new byte[0], null).get(); dump.append("<br><table width=\"100%\" frame=\"box\"><td colspan=\"2\" class=\"heading\">Service Registry</td>"); dump.append("<tr><td class=\"dumpTitle\">UUID</td><td class=\"dumpTitle\">mapping</td></tr>"); while (servRegIter.hasNext()) { Entry<byte[], byte[]> e = servRegIter.next(); final String uuid = new String(e.getKey()); final ServiceRecord sreg = new ServiceRecord(ReusableBuffer.wrap(e.getValue())); dump.append("<tr><td class=\"uuid\">"); dump.append(uuid); dump.append("</td><td class=\"dump\"><table width=\"100%\">"); dump.append("<tr><td width=\"30%\">"); dump.append("type"); dump.append("</td><td><b>"); dump.append(sreg.getType()); dump.append("</b></td></tr>"); dump.append("<tr><td width=\"30%\">"); dump.append("name"); dump.append("</td><td><b>"); dump.append(sreg.getName()); dump.append("</b></td></tr>"); // sort the set of entries SortedMap<String, String> sMap = new TreeMap<String, String>(); for (Entry<String, String> entry : sreg.getData().entrySet()) sMap.put(entry.getKey(), entry.getValue()); for (Entry<String, String> dataEntry : sMap.entrySet()) { dump.append("<tr><td width=\"30%\">"); dump.append(dataEntry.getKey()); dump.append("</td><td><b>"); if (dataEntry.getKey().equals("status_page_url")) { dump.append("<a href=\""); dump.append(dataEntry.getValue()); dump.append("\">"); } if (!dataEntry.getKey().equals(HeartbeatThread.STATUS_ATTR)) { dump.append(dataEntry.getValue()); } if (dataEntry.getKey().equals("status_page_url")) { dump.append("</a>"); } else if (dataEntry.getKey().equals("last_updated")) { } else if (dataEntry.getKey().equals(HeartbeatThread.STATUS_ATTR)) { ServiceStatus status = ServiceStatus.valueOf(Integer.valueOf(dataEntry.getValue())); switch (status) { case SERVICE_STATUS_AVAIL: dump.append("online (new files will be assigned to it)"); break; case SERVICE_STATUS_TO_BE_REMOVED: dump.append("locked (new files will not be assigned to it)"); break; case SERVICE_STATUS_REMOVED: dump.append("removed (replicas assigned to this OSD will be replaced)"); break; } } else if (dataEntry.getKey().equals("free") || dataEntry.getKey().equals("total") || dataEntry.getKey().endsWith("RAM") || dataEntry.getKey().equals("used")) { dump.append(" bytes ("); dump.append(OutputUtils.formatBytes(Long.parseLong(dataEntry.getValue()))); dump.append(")"); } else if (dataEntry.getKey().equals("load")) { dump.append("%"); } else if (dataEntry.getKey().equals("vivaldi_coordinates")) { final VivaldiCoordinates coord = VivaldiNode.stringToCoordinates(dataEntry.getValue()); dump.append(" ("); dump.append(coord.getXCoordinate()); dump.append(","); dump.append(coord.getYCoordinate()); dump.append(" err "); dump.append(coord.getLocalError()); dump.append(")"); } dump.append("</b></td></tr>"); } dump.append("<tr><td width=\"30%\">"); dump.append("last updated"); dump.append("</td><td><b>"); dump.append(sreg.getLast_updated_s()); if (sreg.getLast_updated_s() == 0) { dump.append(" (service was shutdown)"); } else { dump.append(" ("); Date lastUpdatedDate = new Date(sreg.getLast_updated_s() * 1000); dump.append(lastUpdatedDate); // check timeout only for MRCs and OSDs if (sreg.getType() == ServiceType.SERVICE_TYPE_MRC || sreg.getType() == ServiceType.SERVICE_TYPE_OSD) { long lastUpdateDateTime = lastUpdatedDate.getTime(); if (lastUpdateDateTime < (System.currentTimeMillis() - SERVICE_TIMEOUT)) { dump.append(", that's "); dump.append(OutputUtils.SecondsToString((System.currentTimeMillis() - lastUpdateDateTime) / 1000)); dump.append(" ago. Please check connectivity of the server"); } } dump.append(")"); dump.append("</b></td></tr>"); } dump.append("<td></td><td class=\"version\">version: <b>"); dump.append(sreg.getVersion()); dump.append("</b></td></table></td></tr>"); } dump.append("</td></tr></table>"); servRegIter.free(); // Configuration part confIter = database.prefixLookup(DIRRequestDispatcher.INDEX_ID_CONFIGURATIONS, new byte[0], null).get(); dump.append("<br><table width=\"100%\" frame=\"box\"><td colspan=\"2\" class=\"heading\">Configurations</td>"); dump.append("<tr><td class=\"dumpTitle\">UUID</td><td class=\"dumpTitle\">Configuration Parameter</td></tr>"); while (confIter.hasNext()) { Entry<byte[], byte[]> e = confIter.next(); final String uuid = new String(e.getKey()); final ConfigurationRecord conf = new ConfigurationRecord(ReusableBuffer.wrap(e.getValue())); dump.append("<tr><td class=\"uuid\">"); dump.append(uuid); dump.append("</td><td class=\"dump\"><table width=\"100%\">"); Collections.sort(conf.getData(), new Comparator<KeyValuePair>() { public int compare(KeyValuePair o1, KeyValuePair o2) { return o1.getKey().compareTo(o2.getKey()); } }); for (KeyValuePair kvp : conf.getData()) { dump.append("<tr><td width=\"30%\">"); dump.append(kvp.getKey()); dump.append("</td><td><b>"); dump.append(kvp.getKey().equals(ServiceConfig.Parameter.ADMIN_PASSWORD.getPropertyString()) || kvp.getKey().equals(ServiceConfig.Parameter.CAPABILITY_SECRET.getPropertyString()) || kvp.getKey() .equals(ServiceConfig.Parameter.SERVICE_CREDS_PASSPHRASE.getPropertyString()) || kvp.getKey() .equals(ServiceConfig.Parameter.TRUSTED_CERTS_PASSPHRASE.getPropertyString()) ? "*******" : kvp.getValue()); dump.append("</b></td></tr>"); } dump.append("<td></td><td class=\"version\">version: <b>"); dump.append(conf.getVersion()); dump.append("</b></td></table></td></tr>"); } confIter.free(); dump.append("</b></td></table></td></tr>"); dump.append("</table>"); String tmp = null; try { tmp = statusPageTemplate.replace(Vars.AVAILPROCS.toString(), Runtime.getRuntime().availableProcessors() + " bytes"); } catch (Exception e) { tmp = statusPageTemplate; } tmp = tmp.replace(Vars.FREEMEM.toString(), Runtime.getRuntime().freeMemory() + " bytes"); tmp = tmp.replace(Vars.MAXMEM.toString(), Runtime.getRuntime().maxMemory() + " bytes"); tmp = tmp.replace(Vars.BPSTATS.toString(), BufferPool.getStatus()); tmp = tmp.replace(Vars.PORT.toString(), Integer.toString(config.getPort())); tmp = tmp.replace(Vars.DEBUG.toString(), Integer.toString(config.getDebugLevel())); tmp = tmp.replace(Vars.NUMCON.toString(), Integer.toString(master.getNumConnections())); tmp = tmp.replace(Vars.NUMREQS.toString(), Long.toString(master.getNumRequests())); tmp = tmp.replace(Vars.TIME.toString(), new Date(time).toString() + " (" + time + ")"); tmp = tmp.replace(Vars.TABLEDUMP.toString(), dump.toString()); tmp = tmp.replace(Vars.VERSION.toString(), VersionManagement.RELEASE_VERSION); tmp = tmp.replace(Vars.PROTOVERSION.toString(), Integer.toString(DIRServiceConstants.INTERFACE_ID)); tmp = tmp.replace(Vars.DBVERSION.toString(), BabuDBFactory.BABUDB_VERSION); sendResponse(httpExchange, tmp); } catch (BabuDBException ex) { Logging.logError(Logging.LEVEL_WARN, (Object) null, ex); httpExchange.sendResponseHeaders(500, 0); } finally { httpExchange.close(); if (addrMapsIter != null) { addrMapsIter.free(); } if (servRegIter != null) { servRegIter.free(); } if (confIter != null) { confIter.free(); } } } }
package com.jasoftsolutions.mikhuna.model; import com.google.gson.annotations.SerializedName; import java.io.Serializable; /** * Created by pc07 on 03/04/2014. */ public class AbstractModel implements Serializable { @SerializedName("__id__") private Long id; @SerializedName("id") private Long serverId; @SerializedName("lu") private Long lastUpdate; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getServerId() { return serverId; } public void setServerId(Long serverId) { this.serverId = serverId; } public Long getLastUpdate() { return lastUpdate; } public void setLastUpdate(Long lastUpdate) { this.lastUpdate = lastUpdate; } }
package com.tencent.mm.plugin.aa.ui; import android.text.Editable; import android.text.TextWatcher; import com.tencent.mm.sdk.platformtools.bi; protected class LaunchAAByPersonAmountSelectUI$c implements TextWatcher { final /* synthetic */ LaunchAAByPersonAmountSelectUI eDf; String username; public LaunchAAByPersonAmountSelectUI$c(LaunchAAByPersonAmountSelectUI launchAAByPersonAmountSelectUI, String str) { this.eDf = launchAAByPersonAmountSelectUI; this.username = str; } public final void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) { } public final void onTextChanged(CharSequence charSequence, int i, int i2, int i3) { } public final void afterTextChanged(Editable editable) { try { if (editable.toString().startsWith(".")) { editable.insert(0, "0"); } String obj = editable.toString(); int indexOf = obj.indexOf("."); int length = obj.length(); if (indexOf >= 0 && length - indexOf > 2) { editable.delete(indexOf + 3, length); } int lastIndexOf = obj.lastIndexOf("."); if (lastIndexOf != indexOf && lastIndexOf > 0 && length > lastIndexOf) { editable.delete(lastIndexOf, length); } } catch (Exception e) { } if (bi.K(editable) || bi.getDouble(editable.toString(), 0.0d) <= 0.0d) { LaunchAAByPersonAmountSelectUI.c(this.eDf).remove(this.username); } else { LaunchAAByPersonAmountSelectUI.c(this.eDf).put(this.username, editable.toString()); } LaunchAAByPersonAmountSelectUI.j(this.eDf).removeCallbacks(LaunchAAByPersonAmountSelectUI.i(this.eDf)); LaunchAAByPersonAmountSelectUI.j(this.eDf).postDelayed(LaunchAAByPersonAmountSelectUI.i(this.eDf), 50); } }
import java.util.Scanner; public class SixteenIntegers { public static void main(String[] args) { Scanner input = new Scanner(System.in); int[] integers = new int[51]; int num; for (int i = 0; i < 16; i++) { System.out.print("Enter a number between 0 and 50: "); num = input.nextInt(); integers[num]++; } System.out.println(); // prints out how many of each integer is entered for (int integer = 0; integer < integers.length; integer++) { if (integers[integer] >= 1) { System.out.println(integer + ": " + integers[integer]); } } } }
package annotations; import java.lang.reflect.Method; public class AnnotationTest { public static void main(String[] args) throws ClassNotFoundException { @SuppressWarnings("unchecked") Class<AnnotationTest> clazz=(Class<AnnotationTest>) Class.forName("annotations.AnnotationTest"); for(Method method : clazz.getDeclaredMethods()) { System.out.println(method.getName()); CustomAnnotation annotation=method.getAnnotation(CustomAnnotation.class); if(annotation!=null) { System.out.println(annotation.name()); System.out.println(annotation.age()); } } } @CustomAnnotation(name="Ashu",age=10) public void test1() { System.out.println("test1"); } @CustomAnnotation public void test2() { System.out.println("test2"); } }
package com.github.jerrysearch.tns.server.cluster; import java.util.LinkedList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.jerrysearch.tns.protocol.rpc.State; import com.github.jerrysearch.tns.protocol.rpc.TCNode; import com.github.jerrysearch.tns.protocol.rpc.TSNode; import com.github.jerrysearch.tns.server.command.push.ThriftPushCNodeAndSNodeListCommand; import com.github.jerrysearch.tns.server.service.SNodeManager; public class PushTnsAndServiceTask implements Runnable { private final CNodeManager cNodeManager = CNodeManager.getInstance(); private final SNodeManager sNodeManager = SNodeManager.getInstance(); private final Logger log = LoggerFactory.getLogger(getClass()); @Override public void run() { TCNode tcnode = cNodeManager.getNext(); if (null == tcnode) { log.warn("can't get next node, and do nothing"); return; } List<TCNode> cList = new LinkedList<TCNode>(); cNodeManager.toAllClusterNodeList(cList); List<TSNode> sList = new LinkedList<TSNode>(); sNodeManager.toAllServiceNodeList(sList); ThriftPushCNodeAndSNodeListCommand command = new ThriftPushCNodeAndSNodeListCommand(tcnode, cList, sList); State state = command.push(); /** * 更新节点tcnode状态 */ if (state == State.DOWN) { log.error("node [{}] state changed to DOWN !", tcnode.toString()); } tcnode.setState(state); long version = tcnode.getVersion(); tcnode.setVersion(version + 1); tcnode.setTimestamp(System.currentTimeMillis()); } }
package com.company; import java.util.Arrays; public class ArrayTest { public static void main(String[] args) { int[] array = {3, 1300, 700, 67}; int rightIndex = 1; System.out.println("Input array = " + Arrays.toString(array)); if (Array.getMaxArrayIndex(array) == rightIndex) System.out.println("Test passed"); else System.out.println("Test failed"); } }
package com.toshevski.android.shows.activities; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.ExpandableListView; import android.widget.ImageView; import android.widget.TextView; import com.toshevski.android.shows.adapters.SeasonsAdapter; import com.toshevski.android.shows.databases.MyData; import com.toshevski.android.shows.pojos.Episode; import com.toshevski.android.shows.pojos.Season; import com.toshevski.android.shows.pojos.Series; import com.toshevski.android.shows.R; public class SeriesSeasons extends AppCompatActivity { private Series series = null; private MyData myData; private int posOfSer; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.seasons_layout_with_expandable); myData = MyData.getInstance(); posOfSer = getIntent().getIntExtra("position", -1); series = myData.get(posOfSer); Log.i("SeriesSeasons:", "onCreate"); //if (series == null) // series = (Series) getIntent().getSerializableExtra("series"); Log.i("SeriesSeasons:", "Naslov: " + series.getTitle()); this.setTitle(series.getTitle()); if (this.getSupportActionBar() != null) this.getSupportActionBar().setSubtitle(R.string.seasons); final SeasonsAdapter sa = new SeasonsAdapter(this, myData.get(posOfSer)); ExpandableListView elv = (ExpandableListView) findViewById(R.id.seasonsListExpandable); ViewGroup header = (ViewGroup) getLayoutInflater().inflate(R.layout.season_list_header, elv, false); ImageView headerImage = (ImageView) header.findViewById(R.id.seasonHeaderImage); TextView headerTitle = (TextView) header.findViewById(R.id.seasonHeaderTitle); TextView headerOverview = (TextView) header.findViewById(R.id.seasonHeaderOverview); headerImage.setImageDrawable(series.getImageFromFile()); headerTitle.setText(series.getTitle()); headerOverview.setText(series.getOverview()); elv.addHeaderView(header); elv.setAdapter(sa); elv.setOnChildClickListener(new ExpandableListView.OnChildClickListener() { @Override public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) { Log.i("SeriesSeasons:", "Na koja pozicija e tatkoto: " + groupPosition); Episode e = series.getOneSeason(groupPosition).getOneEpisode(childPosition); Season s = series.getOneSeason(groupPosition); if (e.isFinished()) { e.setIsFinished(false); s.removeFinishedEpisode(); } else { e.setIsFinished(true); s.addFinishedEpisode(); } sa.notifyDataSetChanged(); return true; } }); } @Override protected void onResume() { super.onResume(); } @Override protected void onPause() { super.onPause(); myData.saveData(getFilesDir()); } }
/* * Toda Classe herda da classe Object do pacote java.lang * Por padrão, o método toString do Object retorna o nome da classe @ um número de identidade: */ package java.lang.object.tostring; class Pessoa { private String nome; @Override public String toString() { return "Nome: " + this.nome; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } } public class Main { public static void main(String[] args) { Pessoa p = new Pessoa(); System.out.println(p.toString()); } }
package pe.ccruz.trabajoseguroapp.dto; public class BitacoraDto { private String nombreEmpleado; private String detalleIncidencia; private String codIncidencia; public BitacoraDto(){ } public BitacoraDto(String nombreEmpleado, String detalleIncidencia, String codIncidencia) { this.nombreEmpleado = nombreEmpleado; this.detalleIncidencia = detalleIncidencia; this.codIncidencia = codIncidencia; } /** * @return the nombreEmpleado */ public String getNombreEmpleado() { return nombreEmpleado; } /** * @param nombreEmpleado the nombreEmpleado to set */ public void setNombreEmpleado(String nombreEmpleado) { this.nombreEmpleado = nombreEmpleado; } /** * @return the detalleIncidencia */ public String getDetalleIncidencia() { return detalleIncidencia; } /** * @param detalleIncidencia the detalleIncidencia to set */ public void setDetalleIncidencia(String detalleIncidencia) { this.detalleIncidencia = detalleIncidencia; } /** * @return the codIncidencia */ public String getCodIncidencia() { return codIncidencia; } /** * @param codIncidencia the codIncidencia to set */ public void setCodIncidencia(String codIncidencia) { this.codIncidencia = codIncidencia; } }
package com.dil.firstproj; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; @Service public class UserService implements UserDetailsService { @Override public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException { if (!"error".equalsIgnoreCase(userName)) { return User.withDefaultPasswordEncoder() .username("dilshob") .password("test") .roles("test") .build(); } return null; } }
public class Position { double x; double y; Position(double x,double y){ this.x=x; this.y=y; } double getx() { return x; } double gety() { return y; } }
package com.supconit.kqfx.web.analysis.controllers; import hc.base.domains.AjaxMessage; import hc.base.domains.Pageable; import hc.base.domains.Pagination; import hc.business.dic.services.DataDictionaryService; import hc.mvc.annotations.FormBean; import hc.safety.manager.SafetyManager; import java.io.OutputStream; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.persistence.criteria.CriteriaBuilder.In; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.collections.CollectionUtils; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFFont; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.util.HSSFColor; import org.apache.poi.ss.util.Region; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.supconit.honeycomb.business.authorization.entities.User; import com.supconit.honeycomb.business.authorization.services.RoleService; import com.supconit.honeycomb.business.organization.services.DepartmentService; import com.supconit.honeycomb.business.organization.services.PersonService; import com.supconit.kqfx.web.analysis.entities.DayReport; import com.supconit.kqfx.web.analysis.entities.JgZcd; import com.supconit.kqfx.web.analysis.services.DayReportService; import com.supconit.kqfx.web.analysis.services.JgZcdService; import com.supconit.kqfx.web.util.DictionaryUtil; import com.supconit.kqfx.web.util.OperateType; import com.supconit.kqfx.web.util.UtilTool; import com.supconit.kqfx.web.xtgl.entities.ExtPerson; import com.supconit.kqfx.web.xtgl.services.SystemLogService; /** * 按治超站违法统计 * @author gs * */ @SuppressWarnings("deprecation") @RequestMapping("/analysis/overload/zczoverload") @Controller("analysis_zczoverLoad_controller") public class ZczAnalysisController { private static final String MODULE_CODE = "ZCZ_ANALYSIS"; @Autowired private DayReportService dayReportService; @Autowired private DataDictionaryService dataDictionaryService; @Autowired private SafetyManager safetyManager; @Autowired private RoleService roleService; @Autowired private DepartmentService departmentService; @Autowired private PersonService personService; @Autowired private JgZcdService jgZcdService; @Autowired private SystemLogService systemLogService; @Resource private HttpServletRequest request; @ModelAttribute("dayReport") private DayReport getDayReport(){ DayReport dayReport = new DayReport(); return dayReport; } private transient static final Logger logger = LoggerFactory.getLogger(ZczAnalysisController.class); @RequestMapping(value = "list", method = RequestMethod.GET) public String list(ModelMap model){ this.systemLogService.log(MODULE_CODE, OperateType.view.getCode(), "按治超站超限统计", request.getRemoteAddr()); User user = (User) safetyManager.getAuthenticationInfo().getUser(); if(null!=user&&null!=user.getPerson()&&null!=user.getPersonId()) { ExtPerson person = personService.getById(user.getPersonId()); //根据JGID进行权限限制 //若是超级管理员查询JGID = null //大桥的为 JGID=133 // 二桥为JGID=134 model.put("jgid", person.getJgbh()); } HashMap<String, String> stationMap = DictionaryUtil.dictionary("STATIONNAME",dataDictionaryService); for(String key:stationMap.keySet() ){ model.put("station"+key,stationMap.get(key)); } return "analysis/overload/zczoverload/list"; } @ResponseBody @RequestMapping(value = "list", method = RequestMethod.POST) public Pagination<DayReport> list(Pagination<DayReport> pager, @FormBean(value = "condition", modelCode = "dayReport") DayReport condition) { try { this.systemLogService.log(MODULE_CODE, OperateType.query.getCode(), "按治超站超限统计", request.getRemoteAddr()); if (pager.getPageNo() < 1 || pager.getPageSize() < 1 || pager.getPageSize() > Pagination.MAX_PAGE_SIZE) return pager; condition = setDayReport(condition); dayReportService.findZczByPager(pager, condition); SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日"); for(DayReport dayReport : pager){ dayReport.setTjDateStr(formatter.format(dayReport.getTjDate())); if(dayReport.getDetectOne()==null){dayReport.setDetectOne(0);} if(dayReport.getDetectTwo()==null){dayReport.setDetectTwo(0);} if(dayReport.getDetectThree()==null){dayReport.setDetectThree(0);} if(dayReport.getDetectFour()==null){dayReport.setDetectFour(0);} if(dayReport.getDetectFive()==null){dayReport.setDetectFive(0);} if(condition.getJgid()==null){ dayReport.setTotal(dayReport.getDetectOne()+dayReport.getDetectTwo()+dayReport.getDetectThree()+ dayReport.getDetectFour()+dayReport.getDetectFive()); }else{ if(condition.getJgid()==133){ dayReport.setTotal(dayReport.getDetectOne()+dayReport.getDetectTwo()); }else if(condition.getJgid()==134){ dayReport.setTotal(dayReport.getDetectThree()+ dayReport.getDetectFour()+dayReport.getDetectFive()); }else{ dayReport.setTotal(dayReport.getDetectOne()+dayReport.getDetectTwo()+dayReport.getDetectThree()+ dayReport.getDetectFour()+dayReport.getDetectFive()); } } } } catch (Exception e) { logger.error(e.getMessage(), e); } return pager; } /** * 设置默认循环治超站的权限 */ public DayReport setDayReport(DayReport condition){ if(condition.getDetectStation()!=null){ condition.setDetects(condition.getDetectStation().split(",")); }else{ // 根据jgid获取能够查看治超站的权限 if(condition.getJgid()==null){ // 无jgid的默认为所有治超站权限 condition.setDetects(null); }else{ // 含有jgid设置对应的权限 List<JgZcd> zcdList = jgZcdService.getByJgid(condition.getJgid()); String detectStations=""; for(JgZcd jgZcd:zcdList){ detectStations=detectStations+jgZcd.getDeteStation()+","; } condition.setDetects(detectStations.substring(0, detectStations.length()-1).split(",")); } } if(condition.getOverloadStatusStr()==null||condition.getOverloadStatusStr().equals("null")){ condition.setIllegals(null); }else{ String[] illegals = condition.getOverloadStatusStr().split(","); Integer[] datas = new Integer[illegals.length]; for(int j = 0 ;j<illegals.length;j++){ datas[j]=Integer.valueOf(illegals[j]); } condition.setIllegals(datas); } return condition; } /** * 获取违法程度数据 * @return */ @ResponseBody @RequestMapping(value = "overLoadStatus", method = RequestMethod.POST) AjaxMessage getIlleagls(){ try { HashMap<String, String> illeagalMap = DictionaryUtil.dictionary("OVERLOADSTATUS",dataDictionaryService); List<String> stationList = new ArrayList<String>() ; for(String key:illeagalMap.keySet() ){ stationList.add(key+":"+illeagalMap.get(key)); } return AjaxMessage.success(stationList); } catch (Exception e) { logger.error(e.getMessage(), e); } return null; } /** * 获取图标数据 */ @ResponseBody @RequestMapping(value = "getChartData", method = RequestMethod.POST) public AjaxMessage getChartData(@FormBean(value = "condition", modelCode = "dayReport") DayReport condition){ try { this.systemLogService.log(MODULE_CODE, OperateType.view.getCode(), "查询按治超站超限图表信息", request.getRemoteAddr()); // 是否选择日期没有选择查看昨天数据信息,昨天的时间日期是在页面中进行设置的 if(condition.getOverloadStatusStr()!=null&&!condition.getOverloadStatusStr().equals("")){ String[] nos=condition.getOverloadStatusStr().split(","); Integer ills[]=new Integer[nos.length]; for(int i=0;i<nos.length;i++){ ills[i]=Integer.valueOf(nos[i]); } condition.setIllegals(ills); } List<DayReport> zczoverLoadList = new ArrayList<DayReport>(); condition=setDayReport(condition); zczoverLoadList =dayReportService.AnalysisZczByCondition(condition); if(!CollectionUtils.isEmpty(zczoverLoadList)){ // 设置X轴数据 List<String> xAisData = new ArrayList<String>(); SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd"); for(DayReport dayReport : zczoverLoadList){ String date = formatter.format(dayReport.getTjDate()); if(!xAisData.contains(date)){ xAisData.add(date); } } // 设置legend(治超站) HashMap<String, String> detectionLengend = DictionaryUtil.dictionary("STATIONNAME",dataDictionaryService); List<String> legend =new ArrayList<String>(); Iterator<String> iterator = detectionLengend.keySet().iterator(); while (iterator.hasNext()) { String key = iterator.next(); legend.add(detectionLengend.get(key)); } legend.add("汇总"); // 设置y轴数据 List<DayReport> yAisData = new ArrayList<DayReport>(); for(DayReport day:zczoverLoadList){ if(day.getDetectOne()==null){day.setDetectOne(0);} if(day.getDetectTwo()==null){day.setDetectTwo(0);} if(day.getDetectThree()==null){day.setDetectThree(0);} if(day.getDetectFour()==null){day.setDetectFour(0);} if(day.getDetectFive()==null){day.setDetectFive(0);} day.setTotal(day.getDetectOne()+day.getDetectTwo()+day.getDetectThree()+ day.getDetectFour()+day.getDetectFive()); yAisData.add(day); } //标志查询结果不为空 Map<String,Object> resultMap = new HashMap<String,Object>(); resultMap.put("xAis", xAisData); resultMap.put("legend", legend); resultMap.put("yAis", yAisData); resultMap.put("success", 200); return AjaxMessage.success(resultMap); }else{ //标志查询结果为空 Map<String,Object> resultMap = new HashMap<String,Object>(); resultMap.put("success", 1002); return AjaxMessage.success(resultMap); } } catch (Exception e) { //标志查询结果不为空 logger.error("", e); return AjaxMessage.success("请求服务器错误"); } } @RequestMapping(value = "exportAll", method = RequestMethod.GET) public void exportAll(HttpServletRequest request, HttpServletResponse response, String total, @FormBean(value = "condition", modelCode = "dayReport") DayReport condition){ logger.info("-------------------------导出全部excel列表---------------"); try { this.systemLogService.log(MODULE_CODE, OperateType.export.getCode(), "导出按违法程度统计全部记录", request.getRemoteAddr()); Pagination<DayReport> pager = new Pagination<DayReport>(); pager.setPageNo(1); pager.setPageSize(Integer.MAX_VALUE); condition = setDayReport(condition); dayReportService.findZczByPager(pager, condition); SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd"); for(DayReport dayReport : pager){ dayReport.setTjDateStr(formatter.format(dayReport.getTjDate())); if(dayReport.getDetectOne()==null){dayReport.setDetectOne(0);} if(dayReport.getDetectTwo()==null){dayReport.setDetectTwo(0);} if(dayReport.getDetectThree()==null){dayReport.setDetectThree(0);} if(dayReport.getDetectFour()==null){dayReport.setDetectFour(0);} if(dayReport.getDetectFive()==null){dayReport.setDetectFive(0);} dayReport.setTotal(dayReport.getDetectOne()+dayReport.getDetectTwo()+dayReport.getDetectThree()+ dayReport.getDetectFour()+dayReport.getDetectFive()); } Date date = new Date(); String time = formatter.format(date); String title = "治超站超限统计记录_"+time+".xls"; editExcel(pager,response,title,condition); } catch (Exception e) { logger.info("-------------------------导出全部excel列表---------------"); } } HSSFCellStyle setHSSFCellStyle( HSSFCellStyle style){ style.setBorderBottom(HSSFCellStyle.BORDER_THIN); style.setBorderLeft(HSSFCellStyle.BORDER_THIN); style.setBorderRight(HSSFCellStyle.BORDER_THIN); style.setBorderTop(HSSFCellStyle.BORDER_THIN); return style; } void editExcel(Pageable<DayReport> pager,HttpServletResponse response,String title, DayReport condition){ OutputStream out=null; try{ response.setHeader("Content-Disposition", "attachment; filename=" + new String(title.getBytes("GB2312"), "iso8859-1")); response.setContentType("application/msexcel;charset=UTF-8"); out =response.getOutputStream(); HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet sheet = workbook.createSheet(UtilTool.toGBK("治超站超限统计记录")); HSSFRow top = sheet.createRow(0); HSSFRow row = sheet.createRow(1); HSSFCellStyle style1 = workbook.createCellStyle(); HSSFCellStyle style2 = workbook.createCellStyle(); HSSFCellStyle style3 = workbook.createCellStyle(); /** 字体font **/ HSSFFont font1 = workbook.createFont(); font1.setColor(HSSFColor.BLACK.index); font1.setFontHeightInPoints((short) 10); font1.setBoldweight((short) 24); font1.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); HSSFFont font2 = workbook.createFont(); font2.setColor(HSSFColor.BLACK.index); font2.setFontHeightInPoints((short) 10); font2.setBoldweight((short) 24); style1.setFont(font1); style1=setHSSFCellStyle(style1); style1.setFillBackgroundColor(HSSFColor.AQUA.index); style1.setFillForegroundColor(HSSFColor.AQUA.index); style1.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); style2.setFont(font2); style2=setHSSFCellStyle(style2); style3.setFont(font1); style3=setHSSFCellStyle(style3); /** 字体居中 **/ style1.setAlignment(HSSFCellStyle.ALIGN_CENTER); style2.setAlignment(HSSFCellStyle.ALIGN_CENTER); style3.setAlignment(HSSFCellStyle.ALIGN_CENTER); //获取导出条件 String conditionString =""; //获取导出的时间 if(condition.getBeginDate()!=null){ SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd"); String begin = format1.format(condition.getBeginDate()); if(condition.getEndDate()!=null){ String end = format1.format(condition.getEndDate()); end = format1.format(condition.getEndDate()); conditionString="统计日期:"+begin+" 至 "+end+"\r\n"; }else{ conditionString="统计日期:"+begin+"开始至今为止\r\n"; } } //获取违法程度 HashMap<String, String> overLoadMap = DictionaryUtil.dictionary("OVERLOADSTATUS",dataDictionaryService); String overString = ""; if(condition.getOverloadStatusStr()==null||condition.getOverloadStatusStr().equals("")||condition.getOverloadStatusStr()==""||condition.getOverloadStatusStr().equals("null")){ String[] detects=new String[]{"0","1","2","3","4","5"}; for(int i=0;i<detects.length;i++){ overString= overString+" "+overLoadMap.get(detects[i]); } }else{ String[] detects = condition.getOverloadStatusStr().split(","); for(int i=0;i<detects.length;i++){ overString= overString+" "+overLoadMap.get(detects[i]); } } conditionString=conditionString+"统计违法程度:"+overString; //获取用户权限,根据权限导出数据 User user = (User) safetyManager.getAuthenticationInfo().getUser(); if(null!=user&&null!=user.getPerson()&&null!=user.getPersonId()) { ExtPerson person = personService.getById(user.getPersonId()); condition.setJgid(person.getJgbh()); } if(condition.getJgid()==null){ //导出全部 exportExcelAll(pager,conditionString,style1,style2,style3,row,top,sheet); }else{ if(condition.getJgid()==133){ //导出JGBH133 exportExcelJgid133(pager,conditionString,style1,style2,style3,row,top,sheet); }else if(condition.getJgid()==134){ //导出JGBH134 exportExcelJgid134(pager,conditionString,style1,style2,style3,row,top,sheet); } } workbook.write(out); out.flush(); out.close(); } catch (Exception e){ e.printStackTrace(); } } private void exportExcelAll(Pageable<DayReport> pager,String conditionString, HSSFCellStyle style1,HSSFCellStyle style2,HSSFCellStyle style3, HSSFRow row,HSSFRow top,HSSFSheet sheet) { //设置表头长度 for(int i=0;i<8;i++){ HSSFCell cell = top.createCell(i); cell.setCellStyle(style3); } //设置表头长度 top.getSheet().addMergedRegion(new Region(0,(short)0,0,(short)7)); //设置表头样式 HSSFCell celltop = top.createCell(0); top.setHeight((short) (200*4)); celltop.setCellStyle(style3); //设置表头内容: celltop.setCellValue("治超站超限统计\r\n"+conditionString); String[] head = { "序号", "统计日期", "椒江一桥北", "椒江一桥南", "椒江二桥北74省道", "椒江二桥北75省道","椒江二桥南75省道","总计"}; int i0=0,i1=0,i2=0,i3=0,i4=0,i5=0,i6=0,i7=0; for (int i = 0; i < head.length; i++) { HSSFCell cell = row.createCell(i); cell.setCellValue(head[i]); cell.setCellStyle(style1); if(i==0){ i0= head[i].length()*256+256*10;} if(i==1){ i1= head[i].length()*256+256*10;} if(i==2){ i2= head[i].length()*256+256*10;} if(i==3){ i3= head[i].length()*256+256*10;} if(i==4){ i4= head[i].length()*256+256*10;} if(i==5){ i5= head[i].length()*256+256*10;} if(i==6){ i6= head[i].length()*256+256*10;} if(i==7){ i7= head[i].length()*256+256*10;} } for(int i=0; i<pager.size();i++){ row = sheet.createRow(i+2); // 序号 HSSFCell cell0 =row.createCell(0); cell0.setCellValue(1+i); cell0.setCellStyle(style2); if(String.valueOf(1+i).length()*256>=i0){ i0=String.valueOf(1+i).length()*256+256*8; } // 统计时间 HSSFCell cell1 =row.createCell(1); cell1.setCellStyle(style2); if(pager.get(i).getTjDateStr()!=null){ cell1.setCellValue(pager.get(i).getTjDateStr()); if(pager.get(i).getTjDateStr().length()*256>=i1){ i1=pager.get(i).getTjDateStr().length()*256+256*10; } }else{ cell1.setCellValue(""); } //// 椒江一桥北 HSSFCell cell2 =row.createCell(2); cell2.setCellStyle(style2); if(pager.get(i).getDetectOne()!=null){ cell2.setCellValue(pager.get(i).getDetectOne()); }else{ cell2.setCellValue(""); } //// 椒江一桥南 HSSFCell cell3 =row.createCell(3); cell3.setCellStyle(style2); if(pager.get(i).getDetectTwo()!=null){ cell3.setCellValue(pager.get(i).getDetectTwo()); }else{ cell3.setCellValue(""); } //// 椒江二桥北74省道 HSSFCell cell4 =row.createCell(4); cell4.setCellStyle(style2); if(pager.get(i).getDetectThree()!=null){ cell4.setCellValue(pager.get(i).getDetectThree()); }else{ cell4.setCellValue(""); } //// 椒江二桥北75省道 HSSFCell cell5 =row.createCell(5); cell5.setCellStyle(style2); if(pager.get(i).getDetectFour()!=null){ cell5.setCellValue(pager.get(i).getDetectFour()); }else{ cell5.setCellValue(""); } //// 椒江二桥南75省道 HSSFCell cell6 =row.createCell(6); cell6.setCellStyle(style2); if(pager.get(i).getDetectFive()!=null){ cell6.setCellValue(pager.get(i).getDetectFive()); }else{ cell6.setCellValue(""); } // 总计 HSSFCell cell7 =row.createCell(7); cell7.setCellStyle(style2); if(pager.get(i).getTotal()!=null){ cell7.setCellValue(pager.get(i).getTotal()); }else{ cell7.setCellValue(""); } } sheet.setColumnWidth(0,i0); sheet.setColumnWidth(1,i1); sheet.setColumnWidth(2,i2); sheet.setColumnWidth(3,i3); sheet.setColumnWidth(4,i4); sheet.setColumnWidth(5,i5); sheet.setColumnWidth(6,i6); sheet.setColumnWidth(7,i7); } private void exportExcelJgid133(Pageable<DayReport> pager,String conditionString, HSSFCellStyle style1,HSSFCellStyle style2,HSSFCellStyle style3, HSSFRow row,HSSFRow top,HSSFSheet sheet) { //设置表头长度 for(int i=0;i<5;i++){ HSSFCell cell = top.createCell(i); cell.setCellStyle(style3); } //设置表头长度 top.getSheet().addMergedRegion(new Region(0,(short)0,0,(short)4)); //设置表头样式 HSSFCell celltop = top.createCell(0); top.setHeight((short) (200*4)); celltop.setCellStyle(style3); //设置表头内容: celltop.setCellValue("治超站超限统计\r\n"+conditionString); String[] head = { "序号", "统计日期", "K110+150", "K109+800","总计"}; int i0 = 0,i1=0,i2=0,i3=0,i4=0; for (int i = 0; i < head.length; i++) { HSSFCell cell = row.createCell(i); cell.setCellValue(head[i]); cell.setCellStyle(style1); if(i==0){ i0= head[i].length()*256+256*10;} if(i==1){ i1= head[i].length()*256+256*10;} if(i==2){ i2= head[i].length()*256+256*10;} if(i==3){ i3= head[i].length()*256+256*10;} if(i==4){ i4= head[i].length()*256+256*10;} } for(int i=0; i<pager.size();i++){ row = sheet.createRow(i+2); // 序号 HSSFCell cell0 =row.createCell(0); cell0.setCellValue(1+i); cell0.setCellStyle(style2); if(String.valueOf(1+i).length()*256>=i0){ i0=String.valueOf(1+i).length()*256+256*8; } // 统计时间 HSSFCell cell1 =row.createCell(1); cell1.setCellStyle(style2); if(pager.get(i).getTjDateStr()!=null){ cell1.setCellValue(pager.get(i).getTjDateStr()); if(pager.get(i).getTjDateStr().length()*256>=i1){ i1=pager.get(i).getTjDateStr().length()*256+256*10; } }else{ cell1.setCellValue(""); } //// 椒江一桥北 HSSFCell cell2 =row.createCell(2); cell2.setCellStyle(style2); if(pager.get(i).getDetectOne()!=null){ cell2.setCellValue(pager.get(i).getDetectOne()); }else{ cell2.setCellValue(""); } //// 椒江一桥南 HSSFCell cell3 =row.createCell(3); cell3.setCellStyle(style2); if(pager.get(i).getDetectTwo()!=null){ cell3.setCellValue(pager.get(i).getDetectTwo()); }else{ cell3.setCellValue(""); } //// 总计 HSSFCell cell4 =row.createCell(4); cell4.setCellStyle(style2); if(pager.get(i).getTotal()!=null){ cell4.setCellValue(pager.get(i).getTotal()); }else{ cell4.setCellValue(""); } } sheet.setColumnWidth(0,i0); sheet.setColumnWidth(1,i1); sheet.setColumnWidth(2,i2); sheet.setColumnWidth(3,i3); sheet.setColumnWidth(4,i4); } private void exportExcelJgid134(Pageable<DayReport> pager,String conditionString, HSSFCellStyle style1,HSSFCellStyle style2,HSSFCellStyle style3, HSSFRow row,HSSFRow top,HSSFSheet sheet) { //设置表头长度 for(int i=0;i<6;i++){ HSSFCell cell = top.createCell(i); cell.setCellStyle(style3); } //设置表头长度 top.getSheet().addMergedRegion(new Region(0,(short)0,0,(short)5)); //设置表头样式 HSSFCell celltop = top.createCell(0); top.setHeight((short) (200*4)); celltop.setCellStyle(style3); //设置表头内容: celltop.setCellValue("治超站超限统计\r\n"+conditionString); String[] head = { "序号", "统计日期", "椒江二桥北74省道", "椒江二桥北75省道","椒江二桥南75省道","总计"}; int i0=0,i1=0,i2=0,i3=0,i4=0,i5=0; for (int i = 0; i < head.length; i++) { HSSFCell cell = row.createCell(i); cell.setCellValue(head[i]); cell.setCellStyle(style1); if(i==0){ i0= head[i].length()*256+256*10;} if(i==1){ i1= head[i].length()*256+256*10;} if(i==2){ i2= head[i].length()*256+256*10;} if(i==3){ i3= head[i].length()*256+256*10;} if(i==4){ i4= head[i].length()*256+256*10;} if(i==5){ i5= head[i].length()*256+256*10;} } for(int i=0; i<pager.size();i++){ row = sheet.createRow(i+2); // 序号 HSSFCell cell0 =row.createCell(0); cell0.setCellValue(1+i); cell0.setCellStyle(style2); if(String.valueOf(1+i).length()*256>=i0){ i0=String.valueOf(1+i).length()*256+256*8; } // 统计时间 HSSFCell cell1 =row.createCell(1); cell1.setCellStyle(style2); if(pager.get(i).getTjDateStr()!=null){ cell1.setCellValue(pager.get(i).getTjDateStr()); if(pager.get(i).getTjDateStr().length()*256>=i1){ i1=pager.get(i).getTjDateStr().length()*256+256*10; } }else{ cell1.setCellValue(""); } //// 椒江二桥北74省道 HSSFCell cell2 =row.createCell(2); cell2.setCellStyle(style2); if(pager.get(i).getDetectThree()!=null){ cell2.setCellValue(pager.get(i).getDetectThree()); }else{ cell2.setCellValue(""); } //// 椒江二桥北75省道 HSSFCell cell3 =row.createCell(3); cell3.setCellStyle(style2); if(pager.get(i).getDetectFour()!=null){ cell3.setCellValue(pager.get(i).getDetectFour()); }else{ cell3.setCellValue(""); } //// 椒江二桥南75省道 HSSFCell cell4 =row.createCell(4); cell4.setCellStyle(style2); if(pager.get(i).getDetectFive()!=null){ cell4.setCellValue(pager.get(i).getDetectFive()); }else{ cell4.setCellValue(""); } // 总计 HSSFCell cell5 =row.createCell(5); cell5.setCellStyle(style2); if(pager.get(i).getTotal()!=null){ cell5.setCellValue(pager.get(i).getTotal()); }else{ cell5.setCellValue(""); } } sheet.setColumnWidth(0,i0); sheet.setColumnWidth(1,i1); sheet.setColumnWidth(2,i2); sheet.setColumnWidth(3,i3); sheet.setColumnWidth(4,i4); sheet.setColumnWidth(5,i5); } }
package hearthstone; import java.util.ArrayList; public class Mirror extends Puzzles { public Mirror(ArrayList<Card> d, ArrayList<Card> ed, Card[] h, Card[] eh, Card[] fc, Card[] efc, int cp, int sm, int cm, Hero aHero, Hero eHero) { super(d, ed, h, eh, fc, efc, cp, sm, cm, aHero, eHero); } public Mirror() { super(null, null, null, null, null, null, 0, 0, 0, null, null); } public boolean checkWin() {//checks enemies board matches your board boolean check = true; //compares every minion for (int i = 0; i < 7; i++) { if (logicalXOR(this.enemyFieldCards[i], this.fieldCards[i])) {//checks if only one minion is null check = false; } if (this.enemyFieldCards[i] != null && this.fieldCards[i] != null) { //compares that it is same minion if (!this.enemyFieldCards[i].name.equals(this.fieldCards[i].name)) { check = false; //compares that it is the same health } else if (this.enemyFieldCards[i].hp != this.fieldCards[i].hp) { check = false; //compares that it is the same attack } else if (this.enemyFieldCards[i].attack != this.fieldCards[i].attack) { check = false; } } } //if everything matches return check; } public boolean logicalXOR(Card enemyMinion, Card allyMinion) {//returns the XOR operation if only one card is null boolean eM, aM; if (enemyMinion == null) { eM = true; } else { eM = false; } if (allyMinion == null) { aM = true; } else { aM = false; } return ((aM || eM) && !(aM && eM)); } }
package com.tencent.mm.plugin.bottle.ui; import com.tencent.mm.plugin.bottle.ui.ThrowBottleAnimUI.a; class ThrowBottleUI$4 implements a { final /* synthetic */ ThrowBottleUI hnD; ThrowBottleUI$4(ThrowBottleUI throwBottleUI) { this.hnD = throwBottleUI; } public final void auA() { ThrowBottleUI.q(this.hnD).setVisibility(8); ThrowBottleUI.h(this.hnD).nm(0); } }
package com.ziroom.service; import com.ziroom.dao.UserDAO; import com.ziroom.entity.UserEntity; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; /** * <p></p> * <p> * <PRE> * <BR> 修改记录 * <BR>----------------------------------------------- * <BR> 修改日期 修改人 修改内容 * </PRE> * * @author zhangxiuli * @version 1.0 * @date 2018/9/30 14:41 * @since 1.0 */ @Transactional @Service("userService") public class UserServiceImpl implements UserService { @Autowired private UserDAO userDAO; @Override @Transactional(propagation = Propagation.SUPPORTS,readOnly = true) public UserEntity queryByUsername(String username) { return userDAO.queryByUsername(username); } }
/** * */ package com.yougou.merchant.api.monitor.vo; import java.io.Serializable; import java.util.List; /** * Api监控预警 * * @author huang.tao * */ public class MonitorEarlyWarning implements Serializable { private static final long serialVersionUID = -5693969468095820607L; private String id; //appKey 对应到数据库的appkey private String appKey; //appKeyHolder持有者 private String appKeyHolder; private String timeQuantum; private Integer warmAppkeyCallCount; private Integer warmDayCallCount; private Integer warmRateCount; private Integer warmSuccessCount; /** appKey 日调用次数预警明细 */ private MonitorAppkeyWarnDetail appKeyDetail; /** api 日调用次数预警明细 */ private List<MonitorDayWarnDetail> dayDetails; /** api调用成功率预警明细 */ private List<MonitorSuccRateWarnDetail> succRateDetails; /** api调用频率预警明细 */ private List<MonitorRateWarnDetail> rateWarnDetails; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getAppKey() { return appKey; } public void setAppKey(String appKey) { this.appKey = appKey; } public String getAppKeyHolder() { return appKeyHolder; } public void setAppKeyHolder(String appKeyHolder) { this.appKeyHolder = appKeyHolder; } public String getTimeQuantum() { return timeQuantum; } public void setTimeQuantum(String timeQuantum) { this.timeQuantum = timeQuantum; } public Integer getWarmAppkeyCallCount() { return warmAppkeyCallCount; } public void setWarmAppkeyCallCount(Integer warmAppkeyCallCount) { this.warmAppkeyCallCount = warmAppkeyCallCount; } public Integer getWarmDayCallCount() { return warmDayCallCount; } public void setWarmDayCallCount(Integer warmDayCallCount) { this.warmDayCallCount = warmDayCallCount; } public Integer getWarmRateCount() { return warmRateCount; } public void setWarmRateCount(Integer warmRateCount) { this.warmRateCount = warmRateCount; } public Integer getWarmSuccessCount() { return warmSuccessCount; } public void setWarmSuccessCount(Integer warmSuccessCount) { this.warmSuccessCount = warmSuccessCount; } public MonitorAppkeyWarnDetail getAppKeyDetail() { return appKeyDetail; } public void setAppKeyDetail(MonitorAppkeyWarnDetail appKeyDetail) { this.appKeyDetail = appKeyDetail; } public List<MonitorDayWarnDetail> getDayDetails() { return dayDetails; } public void setDayDetails(List<MonitorDayWarnDetail> dayDetails) { this.dayDetails = dayDetails; } public List<MonitorSuccRateWarnDetail> getSuccRateDetails() { return succRateDetails; } public void setSuccRateDetails(List<MonitorSuccRateWarnDetail> succRateDetails) { this.succRateDetails = succRateDetails; } public List<MonitorRateWarnDetail> getRateWarnDetails() { return rateWarnDetails; } public void setRateWarnDetails(List<MonitorRateWarnDetail> rateWarnDetails) { this.rateWarnDetails = rateWarnDetails; } }
package com.aciton; import com.entity.UsersEntity; import com.service.UserService; import org.apache.struts2.ServletActionContext; import javax.servlet.http.HttpServletRequest; import java.util.Vector; /** * Created by 滩涂上的芦苇 on 2016/6/7. */ public class QueryUserAction { public static final long serialVersionUID = 1L; public static final String RETURN = "return"; public HttpServletRequest request; private UserService userService; public UserService getUserService() { return userService; } public void setUserService(UserService userService) { this.userService = userService; } public String execute() { request = ServletActionContext.getRequest(); Vector<UsersEntity> users = new Vector<UsersEntity>(); try { users = userService.queryAll(); request.setAttribute("userlist", users); } catch (Exception e) { e.printStackTrace(); } ServletActionContext.setRequest(request); return RETURN; } }
package com.everis.eCine.model; import java.util.Date; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import lombok.AllArgsConstructor; import lombok.Data; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; @Entity @Data @Getter @Setter @AllArgsConstructor @NoArgsConstructor @ToString public class Film extends AbstractModel<Long>{ /** * */ private static final long serialVersionUID = 1L; @Column(nullable = false, length = 50) private String titre; @Column(nullable = false) private int duree; @Column(nullable = false) private int annee; @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="GENRE_ID") private Genre genre; @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="NATIONALITE_ID") private Nationalite nationalite; @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="DIRECTOR_ID") private Personne realisateur; @ManyToMany @JoinTable( name="FILM_ACTEUR", joinColumns=@JoinColumn(name="ACTOR_ID", referencedColumnName="ID"), inverseJoinColumns=@JoinColumn(name="FILM_ID", referencedColumnName="ID")) private List<Personne> acteurs; @OneToMany(mappedBy = "film") private List<Seance> seances; @Column(name = "added_date", columnDefinition = "TIMESTAMP DEFAULT CURRENT_TIMESTAMP", insertable = false, updatable = false) private Date addedDate; }
package com.example.todolistapp.Business; import android.content.Context; import com.example.todolistapp.DataAccess.ToDoDal; import com.example.todolistapp.Entities.ToDo; import java.util.List; public class ToDoManager { ToDoDal toDoDal; public ToDoManager(Context context) { toDoDal = new ToDoDal(context); } public void Add(ToDo product){ toDoDal.create(product); } public void Delete(int id){ toDoDal.delete(id); } public void Update(ToDo product){ toDoDal.update(product); } public ToDo Get( int id){ return toDoDal.read(id); } public List<ToDo> GetList( ){ return toDoDal.readAll(); } public List<ToDo> getToDosWithTagId(int id) { return toDoDal.getToDosWithTagId(id); } }
package model; import java.util.HashMap; import java.util.List; import java.util.Random; /** * InsanityHauntState is a GameState * Occurs after a player has triggered X amount of events * InsanityHauntState makes a player haunted, giving the haunted player the ability to attack other players. * The winCondition for the haunted player if all players is killed * The winCondition for the other players is finding a escapeHatch. */ public class InsanityHauntState implements GameState { private final String hauntText = "After wandering the house for too long your mind begins to break down." + "You hear whispers from the old gods telling you that only way to carry on is to betray your friends.\n " + "\n The rules for this haunt are written below: \n" + "\n The haunted players objective is to kill all the other players\n" + "\n The adventurers objective is to find a hidden escape hatch to escape the horrors of the house"; Game game; int numEscapeHatch = 4; Random rand = new Random(); HashMap<Stat, Integer> statBoost; public InsanityHauntState() { statBoost = new HashMap<>(); statBoost.put(Stat.STRENGTH, 10); statBoost.put(Stat.SPEED, 5); } @Override public void init() { game = Game.getInstance(); createEscapeHatches(); setHauntedPlayer(); } private void setHauntedPlayer() { game.getCurrentPlayer().setIsHaunted(); game.getCurrentPlayer().getCharacter().updateStat(statBoost); } /** * The new turn when the state is activated * * @param activePlayer the current player. */ @Override public void turn(Player activePlayer) { combat(); winConditionChecker(); } /** * Creates escapeHatches for the players that are not hunted. */ private void createEscapeHatches() { Tile tile; int i = 0; while (i < numEscapeHatch) { tile = game.getBoard().getFloor(1).getTile(rand.nextInt(6), rand.nextInt(6)); if (!tile.hasEvent()) { tile.setEvent(EventFactory.createEscapeEvent()); i++; } } } /** * Logic for the combat between players during haunt */ private void combat() { Player hauntedPlayer = null; List<Player> playersInRoom = game.createListOfPlayersInSameRoom(); for (Player p : playersInRoom) { if (p.isHaunted()) { hauntedPlayer = p; } } playersInRoom.remove(hauntedPlayer); if (hauntedPlayer != null && !playersInRoom.isEmpty()) { game.saveOldStaminaMap(); game.notifyCombat(); for (Player p : playersInRoom) { int insanePlayerStrenght = hauntedPlayer.rollStat(Stat.STRENGTH); int playerInRoomStrenght = p.rollStat(Stat.STRENGTH); int damage = Math.max(0, insanePlayerStrenght - playerInRoomStrenght); p.getCharacter().updateStatFromCombat(Stat.STAMINA, damage); } } } /** * @return if the monster kills all players the game is won, return true. */ @Override public boolean winConditionChecker() { if (game.getPlayerList().isEmpty() || (game.getPlayerList().size() == 1 && game.getPlayerList().get(0).isHaunted())) { game.notifyGameOver(); return true; } return false; } @Override public String getHauntText() { return hauntText; } }
package com.tencent.mm.plugin.wenote.ui.nativenote.voiceview; interface a$a { void Sw(String str); void cba(); }
#include<stdio.h> int main() { int n,i=1,t,x,sum=0; scanf("%d",&n); while(i<n) { if(n%i==0) sum=sum+i; i++; } if(n==sum) printf("Not Abundant Number"); else printf("Abundant Number"); return 0; }
package com.tencent.mm.plugin.product.ui; import com.tencent.mm.plugin.product.ui.g.a; class MallGalleryUI$2 implements a { final /* synthetic */ MallGalleryUI lSt; MallGalleryUI$2(MallGalleryUI mallGalleryUI) { this.lSt = mallGalleryUI; } public final void bnd() { MallGalleryUI.c(this.lSt); } }
package com.happybudui.springbase.exception; //CopyRight © 2018-2018 Happybudui All Rights Reserved. //Written by Happybudui public class SpringBaseException extends RuntimeException{ private int errorcode; private String message; public SpringBaseException(){ super(); } public SpringBaseException(int errorcode){ super("error occurred!"); this.errorcode=errorcode; this.message="error!"; } public SpringBaseException(String message){ super(message); this.errorcode=200; this.message=message; } public SpringBaseException(int errorcode, String message ){ super(message); this.errorcode=errorcode; this.message=message; } public int getErrorcode() { return errorcode; } public void setErrorcode(int errorcode) { this.errorcode = errorcode; } @Override public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
package instructable.server.dal; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.List; /** * Created by Amos Azaria on 13-Aug-15. * * static class meant to record what user said, what the system replied and the logical form */ public class InteractionRecording { private static final String interactionTable = "interaction"; private static final String userIdCol = "user_id"; private static final String fullAltCol = "full_alt"; private static final String selSentenceCol = "sentence"; private static final String logicalFormCol = "logical_form"; private static final String systemReplyCol = "reply"; private static final String isSuccessCol = "success"; private InteractionRecording() { //static class } static public void addUserUtterance(String userId, List<String> fullUserAlternatives, String selectedSentence, String logicalForm, String systemReply, boolean isSuccess) { try ( Connection connection = InstDataSource.getDataSource().getConnection(); PreparedStatement pstmt = connection.prepareStatement("insert into "+ interactionTable + " (" + userIdCol + "," + fullAltCol + "," + selSentenceCol + "," + logicalFormCol + "," + systemReplyCol + "," + isSuccessCol + ") values (?,?,?,?,?,?)"); ) { String allAlterASR = String.join("^", fullUserAlternatives); if (selectedSentence.length() >= 3000-1) selectedSentence = selectedSentence.substring(0,3000-2); if (selectedSentence.length() >= 1000-1) selectedSentence = selectedSentence.substring(0,1000-2); pstmt.setString(1, userId); pstmt.setString(2, allAlterASR); pstmt.setString(3, selectedSentence); pstmt.setString(4, logicalForm); pstmt.setString(5, systemReply); pstmt.setBoolean(6, isSuccess); //PreparedStatement pstmt = con.prepareStatement("update "+instanceValTableName+" set "+fieldJSonValColName+" = "+fieldVal.toString()+" where "+userIdColName+"="+userId + " and "+conceptColName+"="+conceptName+" and "+instanceColName+"="+instanceName+" and "+fieldColName+"="+fieldName); pstmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } }
package enthu_l; public class e_1245 { public static void main(String[] args){ for (int i = 0; i < 10; i++) System.out.print(i + " "); //1 for (int i = 10; i > 0; i--) System.out.print(i + " "); //2 int i = 20; //3 System.out.print(i + " "); //4 } }
package com.yunhe.billmanagement.entity; import java.io.Serializable; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; /** * <p> * 账户转账表(ymy) * </p> * * @author 杨明月 * @since 2019-01-02 */ @Data @EqualsAndHashCode(callSuper = false) @Accessors(chain = true) @TableName("account_transfer") public class AccountTransfer implements Serializable { private static final long serialVersionUID = 1L; /** * ID */ @TableId(value = "id",type = IdType.AUTO) private Integer id; /** * 转出账户 */ @TableField(value = "at_out_account") private String atOutAccount; /** * 转出日期 */ @TableField(value = "at_out_time") private String atOutTime; /** * 转入账户 */ @TableField(value = "at_into_account") private String atIntoAccount; /** * 到账日期 */ @TableField(value = "at_into_time") private String atIntoTime; /** * 金额 */ @TableField(value = "at_money") private Double atMoney; /** * 手续费 */ @TableField(value = "at_charge") private Double atCharge; /** * 手续费支付方 */ @TableField(value = "at_charge_person") private String atChargePerson; /** * 经手人 */ @TableField(value = "at_person") private String atPerson; /** *备注 */ @TableField(value = "at_remark") private String atRemark; }
package com.gzpy.remark.service; import org.springframework.data.domain.Page; import com.gzpy.remark.entity.Remark; public interface RemarkService { public Page findRemark(int currentpage, int size); public Remark findRemarkById(String remarkId); public Remark updateRemark(Remark remark); public Page findRemarkBySearch(int currentpage, int size,String name,String status); public Page findRemarkByDelStatus(int currentpage,int size); public Remark delRemarkById(String remarkId); public Remark saveRemark(Remark remark); }
package task3; import java.util.*; import java.util.HashMap; public class HashExmp { public static void main(String[] args){ // TODO Auto-generated method stub HashMap<String,Integer> obj=new HashMap<String,Integer>(); HashMap<String,Integer> obj1=new HashMap<String,Integer>(); obj.put("one",1); obj.put("two", 2); obj.put("three", 3); obj.put("four",4); obj1.putAll(obj); if(obj.containsValue(1)) { System.out.println("contains value"); }else { System.out.println("not having the value"); } Iterator<String> itr=obj.keySet().iterator(); while(itr.hasNext()) { System.out.println(itr.next()); } Iterator<Integer> itr1=obj.values().iterator(); while(itr1.hasNext()) { System.out.println(itr1.next()); } Iterator<Map.Entry<String,Integer>> itr2=obj.entrySet().iterator(); while(itr2.hasNext()) { System.out.println(itr2.next()); } Iterator<Integer> itr4=obj1.values().iterator(); while(itr4.hasNext()) { System.out.println(itr4.next()); } } }
package com.flightbooking.tests; import com.flightbooking.pages.FlightBookingPage; import org.testng.Assert; import org.testng.annotations.Test; public class FlightBookingTest extends FlightBookingPage { @Test public void verifyThatResultsAppearForAOneWayJourney() { String source = "Bangalore"; String destination = "Delhi"; selectAOneWayFlight(source,destination); Assert.assertTrue(isSearchSummaryPresent(),"Flight Search Summary are not displayed"); } }
package primitivedatatypes.src; public class byteDataType { public static void main(String[] args) { byte minByteval = Byte.MIN_VALUE; byte maxByteVal = Byte.MAX_VALUE; System.out.println("Byte min value = " + minByteval); System.out.println("Byte max value = " + maxByteVal); } }
package net.minecraft.network.play.client; import java.io.IOException; import net.minecraft.network.INetHandler; import net.minecraft.network.Packet; import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayServer; import net.minecraft.util.EnumHand; public class CPacketAnimation implements Packet<INetHandlerPlayServer> { private EnumHand hand; public CPacketAnimation() {} public CPacketAnimation(EnumHand handIn) { this.hand = handIn; } public void readPacketData(PacketBuffer buf) throws IOException { this.hand = (EnumHand)buf.readEnumValue(EnumHand.class); } public void writePacketData(PacketBuffer buf) throws IOException { buf.writeEnumValue((Enum)this.hand); } public void processPacket(INetHandlerPlayServer handler) { handler.handleAnimation(this); } public EnumHand getHand() { return this.hand; } } /* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\net\minecraft\network\play\client\CPacketAnimation.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
/* * 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 hr.softwarecity.osijek.controllers; import hr.softwarecity.osijek.model.Zone; import hr.softwarecity.osijek.repositories.ZoneRepository; import java.util.List; import org.jboss.logging.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * * @author Leon */ @RestController @RequestMapping(value = "/zone") public class ZoneController { ZoneRepository zoneRepository; @Autowired public ZoneController(ZoneRepository zoneRepository){ this.zoneRepository =zoneRepository; } @RequestMapping(value = "/") public List<Zone> findAll() { Logger.getLogger("ZoneController.java").log(Logger.Level.INFO, "Recognized request to / root path for zone"); Logger.getLogger("ZoneController.java").log(Logger.Level.INFO, "Returning list of zones"); return zoneRepository.findAll(); } }
package com.qtrj.simpleframework.ssh.service; import java.util.HashMap; import java.util.Map; public class ServiceFactory { private static Map serviceMap = new HashMap<>(); public static <T> T getInstance(Class<T> clazz) { Object o = serviceMap.get(clazz); if (null == o) { o = (new CglibProxy()).get(clazz); serviceMap.put(clazz, o); } return (T)o; } }
package com.example.service; import java.nio.file.Path; import java.util.stream.Stream; import org.springframework.core.io.Resource; import org.springframework.web.multipart.MultipartFile; public interface StorageService { void store (int id, MultipartFile file); Stream<Path> loadAll(int id); Resource loadAsResource(int id, String filename); }
package com.tencent.mm.plugin.t; import com.tencent.mm.bt.h; import com.tencent.mm.kernel.api.bucket.d; import com.tencent.mm.kernel.g; import com.tencent.mm.storage.bc; import java.util.HashMap; public final class a implements com.tencent.mm.kernel.api.bucket.a, d, com.tencent.mm.plugin.t.a.a { private bc lby; public final bc FY() { g.Ek(); g.Eg().Ds(); return this.lby; } public final void onDataBaseOpened(h hVar, h hVar2) { this.lby = new bc(hVar); } public final void onDataBaseClosed(h hVar, h hVar2) { } public final HashMap<Integer, h.d> collectDatabaseFactory() { HashMap<Integer, h.d> hashMap = new HashMap(); hashMap.put(Integer.valueOf("MediaCheckDumplicationStorage".hashCode()), new 1(this)); return hashMap; } }
import org.apache.commons.io.FileUtils; import org.apache.lucene.document.Field; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import org.junit.Test; import java.awt.*; import java.io.File; import java.io.IOException; public class luceneTest1 { @Test public void creatInddex() throws Exception { //1、创建一个Director对象,指定索引库保存的位置 Directory directory = FSDirectory.open(new File("D:\\temp\\index").toPath()); //2、基于Directory对象创建一个IndexWriter对象 IndexWriterConfig config = new IndexWriterConfig(); IndexWriter indexWriter = new IndexWriter(directory, config); //3、读取磁盘上的文件,对应每个文件创建一个文档对象。 File dir = new File("D:\\code\\java就业班\\lucene_git_eclipse\\lucene\\02.参考资料"); File[] files = dir.listFiles(); for (File file : files) { String fileName = file.getName(); String filePath = file.getPath(); String fileContent = FileUtils.readFileToString(file); long fileSize = FileUtils.sizeOf(file); //4、向文档对象中添加域 // TextField fileNameField = new TextField("filename", fileName, Field.Store.YES); Field fileNameField = new TextField("filename", fileName, Field.Store.YES); } System.out.println("22222"); //5、把文档对象写入索引库 //6、关闭indexwriter对象 } }
package Pages; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; public class NewAccountPage { @FindBy(linkText = "New Account") public WebElement NewAccountField; @FindBy(name = "cusid") public WebElement CustomerIdField; @FindBy(name = "selaccount") public WebElement CustomerAcctTypeDropDownField; @FindBy(name = "inideposit") public WebElement CustomerDepoField; @FindBy(name = "button2") public WebElement SubmitFiled; @FindBy(id = "customer") public WebElement Customertable;// / I created a new customer...this is the @FindBy(xpath= ".//*[@id='Accmsg']/tbody/tr/td") public WebElement gettingText; @FindBy (xpath= "html/body/p/a") public WebElement GetBAcktohomePgae; public void NewAccount(String id, String amt) { NewAccountField.click(); CustomerIdField.sendKeys("1234"); CustomerAcctTypeDropDownField.click(); CustomerDepoField.sendKeys("amt"); SubmitFiled.click(); gettingText.getText(); GetBAcktohomePgae.click(); } }
// Notificable.java package inmobiliarias; public interface Notificable { String getNombre(); String getEmail(); void avisarCambioPrecio(Inmueble x, int nuevoPrecio); void avisarReserva(Inmueble x); void avisarVenta(Inmueble x); }
package things.entity; import things.GameMain; import things.Player; import things.SpaceInvadersGUI; import things.entity.singleton.FiredBullets; import things.entity.strategy.movement.MovementModified; import javax.swing.*; import java.awt.*; /** * This is an instantiable class called Tank for creating a Tank entity. * It is a sub-class of GameComponent therefore it inherits all of its * attributes and abstract methods * * @author Darren Moriarty * created on 11/11/2016. * * @version 2.0 */ public class Tank extends GameComponent{ private Player player; private int livesLeft; private FiredBullets alienBulls = FiredBullets.getAlienBullets(); private final int RIGHT_OF_SCREEN = 1000 - width - 25; private final int LEFT_OF_SCREEN = 25; /** * 6 argument constructor method * * @param topLeftXPos The initial x coordinate of the instantiated Tank entity object * @param topLeftYPos The initial y coordinate of the instantiated Tank entity object * @param width The initial width of the entity * @param height The initial height of the Tank entity * @param color The initial colour of the Tank entity * @param livesLeft The initial amount of lives the Tank entity has * @param horizontalSpeed The initial horizontal speed of the Tank entity */ public Tank(int topLeftXPos, int topLeftYPos, int width, int height, Color color, int livesLeft, int horizontalSpeed) { super(topLeftXPos, topLeftYPos, width, height, color); setLivesLeft(livesLeft); setMovement(new MovementModified(this)); movement.setSpeed(horizontalSpeed); } /** * This sets the amount of the lives for the entity * @param livesLeft is the amount of lives */ public void setLivesLeft(int livesLeft) { this.livesLeft = livesLeft; } /** * This returns the amount of lives the entity has remaining * @return the amount of lives left */ @Override public int getLivesLeft(){ return livesLeft; } @Override public void draw(Graphics2D g) { g.setColor(getColor()); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.drawRect(getTopLeftXPos(), getTopLeftYPos(), getWidth(), getHeight()); g.fillRect(getTopLeftXPos(), getTopLeftYPos(), getWidth(), getHeight()); } // This method decides what to do every time the screen refreshes @Override public void update(){ moveSprite(); if (metRightBorder()){ topLeftXPos = RIGHT_OF_SCREEN; } if (metLeftBorder()){ topLeftXPos = LEFT_OF_SCREEN; } // checking for collisions with the tank for (int k = 0; k < alienBulls.size(); k++) { Bullet alienBullet = alienBulls.getBullet(k); if (alienBullet.collidesWith(this)) { System.out.println(getLivesLeft()); try{ playSound("sounds/explosion.wav"); } catch (Exception e) { e.printStackTrace(); } // reducing the lives of the tank setLivesLeft(getLivesLeft() - 1); // setting the colour of the lives to black SpaceInvadersGUI.tankLife1.setColor(Color.BLACK); if(getLivesLeft() == 1){ SpaceInvadersGUI.tankLife2.setColor(Color.BLACK); } alienBulls.removeBullet(alienBullet); // if the lives run out if (getLivesLeft() < 1){ SpaceInvadersGUI.tankLife3.setColor(Color.BLACK); this.setTopLeftXPos(-100); this.setTopLeftYPos(-100); this.setWidth(-100); this.setHeight(-100); //Keeping track of the highScores GameMain.getGameMain().manageHighScores(); } } } } private boolean metLeftBorder() { return topLeftXPos < LEFT_OF_SCREEN; } private boolean metRightBorder() { return topLeftXPos > RIGHT_OF_SCREEN; } public String toString(){ return "Tank class is working"; } }
package ars.ramsey.interviewhelper.fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import ars.ramsey.interviewhelper.R; import ars.ramsey.interviewhelper.adapter.ExplorePagerAdapter; /** * Created by Ramsey on 2017/5/10. */ public class ExploreFragment extends Fragment { private ViewPager mViewPager; private TabLayout mTabLayout; private PagerAdapter mAdapter; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.explore_layout,null); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mViewPager = (ViewPager)view.findViewById(R.id.explore_pager); mTabLayout = (TabLayout)view.findViewById(R.id.explore_pager_tabs); mAdapter = new ExplorePagerAdapter(getChildFragmentManager()); mViewPager.setAdapter(mAdapter); mTabLayout.setupWithViewPager(mViewPager); mTabLayout.setTabMode(TabLayout.MODE_FIXED); } @Override public void onResume() { super.onResume(); } @Override public void onPause() { super.onPause(); } @Override public void onStop() { super.onStop(); } @Override public void onDestroy() { super.onDestroy(); } }
import interviewbit.array.NobleInteger; import interviewbit.binarysearch.Matrix_Search; import interviewbit.hashing.Fraction; import interviewbit.linkedlist.ListNode; import interviewbit.string.LongestCommonPrefix; import java.util.ArrayList; import java.util.Arrays; public class Index { public static void main(String s[]) { System.out.println("Running..."); ArrayList<Integer> a = new ArrayList<Integer>(Arrays.asList(-4, 7, 5, 3, 5, -4, 2, -1, -9, -8, -3, 0, 9, -7, -4, -10, -4, 2, 6, 1, -2, -3, -1, -8, 0, -8, -7, -3, 5, -1, -8, -8, 8, -1, -3, 3, 6, 1, -8, -1, 3, -9, 9, -6, 7, 8, -6, 5, 0, 3, -4, 1, -10, 6, 3, -8, 0, 6, -9, -5, -5, -6, -3, 6, -5, -4, -1, 3, 7, -6, 5, -8, -5, 4, -3, 4, -6, -7, 0, -3, -2, 6, 8, -2, -6, -7, 1, 4, 9, 2, -10, 6, -2, 9, 2, -4, -4, 4, 9, 5, 0, 4, 8, -3, -9, 7, -8, 7, 2, 2, 6, -9, -10, -4, -9, -5, -1, -6, 9, -10, -1, 1, 7, 7, 1, -9, 5, -1, -3, -3, 6, 7, 3, -4, -5, -4, -7, 9, -6, -2, 1, 2, -1, -7, 9, 0, -2, -2, 5, -10, -1, 6, -7, 8, -5, -4, 1, -9, 5, 9, -2, -6, -2, -9, 0, 3, -10, 4, -6, -6, 4, -3, 6, -7, 1, -3, -5, 9, 6, 2, 1, 7, -2, 5)); //ArrayList<Integer> a = new ArrayList<Integer>(Arrays.asList(-4, -2, 0, -1, -6)); //ArrayList<Integer> a = new ArrayList<Integer>(Arrays.asList(8,4,4,7,5,2,0,2,5,0)); int z = new NobleInteger().solve(a); System.out.println("Z = " + z); } public ListNode createListNode(ArrayList<Integer> al) { ListNode a = null, m, n; if (al.size() == 0) { return a; } a = new ListNode(al.get(0)); m = a; int i = 1; while (i < al.size()) { n = new ListNode(al.get(i)); m.next = n; m = m.next; i++; } return a; } public ListNode mergeListNode(ListNode a, ListNode b) { if (a == null) { return b; } if (b == null) { return a; } ListNode aHead = a; while (aHead.next != null) { aHead = aHead.next; } aHead.next = b; return a; } public void printListNode(String s, ListNode a) { ListNode t = a; if (t == null) { System.out.println("EMPTY LISTNODE !"); return; } System.out.print("ListNode " + s + " : "); while (t.next != null) { System.out.print(t.val + ", "); // ( " + t.next + " ) t = t.next; } System.out.println(t.val + " ."); // (" + t.next + ") } }
package com.bingo.code.example.design.adapter.adapterlog; import java.util.List; /** * ��־�ļ������ӿ� */ public interface LogFileOperateApi { public List<LogModel> readLogFile(); public void writeLogFile(List<LogModel> list); }
package loginYGestionDeUsuarios; /** * Alberga las variables globales del sistema. * * @author Usuario */ public class VariablesDelSistema { /** * Identifica al usuario que inició sesión. * Es su id de empleado y de usuario en la base de datos. La clave principal en la tabla usuario es idEmpleado. * Inicialmente vale 0 indicando que ningún usuario inició sesión aún. */ public static Integer idUsuarioActual = 0; /** * Indica si el usuario actual del sistema es un administrador. Sirve principalmente para que el constructor de la * pantalla principal sepa si debe activar aquellos ítems de menú reservados para los administradores del sistema. */ public static Boolean usuarioEsAdministrador = false; /** * indica si se restauró la contraseña del usuario actual, en cuyo caso * deberá cambiarla por otra obligatoriamente. También será false si * es la primera vez que el usuario inicia sesión en el sistema. */ public static Boolean contraseñaRestaurada = false; }
package com.mx.profuturo.bolsa.model.graphics.vo; import com.mx.profuturo.bolsa.model.graphics.vo.elements.StackedChartValue; public class StackedChartWidgetVO extends WidgetBase { private String size; private String labelX; private String labelY; private StackedChartValue value; public String getSize() { return size; } public void setSize(String size) { this.size = size; } public String getLabelX() { return labelX; } public void setLabelX(String labelX) { this.labelX = labelX; } public String getLabelY() { return labelY; } public void setLabelY(String labelY) { this.labelY = labelY; } public StackedChartWidgetVO() { this.type = "chart"; this.variant = "bar-chart-stacked"; this.size = "lg"; } public StackedChartValue getValue() { return value; } public void setValue(StackedChartValue value) { this.value = value; } }
package com.flutterwave.raveandroid.rave_presentation.account; import android.webkit.WebResourceRequest; import android.webkit.WebView; import androidx.annotation.Nullable; import com.flutterwave.raveandroid.rave_core.models.Bank; import java.util.List; public interface AccountPaymentCallback { /** * Passes a list of banks available for this payment method. * * @param banks List of banks. */ void onBanksListRetrieved(List<Bank> banks); /** * Called when there is an issue retrieving the list of banks. * * @param message */ void onGetBanksRequestFailed(String message); /** * Called to indicate that a background task is running, e.g. a network call. * This should typically show or hide a progress bar. * * @param active If true, background task is running. If false, background task has stopped */ void showProgressIndicator(boolean active); /** * Called to trigger an otp collection. The OTP should be collected from the user and passed to * the PaymentManager using {@link AccountPaymentManager#submitOtp(String)} to continue the payment. */ void collectOtp(String message); /** * Called to display a {@link android.webkit.WebView} for charges that require webpage authentication. * When the payment is completed, the authentication page redirects to a {@link com.flutterwave.raveandroid.rave_java_commons.RaveConstants#RAVE_3DS_CALLBACK predefined url} * with the payment details appended to the url. * <p> * You should override the webview client's {@link android.webkit.WebViewClient#shouldOverrideUrlLoading(WebView, WebResourceRequest)} shouldOverrideUrlLoading} * function to check if the {@link WebResourceRequest#getUrl() url being loaded} contains the * {@link com.flutterwave.raveandroid.rave_java_commons.RaveConstants#RAVE_3DS_CALLBACK predefined redirect url}. * <p> * If it does, it means the transaction has been completed and you can now call {@link AccountPaymentManager#onWebpageAuthenticationComplete()} to check the transaction status. * * @param authenticationUrl The url to the authentication page */ void showAuthenticationWebPage(String authenticationUrl); /** * Called when an error occurs with the payment. The error message can be displayed to the users. * * @param errorMessage A message describing the error * @param flwRef The Flutterwave reference to the transaction. */ void onError(String errorMessage, @Nullable String flwRef); /** * Called when the transaction has been completed successfully. * * @param flwRef The Flutterwave reference to the transaction. */ void onSuccessful(String flwRef); }
package com.klapeks.colinker.bungee; import java.util.HashMap; import java.util.List; import com.klapeks.colinker.Functions; import com.klapeks.coserver.aConfig; import com.klapeks.coserver.dCoserver; import com.klapeks.funcs.dRSA; import com.klapeks.funcs.uArrayMap; import net.md_5.bungee.Util; import net.md_5.bungee.api.ProxyServer; public class ColinServer { public static int last_id = 0; // static HashMap<String, Integer> mode$last_id = new HashMap<>(); static uArrayMap<String, ColinServer> mode$server = new uArrayMap<>(); static HashMap<Integer, ColinServer> id$server = new HashMap<>(); // static ColinServer makeServer(String mode, String ip, int port) { // String s = ip+":"+port; // if (ip$server.containsKey(s)) return ip$server.get(s); // return createServer(mode, ip, port); // } static ColinServer findServer(String mode, String ip, int mcport) { List<ColinServer> css = mode$server.get(mode); for (ColinServer cs : css) { if (cs.ip.equals(ip) && cs.mcport == mcport) return cs; } return null; } static ColinServer remakeServer(String mode, String ip, int mcport) { deleteServer(findServer(mode, ip, mcport)); return createServer(mode, ip, mcport); } private static ColinServer createServer(String mode, String ip, int port) { ColinServer cs = new ColinServer(mode, ip, port); mode$server.addIn(mode, cs); id$server.put(cs.id, cs); return cs; } static ColinServer deleteServer(String mode, int id) { // String s = ip+":"+port; ColinServer cs = id$server.get(id); mode$server.remove(mode, cs); id$server.remove(id); return cs; } static ColinServer deleteServer(ColinServer cs) { if (cs==null) return cs; cs.onDisabling(); mode$server.remove(cs.mode, cs); id$server.remove(cs.id); return cs; } static void recalculateServers() { uArrayMap<String, ColinServer> am = new uArrayMap<>(); int maxonline = 0; for (String mode : mode$server.keySet()) { for (ColinServer cs : mode$server.get(mode)) { try { if (cs.sendData("isalive").equals("yesiamalive")) { maxonline += cs.maxonline; continue; } } catch (Throwable t) { if (aConfig.useDebugMsg) t.printStackTrace(); } am.addIn(mode, cs); } } ColinConnector.max_online = maxonline; int i = 0; for (String mode : am.keySet()) { for (ColinServer cs : am.get(mode)) { deleteServer(cs); i++; } } if (i > 0) Functions.log("§e{0} §6servers was disabled due crash or something", i); am.clear(); } // public static ColinServer getServerByIP(String ip, int port) { // return ip$server.get(ip+":"+port); //} public static ColinServer getServerByID(int id) { return id$server.get(id); } final int mcport, id; public int rcport; final String mode, ip; boolean isEnabled = false; private ColinServer(String mode, String ip, int mcport) { this.ip = ip; this.mcport = mcport; this.mode = mode; this.id = ++last_id; } int maxonline = 0; void onEnabling(Object... args) { isEnabled = true; maxonline = args.length > 0 ? (Integer) args[0] : 0; ColinConnector.max_online += maxonline; ProxyServer.getInstance().getServers().put(mode.split("")[0]+id, ProxyServer.getInstance() .constructServerInfo(mode.split("")[0]+id, Util.getAddr(ip+":"+mcport), "mode:"+mode, false)); Functions.log("§aServer §6" + id + "§7(§e"+ip+":"+mcport+"§f)§a was enabled and added as §b" + mode + "§a.§r"); Functions.log("§aServer §9{0}§a was enabled", id); } public String getMode() { return mode; } void onDisabling() { isEnabled = false; ColinConnector.max_online -= maxonline; ProxyServer.getInstance().getServers().remove(mode.split("")[0]+id); Functions.log("§cServer §9{0}§c was disabled", id); } public String sendData(String cmd, Object... args) { cmd = dRSA.base64_encode(cmd); for (Object arg : args) { cmd += " " + dRSA.base64_encode(arg+""); } if (aConfig.useSecurity) { return dCoserver.securitySend(ip, rcport, "colinkertos " + cmd, false); } else { return dCoserver.send(ip, rcport, "colinkertos " + cmd, false); } } }
package pl.edu.amu.datasupplier.repository; import org.bson.types.ObjectId; import org.springframework.data.domain.Sort; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.stereotype.Repository; import pl.edu.amu.datasupplier.model.TestCaseTemplate; import java.util.List; @Repository public interface TestCaseTemplateRepository extends MongoRepository<TestCaseTemplate, ObjectId> { TestCaseTemplate findById(ObjectId id); List<TestCaseTemplate> findByTagsIn(List<String> tags, Sort sort); }
import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.ChoiceDialog; import javafx.scene.layout.GridPane; import javafx.scene.paint.Color; import javafx.stage.Stage; public class Grid3Dbig { Cell [][] field=new Cell[10][15]; Grid3Dbig(){ initializeScene(); } void initializeScene() { Stage ps=new Stage(); GridPane pane=new GridPane(); pane.setAlignment(Pos.CENTER); Scene scene=new Scene(pane,1280,760); ps.setResizable(false); Button newgame=new Button("New Game"); newgame.setTranslateX(-580+80.5); newgame.setTranslateY(-175); newgame.setPrefSize(90, 30); newgame.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent arg0) { ChoiceDialog<String> savedialogue=new ChoiceDialog<String>("Yes","No"); savedialogue.setContentText("Do you Want To save the Game"); savedialogue.showAndWait(); ps.close(); initializeScene(); } }); pane.add(newgame, 1, 0); Button Savegame=new Button("Save Game"); Savegame.setTranslateX(-222.25+190.5); Savegame.setTranslateY(-175); Savegame.setPrefSize(90, 30); pane.add(Savegame, 1, 0); Button Exitgame=new Button("Exit Game"); Exitgame.setTranslateX(-222.25+300.5); Exitgame.setTranslateY(-175); Exitgame.setPrefSize(90, 30); Exitgame.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent arg0) { //SAVE THE GAME ADD CODE ChoiceDialog<String> exitdialogue=new ChoiceDialog<String>("Yes","No"); exitdialogue.setContentText("Are you Sure you Want to exit"); exitdialogue.showAndWait(); if(exitdialogue.getResult().equals("Yes")) { // SAVE GAME ADD CODE } ps.close(); } }); pane.add(Exitgame, 1, 0); double i=500/15; double j=364/10; double xupda=0; double yupda=0; for(int k=0;k<10;k++) { for(int u=0;u<15;u++) { Position c1p=new Position(-560+xupda,-155.67+yupda); Cell c1=new Cell(pane, i,j,c1p , k , u); c1.ballcolor=Color.BLACK; if((u==0 && k==0) || (u==14 && k==9) || (u==14 && k==0) || (u==0 && k==14)) { c1.settype("corner",k,u); }else if(((u>=1 && u<=14) && k==0) || (u==0 && (k>=1 && k<=9 )) || (u==14 &&( k>=1 && k<=9 )) || ((u>=1 && u<=14) && k==9)) { c1.settype("edge",k,u); }else { c1.settype("between",k,u); } field[k][u]=c1; c1.setposition(c1p); //c1.click(pane,"9 * 6",field,c1.gettype()); xupda=xupda+80.8; } yupda=yupda+31.4; xupda=0; } for(int k=0;k<10;k++) { for(int u=0;u<15;u++) { Cell c=field[k][u]; c.click(pane, "10 * 15", field,c.gettype(),c.retfieldrow(),c.retfieldcol()); } } ps.setScene(scene); ps.show(); } }
package com.boniu.ad.aes; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; public class AESUtil { public static String encrypt(String data, String key) { // return data; try { SecretKeySpec spec = new SecretKeySpec(key.getBytes("UTF-8"), "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, spec, new IvParameterSpec(new byte[cipher.getBlockSize()])); byte[] bs = cipher.doFinal(data.getBytes("UTF-8")); return JukeBase64.encode(bs); } catch (Exception e) { return ""; // throw new RuntimeException("AES加密异常", e); } } public static String decrypt(String data, String key) { // return data; try { SecretKeySpec spec = new SecretKeySpec(key.getBytes("UTF-8"), "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, spec, new IvParameterSpec(new byte[cipher.getBlockSize()])); byte[] originBytes = JukeBase64.decode(data); byte[] result = cipher.doFinal(originBytes); return new String(result, "UTF-8"); } catch (Exception e) { return ""; // throw new RuntimeException("AES解密异常", e); } } }
package com.jx.sleep_dg.ui; import android.os.Bundle; import android.support.annotation.Nullable; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import com.jx.sleep_dg.R; import com.jx.sleep_dg.base.BaseActivity; import java.util.HashMap; import java.util.Map; /** * 注册页面 * Created by Administrator on 2018/5/21. */ public class RegistActivity extends BaseActivity { Button btnFinish; TextView tvCode; EditText etPhone; EditText etCode; EditText etPwd; ImageView iv_password; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setLayout(R.layout.activity_regist); bindView(); } @Override public void bindView() { setToolbarTitle(R.string.register); } @Override public void onClick(View view) { super.onClick(view); switch (view.getId()) { case R.id.btn_finish: //注册 doRegist(); break; case R.id.tv_code: if (TextUtils.isEmpty(etPhone.getText().toString())) { etPhone.requestFocus(); etPhone.setError(getResources().getString(R.string.normal_input_null)); return; } break; } } private void doRegist() { String phone = etPhone.getText().toString(); String code = etCode.getText().toString(); String pwd = etPwd.getText().toString(); if (TextUtils.isEmpty(phone)) { etPhone.requestFocus(); etPhone.setError(getResources().getString(R.string.normal_input_null)); return; } if (TextUtils.isEmpty(code)) { etCode.requestFocus(); etCode.setError(getResources().getString(R.string.normal_input_null)); return; } if (TextUtils.isEmpty(pwd)) { etPwd.requestFocus(); etPwd.setError(getResources().getString(R.string.normal_input_null)); return; } Map<String, String> map = new HashMap<>(); map.put("phone_number", phone); map.put("password", pwd); map.put("messagecode", code); } }
package com.nmovie.springboot.crudapp.service; import java.util.List; import com.nmovie.springboot.crudapp.entity.MovieList; public interface MovieService { public List<MovieList> fineAll(); public MovieList findById(int theId); public void save(MovieList theMovie); public void deleteById(int theId); }
package com.example.accounting_app.function; import android.view.View; import com.bigkoo.pickerview.builder.TimePickerBuilder; import com.bigkoo.pickerview.listener.OnTimeSelectListener; import java.text.SimpleDateFormat; import java.util.Date; /** * @Creator cetwag yuebanquan * @Version V2.0.0 * @Time 2019.6.28 * @Description 这个类包含了数据间的类型转换函数以及日期的提取格式等相关函数 */ public class type_or_format_conversion { /** * @parameter date传入的Date型日期 * @description 将传入的Date型日期数据转换为字符串, 只取月份 * @Time 2019/6/28 22:32 */ public String getTimeMonth(Date date) { SimpleDateFormat format = new SimpleDateFormat("M"); return format.format(date); } /** * @parameter date传入的Date型日期 * @description 将传入的Date型日期数据转换为字符串并格式化,年月日都取 * @Time 2019/6/29 11:14 */ public String getTimeYMD(Date date) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); return format.format(date); } /** * @parameter date传入的Date型日期 * @description 将传入的Date型日期数据转换为字符串并格式化,年月日时分秒都取 * @Time 2019/6/29 11:14 */ public String getTimeYMDhhmmss(Date date) { //这里有个问题,取出的时分秒不一和电脑的不一致,但比较大小够用了,后期更改! SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); return format.format(date); } }
package eg.edu.alexu.csd.oop.db; import java.util.ArrayList; public interface Column { public void addNewRecord(Object values); public String getColumnName(); public ArrayList<Object> getRows(); public String getDataType(); public void setColumnName(String columnName); public String getTableName(); public void setTableName(String tableName); public void setDataType(String dataType); public void setRows(ArrayList<Object> rows); }
package chess.pkg2; public class Rook extends Piece{ int[] rookOffset = {-8,-1,1,8}; public final static int[] whiteRookEvaluator = { 0, 0, 0, 0, 0, 0, 0, 0, 5,20,20,20,20,20,20, 5, -5, 0, 0, 0, 0, 0, 0,-5, -5, 0, 0, 0, 0, 0, 0,-5, -5, 0, 0, 0, 0, 0, 0,-5, -5, 0, 0, 0, 0, 0, 0,-5, -5, 0, 0, 0, 0, 0, 0,-5, 0, 0, 0, 5, 5, 0, 0, 0 }; public final static int[] blackRookEvaluator = { 0, 0, 0, 5, 5, 0, 0, 0, -5, 0, 0, 0, 0, 0, 0,-5, -5, 0, 0, 0, 0, 0, 0,-5, -5, 0, 0, 0, 0, 0, 0,-5, -5, 0, 0, 0, 0, 0, 0,-5, -5, 0, 0, 0, 0, 0, 0,-5, 5,20,20,20,20,20,20, 5, 0, 0, 0, 0, 0, 0, 0, 0 }; public Rook(int piecePosition, int Alliance) { super(piecePosition, Alliance); } @Override public int getPointStatic() { return 500; } @Override public String toString(){ // if(alliance == 0){ return "R"; // }else{ // return "r"; // } } @Override public int[] getPossibleNextPosition(ChessPosition positionChess) { int[] possibleRookNextPosition = new int[14]; int j; j=0; for(int i=0;i<14;++i){ possibleRookNextPosition[i] = 100; } int testNextPosition; testNextPosition = piecePosition; while((testNextPosition >= 0) && (testNextPosition <64) && (testNextPosition % 8 != 7) && ((testNextPosition + rookOffset[2])>=0)){ testNextPosition += rookOffset[2]; if(positionChess.chessBoard.get(testNextPosition)==null){ possibleRookNextPosition[j] = testNextPosition; ++j; }else{ Piece pieceAtPosition = positionChess.chessBoard.get(testNextPosition); if(pieceAtPosition.getAlliance() == this.getAlliance()){ break; }else{ possibleRookNextPosition[j] = testNextPosition; ++j; break; } } } testNextPosition = piecePosition; while((testNextPosition >= 0) && (testNextPosition <64) ){ testNextPosition += rookOffset[3]; if((testNextPosition >= 0) && (testNextPosition <64)){ if(positionChess.chessBoard.get(testNextPosition)==null){ possibleRookNextPosition[j] = testNextPosition; ++j; }else{ Piece pieceAtPosition = positionChess.chessBoard.get(testNextPosition); if(pieceAtPosition.getAlliance() == this.getAlliance()){ break; }else{ possibleRookNextPosition[j] = testNextPosition; ++j; break; } } } } testNextPosition = piecePosition; while((testNextPosition >= 0) && (testNextPosition <64) && (testNextPosition % 8 != 0)){ testNextPosition += rookOffset[1]; if(positionChess.chessBoard.get(testNextPosition)==null){ possibleRookNextPosition[j] = testNextPosition; ++j; }else{ Piece pieceAtPosition = positionChess.chessBoard.get(testNextPosition); if(pieceAtPosition.getAlliance() == this.getAlliance()){ break; }else{ possibleRookNextPosition[j] = testNextPosition; ++j; break; } } } testNextPosition = piecePosition; while((testNextPosition >= 0) && (testNextPosition <64) ){ testNextPosition += rookOffset[0]; if((testNextPosition >= 0) && (testNextPosition <64)){ if(positionChess.chessBoard.get(testNextPosition)==null){ possibleRookNextPosition[j] = testNextPosition; ++j; }else{ Piece pieceAtPosition = positionChess.chessBoard.get(testNextPosition); if(pieceAtPosition.getAlliance() == this.getAlliance()){ break; }else{ possibleRookNextPosition[j] = testNextPosition; ++j; break; } } } } return possibleRookNextPosition; } @Override public int getLocationPoint(int location) { if(alliance == 0 ){ return whiteRookEvaluator[location]; }else{ return blackRookEvaluator[location]; } } }
package com.city.beijing.dao.impl; import com.city.beijing.dao.UserBaseDao; import com.city.beijing.dao.mapper.UserBaseMapper; import com.city.beijing.model.UserBase; import com.city.beijing.model.UserBaseExample; import com.city.beijing.utils.Utility; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.util.CollectionUtils; import java.util.List; /** * Created by liuyang on 16-11-8. */ @Repository public class UserBaseDaoImpl implements UserBaseDao{ @Autowired private UserBaseMapper userBaseMapper; public void insertData(UserBase userbase){ userBaseMapper.insertSelective(userbase); } public void updateDataByExample(UserBase userbase, UserBaseExample userbaseExample){ userBaseMapper.updateByExampleSelective(userbase, userbaseExample); } public void updateDataByDynamicExample(UserBase userbase, String mobile){ UserBaseExample userbaseExample = new UserBaseExample(); UserBaseExample.Criteria criteria = userbaseExample.createCriteria(); if(Utility.isNotBlank(mobile)){ criteria.andMobileEqualTo(mobile); } userBaseMapper.updateByExampleSelective(userbase,userbaseExample); } public void updateById(UserBase userbase){ userBaseMapper.updateByPrimaryKeySelective(userbase); } public void deleteById(int dataid){ userBaseMapper.deleteByPrimaryKey(dataid); } public UserBase getDataById(int id){ return userBaseMapper.selectByPrimaryKey(id); } public UserBase getFirstDataByCondition(UserBaseExample userbaseExample){ List<UserBase> checkExceptions = userBaseMapper.selectByExample(userbaseExample); return CollectionUtils.isEmpty(checkExceptions)?null:checkExceptions.get(0); } public List<UserBase> getAllDataByCondition(UserBaseExample userbaseExample){ List<UserBase> checkExceptions = userBaseMapper.selectByExample(userbaseExample); return CollectionUtils.isEmpty(checkExceptions)?null:checkExceptions; } }
/** * MOTECH PLATFORM OPENSOURCE LICENSE AGREEMENT * * Copyright (c) 2010-11 The Trustees of Columbia University in the City of * New York and Grameen Foundation USA. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of Grameen Foundation USA, Columbia University, or * their respective contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY GRAMEEN FOUNDATION USA, COLUMBIA UNIVERSITY * AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRAMEEN FOUNDATION * USA, COLUMBIA UNIVERSITY OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.motechproject.server.ws; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import junit.framework.TestCase; import org.motechproject.server.model.ghana.Community; import org.motechproject.server.model.ExpectedEncounter; import org.motechproject.server.model.ExpectedObs; import org.motechproject.server.service.ContextService; import org.motechproject.server.service.MotechService; import org.motechproject.server.util.MotechConstants; import org.motechproject.ws.Care; import org.motechproject.ws.Gender; import org.motechproject.ws.Patient; import org.openmrs.Location; import org.openmrs.PatientIdentifier; import org.openmrs.PatientIdentifierType; import org.openmrs.PersonAddress; import org.openmrs.PersonName; import static org.easymock.EasyMock.*; public class WebServicePatientModelConverterTest extends TestCase { WebServiceCareModelConverterImpl careModelConverter; PatientIdentifierType motechIdType; private MotechService motechService; private ContextService contextService; @Override protected void setUp() throws Exception { motechService = createMock(MotechService.class); contextService = createMock(ContextService.class); careModelConverter = new WebServiceCareModelConverterImpl(); careModelConverter.setContextService(contextService); motechIdType = new PatientIdentifierType(); motechIdType.setName(MotechConstants.PATIENT_IDENTIFIER_MOTECH_ID); expect(contextService.getMotechService()).andReturn(motechService).atLeastOnce(); } @Override protected void tearDown() throws Exception { motechIdType = null; careModelConverter = null; reset(motechService, contextService); } public void testDefaultedEncounters() { String anc1 = "ANC1", anc2 = "ANC2"; String patient1Id = "Patient1", patient2Id = "Patient2", patient3Id = "Patient3"; String patient1Pref = "Pref1", patient1Last = "Last1", patient1Community = "Comm1"; String patient2Pref = "Pref2", patient2Last = "Last2", patient2Community = "Comm2"; String patient3Pref = "Pref3", patient3Last = "Last3", patient3Community = "Comm3"; Calendar calendar = Calendar.getInstance(); calendar.set(1981, Calendar.JANUARY, 1); Date patient1Birth = calendar.getTime(); calendar.set(1982, Calendar.FEBRUARY, 2); Date patient2Birth = calendar.getTime(); calendar.set(1983, Calendar.MARCH, 3); Date patient3Birth = calendar.getTime(); Community comm1 = new Community(); comm1.setName(patient1Community); Community comm2 = new Community(); comm2.setName(patient2Community); Community comm3 = new Community(); comm3.setName(patient3Community); ExpectedEncounter encounter1 = new ExpectedEncounter(); encounter1.setName(anc1); ExpectedEncounter encounter2 = new ExpectedEncounter(); encounter2.setName(anc2); ExpectedEncounter encounter3 = new ExpectedEncounter(); encounter3.setName(anc2); org.openmrs.Patient patient1 = new org.openmrs.Patient(1); patient1.addIdentifier(new PatientIdentifier(patient1Id, motechIdType, new Location())); patient1.setBirthdate(patient1Birth); patient1.setGender("F"); patient1.addName(new PersonName(patient1Pref, null, patient1Last)); PersonAddress patient1Address = new PersonAddress(); patient1.addAddress(patient1Address); org.openmrs.Patient patient2 = new org.openmrs.Patient(2); patient2.addIdentifier(new PatientIdentifier(patient2Id, motechIdType, new Location())); patient2.setBirthdate(patient2Birth); patient2.setGender("M"); patient2.addName(new PersonName(patient2Pref, null, patient2Last)); PersonAddress patient2Address = new PersonAddress(); patient2.addAddress(patient2Address); org.openmrs.Patient patient3 = new org.openmrs.Patient(3); patient3.addIdentifier(new PatientIdentifier(patient3Id, motechIdType, new Location())); patient3.setBirthdate(patient3Birth); patient3.setGender("F"); patient3.addName(new PersonName(patient3Pref, null, patient3Last)); PersonAddress patient3Address = new PersonAddress(); patient3.addAddress(patient3Address); encounter1.setPatient(patient1); encounter2.setPatient(patient2); encounter3.setPatient(patient3); List<ExpectedEncounter> defaultedEncounters = new ArrayList<ExpectedEncounter>(); defaultedEncounters.add(encounter1); defaultedEncounters.add(encounter2); defaultedEncounters.add(encounter3); expect(motechService.getCommunityByPatient(patient1)).andReturn(comm1); expect(motechService.getCommunityByPatient(patient2)).andReturn(comm2); expect(motechService.getCommunityByPatient(patient3)).andReturn(comm3); replay(motechService, contextService); Care[] cares = careModelConverter .defaultedEncountersToWebServiceCares(defaultedEncounters); verify(motechService, contextService); assertEquals(2, cares.length); Care care1 = cares[0]; assertEquals(anc1, care1.getName()); assertEquals(1, care1.getPatients().length); Patient care1Patient = care1.getPatients()[0]; assertEquals(patient1Id, care1Patient.getMotechId()); assertEquals(patient1Pref, care1Patient.getPreferredName()); assertEquals(patient1Last, care1Patient.getLastName()); assertEquals(patient1Birth, care1Patient.getBirthDate()); assertEquals(Gender.FEMALE, care1Patient.getSex()); assertEquals(patient1Community, care1Patient.getCommunity()); Care care2 = cares[1]; assertEquals(anc2, care2.getName()); assertEquals(2, care2.getPatients().length); Patient care2Patient1 = care2.getPatients()[0]; assertEquals(patient2Id, care2Patient1.getMotechId()); assertEquals(patient2Pref, care2Patient1.getPreferredName()); assertEquals(patient2Last, care2Patient1.getLastName()); assertEquals(patient2Birth, care2Patient1.getBirthDate()); assertEquals(Gender.MALE, care2Patient1.getSex()); assertEquals(patient2Community, care2Patient1.getCommunity()); Patient care2Patient2 = care2.getPatients()[1]; assertEquals(patient3Id, care2Patient2.getMotechId()); assertEquals(patient3Pref, care2Patient2.getPreferredName()); assertEquals(patient3Last, care2Patient2.getLastName()); assertEquals(patient3Birth, care2Patient2.getBirthDate()); assertEquals(Gender.FEMALE, care2Patient2.getSex()); assertEquals(patient3Community, care2Patient2.getCommunity()); } public void testDefaultedEncountersEmpty() { List<ExpectedEncounter> defaultedEncounters = new ArrayList<ExpectedEncounter>(); Care[] cares = careModelConverter .defaultedEncountersToWebServiceCares(defaultedEncounters); assertEquals(0, cares.length); } public void testDefaultedObs() { String tt1 = "TT1", tt2 = "TT2"; String patient1Id = "Patient1", patient2Id = "Patient2", patient3Id = "Patient3"; String patient1Pref = "Pref1", patient1Last = "Last1", patient1Community = "Comm1"; String patient2Pref = "Pref2", patient2Last = "Last2", patient2Community = "Comm2"; String patient3Pref = "Pref3", patient3Last = "Last3", patient3Community = "Comm3"; Calendar calendar = Calendar.getInstance(); calendar.set(1981, Calendar.JANUARY, 1); Date patient1Birth = calendar.getTime(); calendar.set(1982, Calendar.FEBRUARY, 2); Date patient2Birth = calendar.getTime(); calendar.set(1983, Calendar.MARCH, 3); Date patient3Birth = calendar.getTime(); Community comm1 = new Community(); comm1.setName(patient1Community); Community comm2 = new Community(); comm2.setName(patient2Community); Community comm3 = new Community(); comm3.setName(patient3Community); ExpectedObs obs1 = new ExpectedObs(); obs1.setName(tt1); ExpectedObs obs2 = new ExpectedObs(); obs2.setName(tt2); ExpectedObs obs3 = new ExpectedObs(); obs3.setName(tt2); org.openmrs.Patient patient1 = new org.openmrs.Patient(1); patient1.addIdentifier(new PatientIdentifier(patient1Id, motechIdType, new Location())); patient1.setBirthdate(patient1Birth); patient1.setGender("F"); patient1.addName(new PersonName(patient1Pref, null, patient1Last)); PersonAddress patient1Address = new PersonAddress(); patient1.addAddress(patient1Address); org.openmrs.Patient patient2 = new org.openmrs.Patient(2); patient2.addIdentifier(new PatientIdentifier(patient2Id, motechIdType, new Location())); patient2.setBirthdate(patient2Birth); patient2.setGender("M"); patient2.addName(new PersonName(patient2Pref, null, patient2Last)); PersonAddress patient2Address = new PersonAddress(); patient2.addAddress(patient2Address); org.openmrs.Patient patient3 = new org.openmrs.Patient(3); patient3.addIdentifier(new PatientIdentifier(patient3Id, motechIdType, new Location())); patient3.setBirthdate(patient3Birth); patient3.setGender("F"); patient3.addName(new PersonName(patient3Pref, null, patient3Last)); PersonAddress patient3Address = new PersonAddress(); patient3.addAddress(patient3Address); obs1.setPatient(patient1); obs2.setPatient(patient2); obs3.setPatient(patient3); List<ExpectedObs> defaultedObs = new ArrayList<ExpectedObs>(); defaultedObs.add(obs1); defaultedObs.add(obs2); defaultedObs.add(obs3); expect(motechService.getCommunityByPatient(patient1)).andReturn(comm1); expect(motechService.getCommunityByPatient(patient2)).andReturn(comm2); expect(motechService.getCommunityByPatient(patient3)).andReturn(comm3); replay(motechService, contextService); Care[] cares = careModelConverter .defaultedObsToWebServiceCares(defaultedObs); verify(motechService, contextService); assertEquals(2, cares.length); Care care1 = cares[0]; assertEquals(tt1, care1.getName()); assertEquals(1, care1.getPatients().length); Patient care1Patient = care1.getPatients()[0]; assertEquals(patient1Id, care1Patient.getMotechId()); assertEquals(patient1Pref, care1Patient.getPreferredName()); assertEquals(patient1Last, care1Patient.getLastName()); assertEquals(patient1Birth, care1Patient.getBirthDate()); assertEquals(Gender.FEMALE, care1Patient.getSex()); assertEquals(patient1Community, care1Patient.getCommunity()); Care care2 = cares[1]; assertEquals(tt2, care2.getName()); assertEquals(2, care2.getPatients().length); Patient care2Patient1 = care2.getPatients()[0]; assertEquals(patient2Id, care2Patient1.getMotechId()); assertEquals(patient2Pref, care2Patient1.getPreferredName()); assertEquals(patient2Last, care2Patient1.getLastName()); assertEquals(patient2Birth, care2Patient1.getBirthDate()); assertEquals(Gender.MALE, care2Patient1.getSex()); assertEquals(patient2Community, care2Patient1.getCommunity()); Patient care2Patient2 = care2.getPatients()[1]; assertEquals(patient3Id, care2Patient2.getMotechId()); assertEquals(patient3Pref, care2Patient2.getPreferredName()); assertEquals(patient3Last, care2Patient2.getLastName()); assertEquals(patient3Birth, care2Patient2.getBirthDate()); assertEquals(Gender.FEMALE, care2Patient2.getSex()); assertEquals(patient3Community, care2Patient2.getCommunity()); } public void testDefaultedObsEmpty() { List<ExpectedObs> defaultedObs = new ArrayList<ExpectedObs>(); Care[] cares = careModelConverter .defaultedObsToWebServiceCares(defaultedObs); assertEquals(0, cares.length); } public void testDefaulted() { String anc1 = "ANC1", anc2 = "ANC2"; String tt1 = "TT1", tt2 = "TT2"; String patient1Id = "Patient1", patient2Id = "Patient2", patient3Id = "Patient3"; String patient1Pref = "Pref1", patient1Last = "Last1", patient1Community = "Comm1"; String patient2Pref = "Pref2", patient2Last = "Last2", patient2Community = "Comm2"; String patient3Pref = "Pref3", patient3Last = "Last3", patient3Community = "Comm3"; Calendar calendar = Calendar.getInstance(); calendar.set(1981, Calendar.JANUARY, 1); Date patient1Birth = calendar.getTime(); calendar.set(1982, Calendar.FEBRUARY, 2); Date patient2Birth = calendar.getTime(); calendar.set(1983, Calendar.MARCH, 3); Date patient3Birth = calendar.getTime(); Community comm1 = new Community(); comm1.setName(patient1Community); Community comm2 = new Community(); comm2.setName(patient2Community); Community comm3 = new Community(); comm3.setName(patient3Community); org.openmrs.Patient patient1 = new org.openmrs.Patient(1); patient1.addIdentifier(new PatientIdentifier(patient1Id, motechIdType, new Location())); patient1.setBirthdate(patient1Birth); patient1.setGender("F"); patient1.addName(new PersonName(patient1Pref, null, patient1Last)); PersonAddress patient1Address = new PersonAddress(); patient1.addAddress(patient1Address); org.openmrs.Patient patient2 = new org.openmrs.Patient(2); patient2.addIdentifier(new PatientIdentifier(patient2Id, motechIdType, new Location())); patient2.setBirthdate(patient2Birth); patient2.setGender("M"); patient2.addName(new PersonName(patient2Pref, null, patient2Last)); PersonAddress patient2Address = new PersonAddress(); patient2.addAddress(patient2Address); org.openmrs.Patient patient3 = new org.openmrs.Patient(3); patient3.addIdentifier(new PatientIdentifier(patient3Id, motechIdType, new Location())); patient3.setBirthdate(patient3Birth); patient3.setGender("F"); patient3.addName(new PersonName(patient3Pref, null, patient3Last)); PersonAddress patient3Address = new PersonAddress(); patient3.addAddress(patient3Address); ExpectedEncounter encounter1 = new ExpectedEncounter(); encounter1.setName(anc1); encounter1.setPatient(patient1); ExpectedEncounter encounter2 = new ExpectedEncounter(); encounter2.setName(anc2); encounter2.setPatient(patient2); ExpectedEncounter encounter3 = new ExpectedEncounter(); encounter3.setName(anc2); encounter3.setPatient(patient3); List<ExpectedEncounter> defaultedEncounters = new ArrayList<ExpectedEncounter>(); defaultedEncounters.add(encounter1); defaultedEncounters.add(encounter2); defaultedEncounters.add(encounter3); ExpectedObs obs1 = new ExpectedObs(); obs1.setName(tt1); obs1.setPatient(patient1); ExpectedObs obs2 = new ExpectedObs(); obs2.setName(tt2); obs2.setPatient(patient2); ExpectedObs obs3 = new ExpectedObs(); obs3.setName(tt2); obs3.setPatient(patient3); List<ExpectedObs> defaultedObs = new ArrayList<ExpectedObs>(); defaultedObs.add(obs1); defaultedObs.add(obs2); defaultedObs.add(obs3); expect(motechService.getCommunityByPatient(patient1)).andReturn(comm1) .times(2); expect(motechService.getCommunityByPatient(patient2)).andReturn(comm2) .times(2); expect(motechService.getCommunityByPatient(patient3)).andReturn(comm3) .times(2); replay(motechService, contextService); Care[] cares = careModelConverter.defaultedToWebServiceCares( defaultedEncounters, defaultedObs); verify(motechService, contextService); assertEquals(4, cares.length); Care care1 = cares[0]; assertEquals(anc1, care1.getName()); assertEquals(1, care1.getPatients().length); Patient care1Patient = care1.getPatients()[0]; assertEquals(patient1Id, care1Patient.getMotechId()); assertEquals(patient1Pref, care1Patient.getPreferredName()); assertEquals(patient1Last, care1Patient.getLastName()); assertEquals(patient1Birth, care1Patient.getBirthDate()); assertEquals(Gender.FEMALE, care1Patient.getSex()); assertEquals(patient1Community, care1Patient.getCommunity()); Care care2 = cares[1]; assertEquals(anc2, care2.getName()); assertEquals(2, care2.getPatients().length); Patient care2Patient1 = care2.getPatients()[0]; assertEquals(patient2Id, care2Patient1.getMotechId()); assertEquals(patient2Pref, care2Patient1.getPreferredName()); assertEquals(patient2Last, care2Patient1.getLastName()); assertEquals(patient2Birth, care2Patient1.getBirthDate()); assertEquals(Gender.MALE, care2Patient1.getSex()); assertEquals(patient2Community, care2Patient1.getCommunity()); Patient care2Patient2 = care2.getPatients()[1]; assertEquals(patient3Id, care2Patient2.getMotechId()); assertEquals(patient3Pref, care2Patient2.getPreferredName()); assertEquals(patient3Last, care2Patient2.getLastName()); assertEquals(patient3Birth, care2Patient2.getBirthDate()); assertEquals(Gender.FEMALE, care2Patient2.getSex()); assertEquals(patient3Community, care2Patient2.getCommunity()); Care care3 = cares[2]; assertEquals(tt1, care3.getName()); assertEquals(1, care3.getPatients().length); Patient care3Patient = care3.getPatients()[0]; assertEquals(patient1Id, care3Patient.getMotechId()); assertEquals(patient1Pref, care3Patient.getPreferredName()); assertEquals(patient1Last, care3Patient.getLastName()); assertEquals(patient1Birth, care3Patient.getBirthDate()); assertEquals(Gender.FEMALE, care3Patient.getSex()); assertEquals(patient1Community, care3Patient.getCommunity()); Care care4 = cares[3]; assertEquals(tt2, care4.getName()); assertEquals(2, care4.getPatients().length); Patient care4Patient1 = care4.getPatients()[0]; assertEquals(patient2Id, care4Patient1.getMotechId()); assertEquals(patient2Pref, care4Patient1.getPreferredName()); assertEquals(patient2Last, care4Patient1.getLastName()); assertEquals(patient2Birth, care4Patient1.getBirthDate()); assertEquals(Gender.MALE, care4Patient1.getSex()); assertEquals(patient2Community, care4Patient1.getCommunity()); Patient care4Patient2 = care4.getPatients()[1]; assertEquals(patient3Id, care4Patient2.getMotechId()); assertEquals(patient3Pref, care4Patient2.getPreferredName()); assertEquals(patient3Last, care4Patient2.getLastName()); assertEquals(patient3Birth, care4Patient2.getBirthDate()); assertEquals(Gender.FEMALE, care4Patient2.getSex()); assertEquals(patient3Community, care4Patient2.getCommunity()); } public void testUpcomingEncounters() { String anc1 = "ANC1", pnc2 = "PNC2", pnc3 = "PNC3"; Calendar calendar = Calendar.getInstance(); calendar.set(2010, Calendar.JANUARY, 1); Date encounter1Date = calendar.getTime(); calendar.set(2010, Calendar.FEBRUARY, 2); Date encounter2Date = calendar.getTime(); calendar.set(2010, Calendar.MARCH, 3); Date encounter3Date = calendar.getTime(); ExpectedEncounter encounter1 = new ExpectedEncounter(); encounter1.setName(anc1); encounter1.setDueEncounterDatetime(encounter1Date); ExpectedEncounter encounter2 = new ExpectedEncounter(); encounter2.setName(pnc2); encounter2.setDueEncounterDatetime(encounter2Date); ExpectedEncounter encounter3 = new ExpectedEncounter(); encounter3.setName(pnc3); encounter3.setDueEncounterDatetime(encounter3Date); List<ExpectedEncounter> upcomingEncounters = new ArrayList<ExpectedEncounter>(); upcomingEncounters.add(encounter1); upcomingEncounters.add(encounter2); upcomingEncounters.add(encounter3); Care[] cares = careModelConverter .upcomingEncountersToWebServiceCares(upcomingEncounters); assertEquals(3, cares.length); Care care1 = cares[0]; assertEquals(anc1, care1.getName()); assertEquals(encounter1Date, care1.getDate()); Care care2 = cares[1]; assertEquals(pnc2, care2.getName()); assertEquals(encounter2Date, care2.getDate()); Care care3 = cares[2]; assertEquals(pnc3, care3.getName()); assertEquals(encounter3Date, care3.getDate()); } public void testUpcomingEncountersEmpty() { List<ExpectedEncounter> upcomingEncounters = new ArrayList<ExpectedEncounter>(); Care[] cares = careModelConverter .upcomingEncountersToWebServiceCares(upcomingEncounters); assertEquals(0, cares.length); } public void testUpcomingObs() { String tt1 = "TT1", opv2 = "OPV2", penta3 = "Penta3"; Calendar calendar = Calendar.getInstance(); calendar.set(2010, Calendar.JANUARY, 1); Date obs1Date = calendar.getTime(); calendar.set(2010, Calendar.FEBRUARY, 2); Date obs2Date = calendar.getTime(); calendar.set(2010, Calendar.MARCH, 3); Date obs3Date = calendar.getTime(); ExpectedObs obs1 = new ExpectedObs(); obs1.setName(tt1); obs1.setDueObsDatetime(obs1Date); ExpectedObs obs2 = new ExpectedObs(); obs2.setName(opv2); obs2.setDueObsDatetime(obs2Date); ExpectedObs obs3 = new ExpectedObs(); obs3.setName(penta3); obs3.setDueObsDatetime(obs3Date); List<ExpectedObs> upcomingObs = new ArrayList<ExpectedObs>(); upcomingObs.add(obs1); upcomingObs.add(obs2); upcomingObs.add(obs3); Care[] cares = careModelConverter.upcomingObsToWebServiceCares(upcomingObs); assertEquals(3, cares.length); Care care1 = cares[0]; assertEquals(tt1, care1.getName()); assertEquals(obs1Date, care1.getDate()); Care care2 = cares[1]; assertEquals(opv2, care2.getName()); assertEquals(obs2Date, care2.getDate()); Care care3 = cares[2]; assertEquals(penta3, care3.getName()); assertEquals(obs3Date, care3.getDate()); } public void testUpcomingObsEmpty() { List<ExpectedObs> upcomingObs = new ArrayList<ExpectedObs>(); Care[] cares = careModelConverter.upcomingObsToWebServiceCares(upcomingObs); assertEquals(0, cares.length); } public void testUpcoming() { String anc1 = "ANC1", pnc2 = "PNC2", pnc3 = "PNC3"; String tt1 = "TT1", opv2 = "OPV2", penta3 = "Penta3"; Calendar calendar = Calendar.getInstance(); calendar.set(2010, Calendar.JANUARY, 1); Date encounter1Date = calendar.getTime(); calendar.set(2010, Calendar.FEBRUARY, 2); Date encounter2Date = calendar.getTime(); calendar.set(2010, Calendar.MARCH, 3); Date encounter3Date = calendar.getTime(); calendar.set(2010, Calendar.JANUARY, 2); Date obs1Date = calendar.getTime(); calendar.set(2010, Calendar.FEBRUARY, 3); Date obs2Date = calendar.getTime(); calendar.set(2010, Calendar.MARCH, 4); Date obs3Date = calendar.getTime(); ExpectedEncounter encounter1 = new ExpectedEncounter(); encounter1.setName(anc1); encounter1.setDueEncounterDatetime(encounter1Date); ExpectedEncounter encounter2 = new ExpectedEncounter(); encounter2.setName(pnc2); encounter2.setDueEncounterDatetime(encounter2Date); ExpectedEncounter encounter3 = new ExpectedEncounter(); encounter3.setName(pnc3); encounter3.setDueEncounterDatetime(encounter3Date); List<ExpectedEncounter> upcomingEncounters = new ArrayList<ExpectedEncounter>(); upcomingEncounters.add(encounter1); upcomingEncounters.add(encounter2); upcomingEncounters.add(encounter3); ExpectedObs obs1 = new ExpectedObs(); obs1.setName(tt1); obs1.setDueObsDatetime(obs1Date); ExpectedObs obs2 = new ExpectedObs(); obs2.setName(opv2); obs2.setDueObsDatetime(obs2Date); ExpectedObs obs3 = new ExpectedObs(); obs3.setName(penta3); obs3.setDueObsDatetime(obs3Date); List<ExpectedObs> upcomingObs = new ArrayList<ExpectedObs>(); upcomingObs.add(obs1); upcomingObs.add(obs2); upcomingObs.add(obs3); Care[] cares = careModelConverter.upcomingToWebServiceCares( upcomingEncounters, upcomingObs, false); assertEquals(6, cares.length); Care care1 = cares[0]; assertEquals(anc1, care1.getName()); assertEquals(encounter1Date, care1.getDate()); Care care2 = cares[1]; assertEquals(tt1, care2.getName()); assertEquals(obs1Date, care2.getDate()); Care care3 = cares[2]; assertEquals(pnc2, care3.getName()); assertEquals(encounter2Date, care3.getDate()); Care care4 = cares[3]; assertEquals(opv2, care4.getName()); assertEquals(obs2Date, care4.getDate()); Care care5 = cares[4]; assertEquals(pnc3, care5.getName()); assertEquals(encounter3Date, care5.getDate()); Care care6 = cares[5]; assertEquals(penta3, care6.getName()); assertEquals(obs3Date, care6.getDate()); } }
package com.utils.tools.upload.service; import com.utils.tools.upload.pojo.SysFileVo; import org.springframework.web.multipart.MultipartFile; public interface SysFileService { String[] IMG_TYPES = {".png", ".jpg", ".jpeg", ".gif", ".bmp"}; SysFileVo fileUpload(MultipartFile file); }
package com.vilio.mps.common.pojo; /** * 类名: App<br> * 功能:应用实体<br> * 版本: 1.0<br> * 日期: 2017年8月10日<br> * 作者: wangxf<br> * 版权:vilio<br> * 说明:<br> */ public class App { private Integer id; private String appCode; private String appName; private String appType; private String appKey; private String appMessageSecret; private String appMasterSecret; private String desc; private String createTime; private String updateTime; private String remark1; private String remark2; private String status; private String systemType; public String getSystemType() { return systemType; } public void setSystemType(String systemType) { this.systemType = systemType; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getAppCode() { return appCode; } public void setAppCode(String appCode) { this.appCode = appCode; } public String getAppName() { return appName; } public void setAppName(String appName) { this.appName = appName; } public String getAppType() { return appType; } public void setAppType(String appType) { this.appType = appType; } public String getAppKey() { return appKey; } public void setAppKey(String appKey) { this.appKey = appKey; } public String getAppMessageSecret() { return appMessageSecret; } public void setAppMessageSecret(String appMessageSecret) { this.appMessageSecret = appMessageSecret; } public String getAppMasterSecret() { return appMasterSecret; } public void setAppMasterSecret(String appMasterSecret) { this.appMasterSecret = appMasterSecret; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public String getCreateTime() { return createTime; } public void setCreateTime(String createTime) { this.createTime = createTime; } public String getUpdateTime() { return updateTime; } public void setUpdateTime(String updateTime) { this.updateTime = updateTime; } public String getRemark1() { return remark1; } public void setRemark1(String remark1) { this.remark1 = remark1; } public String getRemark2() { return remark2; } public void setRemark2(String remark2) { this.remark2 = remark2; } public App() { } public App(Integer id, String appCode, String appName, String appType, String appKey, String appMessageSecret, String appMasterSecret, String desc, String createTime, String updateTime, String remark1, String remark2, String status, String systemType) { this.id = id; this.appCode = appCode; this.appName = appName; this.appType = appType; this.appKey = appKey; this.appMessageSecret = appMessageSecret; this.appMasterSecret = appMasterSecret; this.desc = desc; this.createTime = createTime; this.updateTime = updateTime; this.remark1 = remark1; this.remark2 = remark2; this.status = status; this.systemType = systemType; } }
package 二叉树的最大路径和; class TreeNode{ int val; TreeNode left; TreeNode right; TreeNode(int val){ this.val = val; } } public class MaxPath { int max = Integer.MIN_VALUE; public int maxPathSum(TreeNode root) { helper(root); return max; } private int helper(TreeNode root){ if(root == null) return 0; int left = Math.max(helper(root.left),0); int right = Math.max(helper(root.right),0); max = Math.max(left+right+root.val,max); return Math.max(left,right)+root.val; } }
package com.sinata.rwxchina.basiclib.entity; import java.util.List; /** * @author HRR * @datetime 2017/11/29 * @describe 商铺基本信息实体类 * @modifyRecord */ public class BaseShopInfo { /** * shopid : 1827 * shop_name : 瑜捷鸿汽车服务有限公司 * shop_type : 1 * shop_zh_type : 汽车服务 * shop_logo : /Uploads/storelogo/88895383259bf3566caa47.jpeg_640_640.jpg * shop_show : ["/Uploads/storepictures/108963756159bf3566d2427._640_640.jpg","/Uploads/storepictures/213809083559bf35671b0e7._640_640.jpg","/Uploads/storepictures/183873730159bf356748c28._640_640.jpg"] * shop_telephone : 18108102011 * shop_address : 成都市金牛区恒德路1号 * shop_lng : 104.08510898128 * shop_lat : 30.67784059335 * distance : 11152.30 * shop_goodsmoney_min : 25.00 * shop_starlevel : 5 * shop_synopsis : 本店主营业务有洗车贴膜,抛光打蜡,镀金封釉,车饰保养,钣金喷漆,维修保险。 * shop_service : * shop_point : * shop_sale : 0 * shop_is_xiche : 1 * shop_is_baoy : 1 * shop_is_meir : 1 * shop_is_weix : 1 * shop_is_discount : 1 * shop_discount : 9.0 * shop_discount_explain : * shop_juan : * shop_tuan : * shop_ding : * shop_type_labels_zh : 保养,洗车,维修,美容 * shop_people_avgmoney : 25.00 * is_shop : 1 * is_webshop : 0 */ private String shopid; private String shop_name; private String shop_type; private String shop_zh_type; private String shop_logo; private String shop_telephone; private String shop_address; private String shop_lng; private String shop_lat; private String distance; private String shop_goodsmoney_min; private String shop_starlevel; private String shop_synopsis; private String shop_service; private String shop_point; private String shop_sale; private String shop_is_xiche; private String shop_is_baoy; private String shop_is_meir; private String shop_is_weix; private String shop_is_discount; private String shop_discount; private String shop_discount_explain; private String shop_juan; private String shop_tuan; private String shop_ding; private String shop_type_labels_zh; private String shop_people_avgmoney; private String is_shop; private String is_webshop; private List<String> shop_show; private String m_shop_type_labels; public String getM_shop_type_labels() { return m_shop_type_labels; } public void setM_shop_type_labels(String m_shop_type_labels) { this.m_shop_type_labels = m_shop_type_labels; } public String getShopid() { return shopid; } public void setShopid(String shopid) { this.shopid = shopid; } public String getShop_name() { return shop_name; } public void setShop_name(String shop_name) { this.shop_name = shop_name; } public String getShop_type() { return shop_type; } public void setShop_type(String shop_type) { this.shop_type = shop_type; } public String getShop_zh_type() { return shop_zh_type; } public void setShop_zh_type(String shop_zh_type) { this.shop_zh_type = shop_zh_type; } public String getShop_logo() { return shop_logo; } public void setShop_logo(String shop_logo) { this.shop_logo = shop_logo; } public String getShop_telephone() { return shop_telephone; } public void setShop_telephone(String shop_telephone) { this.shop_telephone = shop_telephone; } public String getShop_address() { return shop_address; } public void setShop_address(String shop_address) { this.shop_address = shop_address; } public String getShop_lng() { return shop_lng; } public void setShop_lng(String shop_lng) { this.shop_lng = shop_lng; } public String getShop_lat() { return shop_lat; } public void setShop_lat(String shop_lat) { this.shop_lat = shop_lat; } public String getDistance() { return distance; } public void setDistance(String distance) { this.distance = distance; } public String getShop_goodsmoney_min() { return shop_goodsmoney_min; } public void setShop_goodsmoney_min(String shop_goodsmoney_min) { this.shop_goodsmoney_min = shop_goodsmoney_min; } public String getShop_starlevel() { return shop_starlevel; } public void setShop_starlevel(String shop_starlevel) { this.shop_starlevel = shop_starlevel; } public String getShop_synopsis() { return shop_synopsis; } public void setShop_synopsis(String shop_synopsis) { this.shop_synopsis = shop_synopsis; } public String getShop_service() { return shop_service; } public void setShop_service(String shop_service) { this.shop_service = shop_service; } public String getShop_point() { return shop_point; } public void setShop_point(String shop_point) { this.shop_point = shop_point; } public String getShop_sale() { return shop_sale; } public void setShop_sale(String shop_sale) { this.shop_sale = shop_sale; } public String getShop_is_xiche() { return shop_is_xiche; } public void setShop_is_xiche(String shop_is_xiche) { this.shop_is_xiche = shop_is_xiche; } public String getShop_is_baoy() { return shop_is_baoy; } public void setShop_is_baoy(String shop_is_baoy) { this.shop_is_baoy = shop_is_baoy; } public String getShop_is_meir() { return shop_is_meir; } public void setShop_is_meir(String shop_is_meir) { this.shop_is_meir = shop_is_meir; } public String getShop_is_weix() { return shop_is_weix; } public void setShop_is_weix(String shop_is_weix) { this.shop_is_weix = shop_is_weix; } public String getShop_is_discount() { return shop_is_discount; } public void setShop_is_discount(String shop_is_discount) { this.shop_is_discount = shop_is_discount; } public String getShop_discount() { return shop_discount; } public void setShop_discount(String shop_discount) { this.shop_discount = shop_discount; } public String getShop_discount_explain() { return shop_discount_explain; } public void setShop_discount_explain(String shop_discount_explain) { this.shop_discount_explain = shop_discount_explain; } public String getShop_juan() { return shop_juan; } public void setShop_juan(String shop_juan) { this.shop_juan = shop_juan; } public String getShop_tuan() { return shop_tuan; } public void setShop_tuan(String shop_tuan) { this.shop_tuan = shop_tuan; } public String getShop_ding() { return shop_ding; } public void setShop_ding(String shop_ding) { this.shop_ding = shop_ding; } public String getShop_type_labels_zh() { return shop_type_labels_zh; } public void setShop_type_labels_zh(String shop_type_labels_zh) { this.shop_type_labels_zh = shop_type_labels_zh; } public String getShop_people_avgmoney() { return shop_people_avgmoney; } public void setShop_people_avgmoney(String shop_people_avgmoney) { this.shop_people_avgmoney = shop_people_avgmoney; } public String getIs_shop() { return is_shop; } public void setIs_shop(String is_shop) { this.is_shop = is_shop; } public String getIs_webshop() { return is_webshop; } public void setIs_webshop(String is_webshop) { this.is_webshop = is_webshop; } public List<String> getShop_show() { return shop_show; } public void setShop_show(List<String> shop_show) { this.shop_show = shop_show; } @Override public String toString() { return "BaseShopInfo{" + "shopid='" + shopid + '\'' + ", shop_name='" + shop_name + '\'' + ", shop_type='" + shop_type + '\'' + ", shop_zh_type='" + shop_zh_type + '\'' + ", shop_logo='" + shop_logo + '\'' + ", shop_telephone='" + shop_telephone + '\'' + ", shop_address='" + shop_address + '\'' + ", shop_lng='" + shop_lng + '\'' + ", shop_lat='" + shop_lat + '\'' + ", distance='" + distance + '\'' + ", shop_goodsmoney_min='" + shop_goodsmoney_min + '\'' + ", shop_starlevel='" + shop_starlevel + '\'' + ", shop_synopsis='" + shop_synopsis + '\'' + ", shop_service='" + shop_service + '\'' + ", shop_point='" + shop_point + '\'' + ", shop_sale='" + shop_sale + '\'' + ", shop_is_xiche='" + shop_is_xiche + '\'' + ", shop_is_baoy='" + shop_is_baoy + '\'' + ", shop_is_meir='" + shop_is_meir + '\'' + ", shop_is_weix='" + shop_is_weix + '\'' + ", shop_is_discount='" + shop_is_discount + '\'' + ", shop_discount='" + shop_discount + '\'' + ", shop_discount_explain='" + shop_discount_explain + '\'' + ", shop_juan='" + shop_juan + '\'' + ", shop_tuan='" + shop_tuan + '\'' + ", shop_ding='" + shop_ding + '\'' + ", shop_type_labels_zh='" + shop_type_labels_zh + '\'' + ", shop_people_avgmoney='" + shop_people_avgmoney + '\'' + ", is_shop='" + is_shop + '\'' + ", is_webshop='" + is_webshop + '\'' + ", shop_show=" + shop_show + ", m_shop_type_labels='" + m_shop_type_labels + '\'' + '}'; } }
package com.book.proxy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; /** * @author weigs * @date 2017/10/5 0005 */ public class DynamicProxy implements InvocationHandler { Person student; public DynamicProxy(Person person) { this.student = person; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("先执行人的动作"); method.invoke(student, args); System.out.println("执行完人的动作"); return null; } }
/* * Copyright 1999-2011 Alibaba Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.pajk.pt.examples.dubbo.demo.provider; import com.alibaba.dubbo.common.serialize.Serialization; import com.alibaba.dubbo.common.utils.PojoUtils; import com.alibaba.dubbo.remoting.transport.CodecSupport; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.SerializerFeature; import com.pajk.pt.examples.dubbo.demo.ComplexBean; import com.pajk.suez.server.codec.ComplexDecoder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; public class TestJson { private final static Logger logger = LoggerFactory.getLogger(TestJson.class); public static final SerializerFeature[] SERIALIZER_FEATURES = new SerializerFeature[]{ SerializerFeature.DisableCircularReferenceDetect,//disable循环引用 SerializerFeature.WriteMapNullValue,//null属性,序列化为null,do by guankaiqiang,android sdk中 JSON.optString()将null convert成了"null",故关闭该特性 // SerializerFeature.NotWriteRootClassName, //与pocrd保持一致 SerializerFeature.WriteEnumUsingToString, //与pocrd保持一致 SerializerFeature.WriteNullNumberAsZero,//与pocrd保持一致 SerializerFeature.WriteNullBooleanAsFalse,//与pocrd保持一致 // SerializerFeature.PrettyFormat, SerializerFeature.WriteClassName, // SerializerFeature.UseISO8601DateFormat, // SerializerFeature.WriteDateUseDateFormat, }; static { JSON.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; JSON.DEFAULT_TYPE_KEY = "class"; } public static void testClassName(){ String[] array = new String[2]; List<ComplexBean.Entity> entityList = new ArrayList<ComplexBean.Entity>(); logger.info("{}", void.class.getName()); logger.info("{}", array.getClass().getName()); logger.info("{}", int[].class.getName()); logger.info("{}", Integer[].class.getName()); logger.info("{}", Integer.class.getName()); logger.info("{}", ComplexBean.Entity[].class.getName()); logger.info("{}", ComplexBean.Entity[].class.getComponentType().getName()); logger.info("{}", entityList.getClass().getName()); logger.info("{}", entityList.getClass().getSuperclass().getName()); logger.info("{}", entityList.getClass().getGenericInterfaces()); logger.info("{}", entityList.getClass().getGenericSuperclass()); logger.info("{}", entityList.getClass().getTypeParameters()[0].getBounds()); logger.info("{}", entityList.getClass().getTypeParameters()[0].getGenericDeclaration().getName()); // logger.info("{}", ArrayList<ComplexBean.Entity>.class.getComponentType()); } public static void testSerilize(){ Serialization serialization = CodecSupport.getSerializationById((byte) 1); // ChannelBufferOutputStream bos = new ChannelBufferOutputStream(buffer); // ObjectOutput out = serialization.serialize(channel.getUrl(), bos); // if (req.isEvent()) { // encodeEventData(channel, out, req.getData()); // } else { // encodeRequestData(channel, out, req.getData()); // } } public static void main(String[] args) { logger.info("start..........................................."); List<ComplexBean.Entity> entitys = new ArrayList<>(); ComplexBean.Entity entity1 = new ComplexBean.Entity(); ComplexBean.Entity1 entity11 = new ComplexBean.Entity1(); ComplexBean.Entity2 entity21 = new ComplexBean.Entity2(); entity11.str = "entity11"; entity21.entityList = new ArrayList<>(); entity21.entityList.add(entity11); entity1.str = "entity1"; entity1.anEnum = ComplexBean.Enum.B; entity1.entity1 = entity11; entity1.entity2 = entity21; entity1.enumList = new ArrayList<>(); entity1.enumList.add(ComplexBean.Enum.A); entity1.date = new Date(); entity1.i1 = 1; entity1.l1 = 2l; entity1.f1 = 1.1f; entity1.d1 = 2.2; entity1.o1 = entity11; entitys.add(entity1); { logger.info("{}", JSON.toJSONString(entitys, SERIALIZER_FEATURES)); Object pojo = PojoUtils.generalize(entitys); logger.info("{}", JSON.toJSONString(pojo, SerializerFeature.DisableCircularReferenceDetect)); List<ComplexBean.Entity> decodeEntitys = new ArrayList<>(); decodeEntitys = JSON.parseObject(JSON.toJSONString(entitys, SERIALIZER_FEATURES), decodeEntitys.getClass()); Object obj1 = JSON.parse(JSON.toJSONString(entitys, SERIALIZER_FEATURES)); logger.info("{}", JSON.toJSONString(decodeEntitys, SERIALIZER_FEATURES)); } { Object object = PojoUtils.realize(JSON.parse("[{\"anEnum\":\"B\",\"d1\":2.2,\"date\":1442053074620,\"entity1\":{\"str\":\"entity11\"},\"entity2\":{\"entityList\":[{\"str\":\"entity11\"}]},\"enumList\":[\"A\"],\"f1\":1.1,\"i1\":1,\"l1\":2,\"o1\":{\"str\":\"entity11\"},\"str\":\"entity1\"}]"), java.util.List.class, ComplexBean.Entity.class); logger.info("{}", object); } { com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject("{\"anEnum\":\"B\",\"d1\":2.2,\"date\":1442053074620,\"entity1\":{\"str\":\"entity11\"},\"entity2\":{\"entityList\":[{\"str\":\"entity11\"}]},\"enumList\":[\"A\"],\"f1\":1.1,\"i1\":1,\"l1\":2,\"o1\":{\"str\":\"entity11\"},\"str\":\"entity1\"}"); Map<String, Object> map = new HashMap(); for(Map.Entry<String, Object> entry:jsonObject.entrySet()){ map.put(entry.getKey(), entry.getValue()); } Object object = PojoUtils.realize(map, ComplexBean.Entity.class); logger.info("{}", object); } { com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(entity1)); ComplexDecoder complexDecoder = new ComplexDecoder(JSON.toJSONString(entity1, SERIALIZER_FEATURES)); JSON.DEFAULT_TYPE_KEY="@type"; complexDecoder.decode(); Map map = (Map) complexDecoder.getNativeObj4Json(); JSON.DEFAULT_TYPE_KEY="class"; Object object = PojoUtils.realize(map, ComplexBean.Entity.class); logger.info("{}", object); } { Object object = PojoUtils.realize(PojoUtils.generalize(entitys), java.util.List.class); logger.info("{}", object); } { Object object = PojoUtils.realize(PojoUtils.generalize(entitys), Object[].class); logger.info("{}", object); } } }
package com.penzias.dao; import com.penzias.core.interfaces.BasicMapper; import com.penzias.entity.HomocysteineExamInfo; import com.penzias.entity.HomocysteineExamInfoExample; public interface HomocysteineExamInfoMapper extends BasicMapper<HomocysteineExamInfoExample, HomocysteineExamInfo>{ }
package pl.calko.productlistapp.storeapp; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.ListView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import java.util.ArrayList; import java.util.List; import pl.calko.productlistapp.R; public class ProductListActivity extends AppCompatActivity { private final static String TABLE_NAME = "storeProducts"; private DatabaseReference storeProducts; private String userFirebaseId; private ArrayList<Product> products = new ArrayList<>(); private StoreProductsAdapter adapter; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_product_list); initFirebase(); initUi(); fetchProductsFromFirebase(); } private void initUi() { findViewById(R.id.add_new_product).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { openProductEditActivity(null); } }); findViewById(R.id.logout).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { FirebaseAuth.getInstance().signOut(); finish(); } }); adapter = new StoreProductsAdapter(products, new AdapterListener() { @Override public void editProduct(Product product) { openProductEditActivity(product.getId()); } @Override public void remove(Product product) { storeProducts.child(userFirebaseId).child(product.getId()).removeValue(); products.remove(product); adapter.notifyDataSetChanged(); } }); ListView listView = findViewById(R.id.listView); listView.setAdapter(adapter); } private void openProductEditActivity(String productId) { Intent intent = new Intent(this, ProductEditActivity.class); intent.putExtra("arg_product_id", productId); startActivity(intent); } private void initFirebase() { userFirebaseId = FirebaseAuth.getInstance().getCurrentUser().getUid(); FirebaseDatabase database = FirebaseDatabase.getInstance(); storeProducts = database.getReference(TABLE_NAME); } private void fetchProductsFromFirebase() { storeProducts.child(userFirebaseId).addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { loadProductsToListView(cerateProductsFromFirebaseResult(dataSnapshot)); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } private List<Product> cerateProductsFromFirebaseResult(DataSnapshot dataSnapshot) { List<Product> products = new ArrayList<>(); for (DataSnapshot data : dataSnapshot.getChildren()) { Product product = data.getValue(Product.class); products.add(product); } return products; } private void loadProductsToListView(List<Product> products) { this.products.clear(); this.products.addAll(products); adapter.notifyDataSetChanged(); } }
package com.xjf.wemall.api.util; import org.apache.commons.lang3.StringUtils; import sun.misc.BASE64Decoder; /** * Base64加密/解密 * * @version 1.0.0 */ @SuppressWarnings("restriction") public class Base64Operate { /** * base64加密 * * @param String * str * @return String */ @SuppressWarnings("deprecation") public static String toBASE64(String str) { if (StringUtils.isEmpty(str)) return null; return (new sun.misc.BASE64Encoder()).encode(java.net.URLEncoder .encode(str).getBytes()); } /** * base64解密 * * @param String * str * @return String */ @SuppressWarnings("deprecation") public static String fromBASE64(String str) { if (StringUtils.isEmpty(str)) return null; BASE64Decoder decoder = new BASE64Decoder(); try { byte[] b = decoder.decodeBuffer(str); return java.net.URLDecoder.decode(new String(b)); } catch (Exception e) { return null; } } /** * 测试函数 * * @param args */ public static void main(String[] args) { String s = "{\"cityName\":\"南京\",\"sourceType\":\"1\",\"userId\":\"10002500\"}"; String str = toBASE64(s); System.out.println("stringtoBASE64 -> " + str); // System.out.println("stringfromBASE64 -> " + getFromBASE64(str)); } }
package com.fengniao.lightmusic.playmusic; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.ServiceConnection; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.IBinder; import android.os.RemoteException; import android.util.Log; import com.fengniao.lightmusic.MusicManager; import com.fengniao.lightmusic.model.Music; import com.fengniao.lightmusic.service.PlayService; import com.fengniao.lightmusic.utils.MusicUtils; import java.util.List; import static android.content.Context.BIND_AUTO_CREATE; public class PlayMusicPresenter implements PlayMusic.Presenter { private MusicManager mMusicManager; private final PlayMusic.View mView; private List<Music> mList; private int currentPosition; private PlayComletedReceiver receiver; private ServiceConnection connection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { mMusicManager = MusicManager.Stub.asInterface(service); try { mMusicManager.setMusic(mList.get(currentPosition)); mView.selectMusic(currentPosition); } catch (RemoteException e) { e.printStackTrace(); } updateSchedule(); } @Override public void onServiceDisconnected(ComponentName name) { } }; public PlayMusicPresenter(PlayMusic.View mView) { this.mView = mView; mView.setPresenter(this); start(); } @Override public void start() { mList = getMusicList(); Intent intent = new Intent(getActivity(), PlayService.class); getActivity().startService(intent); getActivity().bindService(intent, connection, BIND_AUTO_CREATE); receiver = new PlayComletedReceiver(); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction("com.fengniao.broadcast.PLAY_COMPLETE"); getActivity().registerReceiver(receiver, intentFilter); } @Override public void setMusic(Music music) { try { mMusicManager.setMusic(music); mMusicManager.stop(); mMusicManager.play(); } catch (RemoteException e) { e.printStackTrace(); } } @Override public void playOrPause() { try { if (mMusicManager.isPlaying()) { mView.setPlayStatus("播放"); mMusicManager.pause(); } else { mView.setPlayStatus("暂停"); mMusicManager.play(); } } catch (RemoteException e) { e.printStackTrace(); } } @Override public void next() { if (currentPosition + 1 == mList.size()) { mView.showMusicEndToast(); return; } currentPosition++; mView.selectMusic(currentPosition); setMusic(mList.get(currentPosition)); } @Override public void stop() { try { mMusicManager.stop(); mView.setPlayStatus("播放"); } catch (RemoteException e) { e.printStackTrace(); } } @Override public List<Music> getMusicList() { return MusicUtils.getMusicData(getActivity()); } private android.os.Handler mHandler = new android.os.Handler(); private Runnable runnable = new Runnable() { @Override public void run() { mHandler.postDelayed(runnable, 500); try { if (mMusicManager.getDuration() >= 0) { int progress = (int) ((float) mMusicManager.getCurrentTime() / (float) mList.get(currentPosition).getDuration() * 100); if (mMusicManager.isPlaying()) { mView.setPlayStatus("暂停"); mView.showMusicProgress(progress); } else { mView.setPlayStatus("播放"); if (progress >= 99) { mView.showMusicProgress(0); } } } else { mView.showMusicProgress(0); } } catch (RemoteException e) { e.printStackTrace(); } } }; @Override public void updateSchedule() { mHandler.postDelayed(runnable, 500); } @Override public void setMusicPic(int position) { String album = getAlbumArt((int) mList.get(position).getAlbumId()); Bitmap bm = BitmapFactory.decodeFile(album); mView.showMusicPic(bm); mView.showHeaderPic(bm); } @Override public void itemClick(int position) { mView.setPlayStatus("暂停"); if (currentPosition == position) { try { mMusicManager.play(); } catch (RemoteException e) { e.printStackTrace(); } return; } currentPosition = position; mView.selectMusic(currentPosition); setMusic(mList.get(currentPosition)); } @Override public void onDestroy() { getActivity().unbindService(connection); mHandler.removeCallbacks(runnable); mHandler = null; getActivity().unregisterReceiver(receiver); } @Override public Activity getActivity() { return mView.getActivity(); } /** * 功能 通过album_id查找 album_art 如果找不到返回null * * @param album_id * @return album_art */ private String getAlbumArt(int album_id) { String mUriAlbums = "content://media/external/audio/albums"; String[] projection = new String[]{"album_art"}; Cursor cur = getActivity().getContentResolver().query( Uri.parse(mUriAlbums + "/" + Integer.toString(album_id)), projection, null, null, null); String album_art = null; assert cur != null; if (cur.getCount() > 0 && cur.getColumnCount() > 0) { cur.moveToNext(); album_art = cur.getString(0); } cur.close(); return album_art; } public class PlayComletedReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Log.i("tag", "test"); // next(); } } }
package kh.cocoa.dao; import java.util.List; import org.apache.ibatis.annotations.Mapper; import kh.cocoa.dto.DepartmentsDTO; @Mapper public interface DepartmentsDAO { public String getDeptName(); public DepartmentsDTO getDeptNameByCode(int code); public List<DepartmentsDTO> getDeptList(); public DepartmentsDTO getDept(); public DepartmentsDTO getSearchTopDept(String name); public List<DepartmentsDTO> getSearchDeptCode(String name); /* ====소형=== 관리자 - 사용자관리*/ public List<DepartmentsDTO> getDeptListOrderByCode(); public List<DepartmentsDTO> getDeptListWithout0(); public List<DepartmentsDTO> getDeptListForFilter(); public int addDept(List<DepartmentsDTO> dto); public int updateDept(List<DepartmentsDTO> dto); public int deleteDept(List<DepartmentsDTO> dto); }
package com.neo.bharat.spring.entity; import lombok.Data; import javax.persistence.*; @Entity @Table(name = "project") @Data public class Project { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long projectId; @Column(name = "projectName") private String projectName; @Column(name = "projectDuration") private int projectDuration; @ManyToOne private Student student; }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package discountstrategylab2; /** * * @author Spark */ public class Product { private DiscountStrategy discountStrategy; private String productID; private String description; private double unitCost; //constructor public Product (DiscountStrategy discountStrategy, String productID, String description, double unitCost){ this.discountStrategy = discountStrategy; this.productID = productID; this.description = description; this.unitCost = unitCost; } /** * @return the discountStrategy */ public DiscountStrategy getDiscountStrategy() { return discountStrategy; } /** * @param discountStrategy the discountStrategy to set */ public void setDiscountStrategy(DiscountStrategy discountStrategy) { this.discountStrategy = discountStrategy; } public double getDiscountAmount(int qty){ return (discountStrategy.getDiscount(qty, unitCost)); } /** * @return the productID */ public String getProductID() { return productID; } /** * @param productID the productID to set */ public void setProductID(String productID) { this.productID = productID; } /** * @return the description */ public String getDescription() { return description; } /** * @param description the description to set */ public void setDescription(String description) { this.description = description; } /** * @return the unitCost */ public double getUnitCost() { return unitCost; } /** * @param unitCost the unitCost to set */ public void setUnitCost(double unitCost) { this.unitCost = unitCost; } }
package org.sero.cash.superzk.crypto.ecc; import java.math.BigInteger; import org.junit.Test; import org.sero.cash.superzk.util.Arrays; import org.sero.cash.superzk.util.HexUtils; public class TestEddsa { @Test public void test() { Group base0 = new Group("5dfbb35a38ffdcab".getBytes(), 1, 256, 8); Group base1 = new Group("7f9f2ebf9cb5e28a".getBytes(), 1, 256, 8); Field.FR sk = Field.newFR("20205729828150001148051822792008367049313441672068972729859762844264164030"); byte[] msg = HexUtils.toBytes("0x9e282094f9be08ee6d0340902b8ab8fe57ad82f63700e7d762c1742ec5cca97f"); byte[] s_ret = Eddsa.sign(msg, sk, base0, base1); System.out.println(HexUtils.toHex(s_ret)); } @Test public void testEddsa_n() { Group base0 = new Group("5dfbb35a38ffdcab".getBytes(), 1, 256, 8); Group base1 = new Group("7f9f2ebf9cb5e28a".getBytes(), 1, 256, 8); for (int i = 0; i < 100; i++) { Field.FR sk = Field.newFR(new BigInteger(Arrays.randomBytes(32))); byte[] msg = Arrays.randomBytes(32); Point pk0 = base0.mult(sk); Point pk1 = base1.mult(sk); byte[] s_ret = Eddsa.sign(msg, sk, base0, base1); assert (Eddsa.verify(msg, s_ret, pk0, pk1, base0, base1)); } } @Test public void testEddsa() { Group base = new Group("5dfbb35a38ffdcab".getBytes(), 1, 256, 8); for (int i = 0; i < 100; i++) { Field.FR sk = Field.newFR(Arrays.randomBytes(32)); byte[] msg = Arrays.randomBytes(32); Point pk = base.mult(sk); byte[] s_ret = Eddsa.sign(msg, sk, base); assert (Eddsa.verify(msg, s_ret, pk, base)); } } }
class Subtraction { int num1; int num2; int res1; int res2; int res3; int res4; public void Perform() { res1=num1*num2; res2=num1-num2; res3=num1%num2; res4=num1/num2; } } public class ClassSubDemo { public static void main(String[] args) { // TODO Auto-generated method stub Subtraction obj=new Subtraction(); obj.num1=4; obj.num2=19; obj.Perform(); System.out.println(obj.res1); System.out.println(obj.res2); System.out.println(obj.res3); System.out.println(obj.res4); } }
package com.mahendra.library.models; import java.io.Serializable; public class Member implements Serializable { private Integer id; private String firstName; private String lastName; private char status; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public char getStatus() { return status; } public void setStatus(char status) { this.status = status; } public Member(Integer id, String firstName, String lastName, char status) { super(); this.id = id; this.firstName = firstName; this.lastName = lastName; this.status = status; } public Member() { super(); } }
package com.jim.multipos.ui.vendor_item_managment; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.View; import com.jim.mpviews.MpToolbar; import com.jim.multipos.core.SimpleActivity; import com.jim.multipos.ui.billing_vendor.BillingOperationsActivity; import com.jim.multipos.ui.consignment.ConsignmentActivity; import com.jim.multipos.ui.consignment_list.ConsignmentListActivity; import com.jim.multipos.ui.product_queue_list.ProductQueueListActivity; import com.jim.multipos.ui.vendor_item_managment.fragments.VendorItemFragment; import com.jim.multipos.ui.vendor_products_view.VendorProductsViewActivity; import com.jim.multipos.utils.TextWatcherOnTextChange; import static com.jim.multipos.ui.consignment.ConsignmentActivity.OPERATION_TYPE; import static com.jim.multipos.ui.inventory.InventoryActivity.VENDOR_ID; /** * Created by developer on 09.11.2017. */ public class VendorItemsActivity extends SimpleActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); VendorItemFragment fragment = new VendorItemFragment(); addFragment(fragment); toolbar.getSearchEditText().addTextChangedListener(new TextWatcherOnTextChange() { @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { fragment.searchText(toolbar.getSearchEditText().getText().toString()); } }); toolbar.getBarcodeView().setVisibility(View.GONE); } @Override protected int getToolbar() { return WITH_TOOLBAR; } @Override protected int getToolbarMode() { return MpToolbar.WITH_SEARCH_TYPE; } public void sendDataToConsignment(Long vendorId, int consignment_type) { Intent intent = new Intent(this, ConsignmentActivity.class); intent.putExtra(VENDOR_ID, vendorId); intent.putExtra(OPERATION_TYPE, consignment_type); startActivity(intent); } public void openVendorDetails(Long vendorId) { Intent intent = new Intent(this, VendorProductsViewActivity.class); intent.putExtra(VENDOR_ID, vendorId); startActivity(intent); } public void openVendorConsignmentStory(Long vendorId) { Intent intent = new Intent(this, ConsignmentListActivity.class); intent.putExtra(VENDOR_ID, vendorId); startActivity(intent); } public void openVendorBillingStory(Long vendorId, Double totalDebt) { Intent intent = new Intent(this, BillingOperationsActivity.class); intent.putExtra(BillingOperationsActivity.VENDOR_EXTRA_ID, vendorId); startActivity(intent); } public void openProductQueueStory(Long id) { Intent intent = new Intent(this, ProductQueueListActivity.class); intent.putExtra(VENDOR_ID, id); startActivity(intent); } }
package randomBlockPartition; import java.io.IOException; import org.apache.hadoop.io.*; import org.apache.hadoop.mapreduce.*; public class randomBlockPartition_map extends Mapper<LongWritable, Text, Text, Text>{ public static final int[] blocks = {0,10328,20373,30629,40645,50462,60841,70591,80118,90497,100501,110567,120945,130999,140574,150953, 161332,171154,181514,191625,202004,212383,222762,232593,242878,252938,263149,273210,283473,293255, 303043,313370,323522,333883,343663,353645,363929,374236,384554,394929,404712,414617,424747,434707, 444489,454285,464398,474196,484050,493968,503752,514131,524510,534709,545088,555467,565846,576225, 586604,596585,606367,616148,626448,636240,646022,655804,665666,675448,685230}; public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException{ String[] parameter = getParameters(value); int nodeID = Integer.parseInt(parameter[0]); float PageRank = Float.parseFloat(parameter[1]); int outDegree = Integer.parseInt(parameter[2]); String outgoingLinks = parameter.length == 4? parameter[3]:""; int blockID = badBlockIDofNode(nodeID); context.write(new Text(""+blockID), new Text("is_node " + nodeID + " " + PageRank + " " + outgoingLinks)); if (outgoingLinks != "") { String[] outlinks = outgoingLinks.split(","); for(String s : outlinks){ int blockIDofNeighbor = badBlockIDofNode(Integer.parseInt(s)); Text valueOfmap = new Text(); //If the node and its neighbor are in the same block, map this relation. if(blockID == blockIDofNeighbor){ valueOfmap = new Text("same_block " + nodeID + " " + s); } //If the node and its neighbor are in different blocks, map this relation and the boundary condition. else{ float v = PageRank / outDegree; valueOfmap = new Text("differ_block " + nodeID + " " + s + " " + v); } context.write(new Text(""+blockIDofNeighbor), valueOfmap); } } } public String[] getParameters(Text value){ return value.toString().trim().split("\\s+"); } /** * Given a block ID, check whether or not it is in 'blocks' */ public static boolean checkInblocks(int n){ for(int m : blocks){ if(n == m){ return true; } } return false; } public int badBlockIDofNode(int nodeID){ return (nodeID % 68); } }
/* * Copyright (c) 2017. Universidad Politecnica de Madrid * * @author Badenes Olmedo, Carlos <cbadenes@fi.upm.es> * */ package org.librairy.modeler.lda.tasks; import com.google.common.base.Strings; import com.google.common.collect.ImmutableMap; import com.google.common.primitives.Doubles; import org.apache.spark.api.java.JavaRDD; import org.apache.spark.mllib.clustering.LocalLDAModel; import org.apache.spark.mllib.linalg.Vector; import org.apache.spark.mllib.linalg.Vectors; import org.apache.spark.rdd.RDD; import org.apache.spark.sql.Row; import org.apache.spark.sql.RowFactory; import org.apache.spark.sql.SaveMode; import org.apache.spark.sql.types.DataTypes; import org.apache.spark.sql.types.StructField; import org.librairy.boot.model.Event; import org.librairy.boot.model.domain.relations.Relation; import org.librairy.boot.model.domain.resources.Item; import org.librairy.boot.model.domain.resources.Part; import org.librairy.boot.model.domain.resources.Resource; import org.librairy.boot.model.modules.RoutingKey; import org.librairy.boot.model.utils.TimeUtils; import org.librairy.boot.storage.dao.DBSessionManager; import org.librairy.boot.storage.generator.URIGenerator; import org.librairy.computing.cluster.ComputingContext; import org.librairy.metrics.aggregation.Bernoulli; import org.librairy.metrics.similarity.JensenShannonSimilarity; import org.librairy.modeler.lda.dao.*; import org.librairy.modeler.lda.functions.RowToSimRow; import org.librairy.modeler.lda.functions.RowToTupleVector; import org.librairy.modeler.lda.functions.TupleToResourceShape; import org.librairy.modeler.lda.helper.ModelingHelper; import org.librairy.modeler.lda.models.Corpus; import org.librairy.modeler.lda.models.Text; import org.librairy.modeler.lda.models.TopicModel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import scala.Tuple2; import java.util.*; import java.util.concurrent.ConcurrentLinkedQueue; import static org.apache.parquet.example.Paper.r1; /** * Created on 12/08/16: * * @author cbadenes */ public class LDAIndividualShapingTask implements Runnable { private static final Logger LOG = LoggerFactory.getLogger(LDAIndividualShapingTask.class); public static final String ROUTING_KEY_ID = "lda.individual.shape.created"; private final ModelingHelper helper; private final String domainUri; private final Set<String> uris; public LDAIndividualShapingTask(String domainUri, ModelingHelper modelingHelper, Set<String> uris) { this.domainUri = domainUri; this.helper = modelingHelper; this.uris = uris; } // // @Override // public void run() { // // try{ // String contextId = "lda.ind.shape."+ URIGenerator.retrieveId(domainUri)+"."+URIGenerator.retrieveId(resourceUri); // final ComputingContext context = helper.getComputingHelper().newContext(contextId); // helper.getComputingHelper().execute(context, () -> { // try{ // LOG.info("Ready to analyze '"+resourceUri+"'.."); // String domainId = URIGenerator.retrieveId(domainUri); // Resource.Type type = URIGenerator.typeFrom(resourceUri); // List<Text> texts = new ArrayList<Text>(); // String partialUri = ""; // String id = URIGenerator.retrieveId(resourceUri); // switch (type){ // case ITEM: // partialUri = "/documents/"+id; // texts.add(new Text(URIGenerator.retrieveId(resourceUri), helper.getCustomItemsDao().getTokens(domainUri, resourceUri))); // break; // case PART: // partialUri = "/parts/"+id; // texts.add(new Text(URIGenerator.retrieveId(resourceUri), helper.getCustomPartsDao().getTokens(domainUri, resourceUri))); // break; // case DOMAIN: // partialUri = "/subdomains/"+id; // Optional<String> offset = Optional.empty(); // Integer size = 100; // Boolean finished = false; // // documents // while(!finished){ // List<Item> docs = helper.getDomainsDao().listItems(resourceUri, size, offset, false); // if (docs.isEmpty()) break; // for (Item item: docs){ // String tokens = helper.getCustomItemsDao().getTokens(domainUri, item.getUri()); // LOG.debug("Adding doc '" + item.getUri()+"' from subdomain: '" + resourceUri + "'"); // if (!Strings.isNullOrEmpty(tokens)) texts.add(new Text(item.getUri(), tokens )); // } // finished = (docs.size() < size); // if (!finished) offset = Optional.of(docs.get(size-1).getUri()); // } // // // parts // offset = Optional.empty(); // finished = false; // while(!finished){ // List<Part> parts = helper.getDomainsDao().listParts(resourceUri, size, offset, false); // if (parts.isEmpty()) break; // for (Part part: parts){ // String tokens = helper.getCustomPartsDao().getTokens(domainUri, part.getUri()); // LOG.debug("Adding part '" + part.getUri()+"' from subdomain: '" + resourceUri + "'"); // if (!Strings.isNullOrEmpty(tokens)) texts.add(new Text(part.getUri(), tokens )); // } // finished = (parts.size() < size); // if (!finished) offset = Optional.of(parts.get(size-1).getUri()); // } // break; // // } // // if (texts.isEmpty() || Strings.isNullOrEmpty(texts.get(0).getContent())) { // LOG.info("No tokens available for resource: " + resourceUri + " in domain: " + domainUri); // return; // } // // final Integer partitions = context.getRecommendedPartitions(); // // // Load existing model // TopicModel model = helper.getModelsCache().getModel(context, domainUri); // if (model == null) { // LOG.warn("No model found by domain: " + domainUri); // return; // } // // // Create a corpus with only one document // Corpus corpus = new Corpus(context, domainId, Arrays.asList(new Resource.Type[]{type}), helper); // // final String completeUri = domainUri+partialUri; // // corpus.loadTexts(texts); // // // Use of existing vocabulary // corpus.setCountVectorizerModel(model.getVocabModel()); // // // LDA Model // LocalLDAModel localLDAModel = model.getLdaModel(); // // // // Create and Save shape // final Tuple2<Object,double[]> shape = localLDAModel // .topicDistributions(corpus.getBagOfWords()) // .toJavaRDD() // .map( a -> new Tuple2<Object,double[]>(a._1, a._2.toArray())) // .reduce( (a,b) -> new Tuple2<Object,double[]>(a._1, Bernoulli.apply(a._2,b._2))); // // corpus.clean(); // // List<Double> topicVector = Doubles.asList(shape._2); // // final ShapeRow shapeRow = new ShapeRow(); // shapeRow.setDate(TimeUtils.asISO()); // shapeRow.setUri(resourceUri); // shapeRow.setVector(topicVector); // shapeRow.setId(Long.valueOf(id.hashCode())); // this.helper.getShapesDao().save(domainUri,shapeRow); // // // save in lda_.distributions // for (int i=0;i<topicVector.size(); i++){ // // String topicUri = domainUri+"/topics/"+i; // DistributionRow distributionRow = new DistributionRow(resourceUri, type.key(),topicUri,TimeUtils.asISO(),topicVector.get(i)); // this.helper.getDistributionsDao().save(domainUri, distributionRow); // } // LOG.info("Saved topic distributions for: " + completeUri); // // //// // calculate similarities //// JavaRDD<SimilarityRow> simRows = context.getCassandraSQLContext() //// .read() //// .format("org.apache.spark.sql.cassandra") //// .schema(DataTypes //// .createStructType(new StructField[]{ //// DataTypes.createStructField(ShapesDao.RESOURCE_URI, DataTypes.StringType, false), //// DataTypes.createStructField(ShapesDao.VECTOR, DataTypes.createArrayType(DataTypes.DoubleType), false) //// })) //// .option("inferSchema", "false") // Automatically infer data types //// .option("charset", "UTF-8") ////// .option("spark.sql.autoBroadcastJoinThreshold","-1") //// .option("mode", "DROPMALFORMED") //// .options(ImmutableMap.of("table", ShapesDao.TABLE, "keyspace", DBSessionManager.getSpecificKeyspaceId("lda",URIGenerator.retrieveId(domainUri)))) //// .load() //// .repartition(partitions) //// .toJavaRDD() //// .flatMap( new RowToSimRow(shapeRow.getUri(), shape._2)) //// .filter(el -> el.getScore() > 0.5) //// .cache() //// ; //// //// LOG.info("Calculating similarities for: " + completeUri); //// simRows.take(1);// force cache //// //// context.getSqlContext().createDataFrame(simRows, SimilarityRow.class) //// .write() //// .format("org.apache.spark.sql.cassandra") //// .options(ImmutableMap.of("table", SimilaritiesDao.TABLE, "keyspace", DBSessionManager.getSpecificKeyspaceId("lda",URIGenerator.retrieveId(domainUri)))) //// .mode(SaveMode.Append) //// .save(); //// //// LOG.info("Saved similarities for: " + completeUri); //// //// // Increase similarities counter //// helper.getCounterDao().increment(domainUri, Relation.Type.SIMILAR_TO_ITEMS.route(), simRows.count()); //// //// simRows.unpersist(); //// //// //TODO update similarity graph // // // Publish an Event //// helper.getEventBus().post(Event.from(completeUri), RoutingKey.of(ROUTING_KEY_ID)); //// LOG.info("Published event for: " + completeUri); // // LOG.info("Task completed!!!"); // } catch (Exception e){ // if (e instanceof InterruptedException){ LOG.info("Execution interrupted during process.");} // else LOG.error("Error scheduling an individual topic model distribution for Resource: "+ resourceUri +" in domain: " + domainUri, e); // } // }); // } catch (InterruptedException e) { // LOG.info("Execution interrupted."); // } // LOG.info("LDA Individual task executed!!!"); // // } @Override public void run(){ try{ final ComputingContext context = helper.getComputingHelper().newContext("lda.individualshapes."+ URIGenerator.retrieveId(domainUri)); helper.getComputingHelper().execute(context, () -> { try{ LOG.info("Initializing Spark SQL Context.."); context.getCassandraSQLContext().prepareForExecution(); LOG.info("working .."); List<String> uriList = new ArrayList<String>(uris); // Create corpus Corpus corpus = helper.getCorpusBuilder().build(context, domainUri, Arrays.asList(new Resource.Type[]{Resource.Type.ITEM, Resource.Type.PART}), uriList); // Load existing model String domainId = URIGenerator.retrieveId(domainUri); TopicModel model = helper.getLdaBuilder().load(context, domainId); // Use of existing vocabulary corpus.setCountVectorizerModel(model.getVocabModel()); // Calculate topic distributions for Items and Parts helper.getDealsBuilder().build(context, corpus,model); corpus.clean(); uriList.parallelStream().forEach( uri -> helper.getShapeService().shapeProcessed(domainUri, uri)); } catch (Exception e){ if (e instanceof InterruptedException){ LOG.info("Execution interrupted during process.");} else LOG.error("Error scheduling a new topic model for Items from domain: " + domainUri, e); } }); } catch (InterruptedException e) { LOG.info("Execution interrupted."); } } }
/* * Copyright (C) 2019-2023 Hedera Hashgraph, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hedera.mirror.web3.repository; import com.hedera.mirror.common.domain.file.FileData; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; @Repository public interface FileDataRepository extends CrudRepository<FileData, Long> { @Query( value = """ with latest_create as ( select max(file_data.consensus_timestamp) as consensus_timestamp from file_data where file_data.entity_id = ?1 and file_data.transaction_type in (17, 19) ) select string_agg(file_data.file_data, '' order by file_data.consensus_timestamp) as file_data from file_data join latest_create l on file_data.consensus_timestamp >= l.consensus_timestamp where file_data.entity_id = ?1 and file_data.transaction_type in (16, 17, 19) and ?2 >= l.consensus_timestamp""", nativeQuery = true) byte[] getFileAtTimestamp(long fileId, long timestamp); }
package com.pybeta.ui.widget; import android.app.Dialog; import android.content.Context; import android.os.Bundle; public class CustomDialog extends Dialog { private int mLayout; public CustomDialog(Context context, int layout,int style) { super(context, style); this.mLayout = layout; } public CustomDialog(Context context){ super(context); } @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); // set content setContentView(mLayout); } }
package com.vilio.nlbs.commonMapper.dao; import com.vilio.nlbs.commonMapper.pojo.NlbsRecordersDistributor; import java.util.List; /** * Created by dell on 2017/6/29. */ public interface NlbsRecordersDistributorMapper { List<NlbsRecordersDistributor> selectRecordersDistributorByUserNo(String userNo); }
package tim.prune.undo; import tim.prune.I18nManager; import tim.prune.data.DataPoint; import tim.prune.data.Photo; import tim.prune.data.TrackInfo; /** * Operation to undo an auto-correlation of photos with points */ public class UndoCorrelatePhotos implements UndoOperation { private DataPoint[] _contents = null; private DataPoint[] _photoPoints = null; private int _numPhotosCorrelated = -1; /** * Constructor * @param inTrackInfo track information */ public UndoCorrelatePhotos(TrackInfo inTrackInfo) { // Copy track contents _contents = inTrackInfo.getTrack().cloneContents(); // Copy points associated with photos before correlation int numPhotos = inTrackInfo.getPhotoList().getNumPhotos(); _photoPoints = new DataPoint[numPhotos]; for (int i=0; i<numPhotos; i++) { _photoPoints[i] = inTrackInfo.getPhotoList().getPhoto(i).getDataPoint(); } } /** * @param inNumCorrelated number of photos correlated */ public void setNumPhotosCorrelated(int inNumCorrelated) { _numPhotosCorrelated = inNumCorrelated; } /** * @return description of operation including parameters */ public String getDescription() { return I18nManager.getText("undo.correlatephotos") + " (" + _numPhotosCorrelated + ")"; } /** * Perform the undo operation on the given Track * @param inTrackInfo TrackInfo object on which to perform the operation */ public void performUndo(TrackInfo inTrackInfo) throws UndoException { // restore track to previous values inTrackInfo.getTrack().replaceContents(_contents); // restore photo association for (int i=0; i<_photoPoints.length; i++) { Photo photo = inTrackInfo.getPhotoList().getPhoto(i); // Only need to look at connected photos, since correlation wouldn't disconnect if (photo.getCurrentStatus() == Photo.Status.CONNECTED) { DataPoint prevPoint = _photoPoints[i]; DataPoint currPoint = photo.getDataPoint(); photo.setDataPoint(prevPoint); if (currPoint != null) { currPoint.setPhoto(null); // disconnect } if (prevPoint != null) { prevPoint.setPhoto(photo); // reconnect to prev point } } } // clear selection inTrackInfo.getSelection().clearAll(); } }
package com.facebook.react.flat; final class FlatRootShadowNode extends FlatShadowNode { FlatRootShadowNode() { forceMountToView(); signalBackingViewIsCreated(); } } /* Location: C:\Users\august\Desktop\tik\df_rn_kit\classes.jar.jar!\com\facebook\react\flat\FlatRootShadowNode.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
import java.text.DecimalFormat; public class Index{ public String word; public int number_of_apps; public float frequency; public Index(String word, int nr){ this.word = word; this.number_of_apps = nr; this.frequency = 0; } @Override public String toString(){ DecimalFormat decimal = new DecimalFormat("#.###"); return ""+decimal.format(this.frequency); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import javax.jws.WebService; import Conexion.ConexionBD; import logica.Banco; import logica.BancoId; import logica.EAgua; import logica.EAguaId; /** * Clase que permite realizar operaciones sobre el banco en la base de datos * @author LEIDY * */ public class BancoDao{ /** * Método que permite ingresar informacion de un nuevo banco a la * base de datos * @param banco * @return */ public boolean guardaBanco(Banco banco){ try { Connection conn = ConexionBD.obtenerConexion(); String queryInsertar = "INSERT INTO banco VALUES(?,?,?,?)"; PreparedStatement ppStm = conn.prepareStatement(queryInsertar); ppStm.setInt(1, banco.getId().getNumeroCuenta()); ppStm.setDouble(2, banco.getSaldo()); ppStm.setString(3, banco.getNombreBanco()); ppStm.setInt(4, banco.getId().getClienteCedula()); ppStm.executeUpdate(); conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } return true; } /** * Método que permite actualizar la informacion del banco * en la base de datos * @param banco * @return */ public boolean actualizaBanco(int id, double saldoNuevo){ try { Connection conn = ConexionBD.obtenerConexion(); String queryUpdate = "UPDATE banco SET" + " Saldo = ? WHERE Cliente_Cedula= ?"; PreparedStatement ppStm = conn.prepareStatement(queryUpdate); ppStm.setDouble(1, saldoNuevo); ppStm.setInt(2, id); ppStm.executeUpdate(); conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } return true; } /** * Método que permite eliminar la informacion del banco * @param banco * @return */ public boolean eliminaBanco(Banco banco){ try { Connection conn = ConexionBD.obtenerConexion(); String queryDelete = "DELETE FROM banco WHERE Numero_Cuenta = ?"; PreparedStatement ppStm = conn.prepareStatement(queryDelete); ppStm.setInt(1, banco.getId().getNumeroCuenta()); ppStm.executeUpdate(); conn.close(); return true; } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } } /** * Método que permite retorna la informacion de un banco * que se encuentra almacenado en la base de datos * @param id * @return */ public Banco obtenBanco(int id){ Banco banco = null; try { Connection conn = ConexionBD.obtenerConexion(); String querySearch = "SELECT * FROM banco WHERE Cliente_Cedula = ?"; PreparedStatement ppStm = conn.prepareStatement(querySearch); ppStm.setInt(1, id); ResultSet resultSet = ppStm.executeQuery(); if(resultSet.next()){ banco = new Banco(); banco.setId(new BancoId(resultSet.getInt(1),resultSet.getInt(4))); banco.setSaldo(resultSet.getDouble(2)); banco.setNombreBanco(resultSet.getString(3)); }else{ return banco; } conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return banco; } public List<Banco> obtenListaBanco(){ List<Banco> listaBanco = null; return listaBanco; } // public static void main(String[] args) { // // BancoDao daob = new BancoDao(); // ClienteDao daoc = new ClienteDao(); // daob.guardaBanco(new Banco(new BancoId(7845692,daoc.obtenCliente(108796548).getCedula()), 80000,"Bancolombia")); // // } }
package main; import gui.LoginPage; import javax.swing.JOptionPane; public class Main { public static void main(String arg[]) { try { LoginPage frame=new LoginPage(); frame.setSize(300,100); frame.setVisible(true); frame.setDefaultCloseOperation(javax.swing. WindowConstants.DISPOSE_ON_CLOSE); } catch(Exception e) {JOptionPane.showMessageDialog(null, e.getMessage());} } }
package com.mahii.flavoursdemo; /** * @author i_m_mahii, mahi05 */ public class Constants { public static final String BaseUrl = "https://api.myjson.com/bins/4evqi"; }
package net.doepner.ws.model.de; import net.doepner.ws.model.Categories.Numerus; import net.doepner.ws.model.Categories.Person; /** * TODO */ public abstract class Hilfsverb extends DeutschesVerb { public Hilfsverb(String infinitiv, String praeteritumStamm, String partizipPerfekt) { this(infinitiv, praeteritumStamm, partizipPerfekt, false); } public Hilfsverb(String infinitiv, String praeteritumStamm, String partizipPerfekt, boolean hilfsverbSein) { super(infinitiv, praeteritumStamm, partizipPerfekt, hilfsverbSein); init(); } protected abstract void init(); public static final Hilfsverb HABEN = new Hilfsverb("haben", "hatte", "gehabt") { @Override protected void init() { setPraesensForm(Numerus.SINGULAR , Person.P2, "hast"); setPraesensForm(Numerus.SINGULAR , Person.P3, "hat"); } }; public static final Hilfsverb WERDEN = new Hilfsverb("werden", "wurde", "geworden", true) { @Override protected void init() { setPraesensForm(Numerus.SINGULAR , Person.P2, "wirst"); setPraesensForm(Numerus.SINGULAR , Person.P3, "wird"); } }; public static final Hilfsverb SEIN = new Hilfsverb("sein", "war", "gewesen", true) { @Override protected void init() { setPraesensForm(Numerus.SINGULAR , Person.P1, "bin"); setPraesensForm(Numerus.SINGULAR , Person.P2, "bist"); setPraesensForm(Numerus.SINGULAR , Person.P3, "ist"); setPraesensForm(Numerus.PLURAL , Person.P1, "sind"); setPraesensForm(Numerus.PLURAL , Person.P2, "seid"); setPraesensForm(Numerus.PLURAL , Person.P3, "sind"); } }; }
import javax.xml.crypto.Data; import java.io.*; import java.net.ServerSocket; import java.net.Socket; import java.util.Scanner; public class Resub { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); String website = "ftp.dlptest.com"; Socket sock = new Socket(website, 21); DataOutputStream os = new DataOutputStream(sock.getOutputStream()); BufferedReader br = new BufferedReader(new InputStreamReader(sock.getInputStream())); getReturnCode(br); // Connects to server send(os, br, "USER dlpuser@dlptest.com"); send(os, br, "PASS 5p2tvn92R0di8FdiLCfzeeT0b"); Socket dataSock = createDataSocket(os, br, website); boolean active = true; String input, replycode; do { System.out.println( "\n1. Show current directory\t" + "5. Upload file\n" + "2. Change directory\t\t\t" + "6. Set file transfer type (BETA)\n" + "3. Create directory\t" + "\t\t7. QUIT\n" + "4. Download file" ); input = sc.nextLine(); if (dataSock == null){ dataSock = createDataSocket(os, br, website); } switch (input) { case "1": showDirectory(os, br, dataSock); dataSock = null; break; case "2": System.out.println("Name of directory (leave blank to go back):"); input = sc.nextLine(); changeDirectory(os, br, input); break; case "3": System.out.println("Name of new directory:"); input = sc.nextLine(); createDirectory(os, br, input); break; case "4": System.out.println("Name of file to download:"); input = sc.nextLine(); downloadFile(os, br, dataSock, input); dataSock = null; break; case "5": System.out.println("Name of file to upload:"); input = sc.nextLine(); uploadFile(os, br, dataSock, input); dataSock = null; break; case "6": System.out.println("Choose between ASCII (A) or image (I):"); input = sc.nextLine(); changeTransferType(os, br, input); break; case "7": System.out.println("Quitting..."); active = false; break; } } while(active); } public static void changeTransferType(DataOutputStream os, BufferedReader br, String input) throws IOException { if (!input.equalsIgnoreCase("A") && !input.equalsIgnoreCase("I")) System.out.println("Incorrect type"); else send(os, br, "TYPE " + input); } public static Socket createDataSocket(DataOutputStream os, BufferedReader br, String web) throws IOException { send(os, "PASV"); String response = br.readLine(); System.out.println(response); while (!response.substring(0,3).equals("227")){ response = br.readLine(); //System.out.println(response); } String[] ipPort = response.substring(27,response.length()-1).split(","); int port = Integer.parseInt(ipPort[4]) * 256 + Integer.parseInt(ipPort[5]); return new Socket(web, port); } public static void uploadFile(DataOutputStream os, BufferedReader br, Socket dataSock, String fileName) throws IOException { File file = new File(fileName); if(file.exists()) { DataOutputStream dataOS = new DataOutputStream(dataSock.getOutputStream()); String replycode = send(os, br, "STOR " + fileName); if (replycode.substring(0, 3).equals("150")) { FileInputStream fileIS = new FileInputStream(file); BufferedReader fileBR = new BufferedReader(new InputStreamReader(fileIS)); String line = fileBR.readLine(); while (line != null) { dataOS.writeBytes(line + "\n"); line = fileBR.readLine(); } /* int next = fileIS.read(); while(next != -1) { dataOS.writeBoolean(Integer.toBinaryString(next)); next = fileIS.read(); } */ dataOS.close(); getReturnCode(br); } } else{ System.out.println("Error: No such file exists"); } } public static void downloadFile(DataOutputStream os, BufferedReader br, Socket dataSock, String fileName) throws IOException { String replycode = send(os, br, "RETR " + fileName); StringBuilder sb = new StringBuilder(); if (replycode.equals("150")) { InputStreamReader dataReader = new InputStreamReader(dataSock.getInputStream()); File file = new File(fileName); FileOutputStream fileOS = new FileOutputStream(file); int counter = 0; char next; do { next = (char) dataReader.read(); if (counter < 125){ sb.append(next); counter++; } fileOS.write(next); } while (dataReader.ready()); fileOS.close(); getReturnCode(br); System.out.println("\nFile downloaded. Preview of the first Kb:"); System.out.println(sb.toString()); } } public static void createDirectory(DataOutputStream os, BufferedReader br, String name) throws IOException { send(os, br, "MKD " + name); } public static void showDirectory(DataOutputStream os, BufferedReader br, Socket dataSock) throws IOException { send(os, "LIST"); BufferedReader dataBR = new BufferedReader(new InputStreamReader(dataSock.getInputStream())); getReturnCode(dataBR); } public static void changeDirectory(DataOutputStream os, BufferedReader br, String name) throws IOException { send(os, br, "CWD " + name); } public static String getReturnCode(BufferedReader br) throws IOException { String reply = null; do{ reply = br.readLine(); System.out.println(reply); }while(br.ready()); if (reply == null){ return null; } return reply.substring(0,3); } public static int getFileSize(DataOutputStream os, BufferedReader br, String fileName) throws IOException { send(os, "SIZE " + fileName); String reply = br.readLine(); String size = "-1"; if (reply.substring(0,3).equals("213")){ size = reply.substring(4,7); } while(br.ready()){ System.out.println(br.readLine()); } return Integer.parseInt(size); } public static String send(DataOutputStream os, BufferedReader br, String msg) throws IOException { os.writeBytes(msg + "\r\n"); return getReturnCode(br); } public static void send(DataOutputStream os, String msg) throws IOException { os.writeBytes(msg + "\r\n"); } }
package com.example.demo.product; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.util.List; import java.util.Optional; @RestController @RequestMapping("/products") public class ProductController { @Autowired ProductService productService; @GetMapping() public List<Product> getProduct() { return productService.retrieveProduct(); } @GetMapping("/{id}") public ResponseEntity<?> getProduct(@PathVariable Long id) { Optional<Product> product = productService.retrieveProduct(id); if(!product.isPresent()) { return ResponseEntity.notFound().build(); } return ResponseEntity.ok(product); } @GetMapping("/search") public List<Product> getProduct(@RequestParam(value = "productName") String productName ) { return productService.retrieveProduct(productName); } @PostMapping() public ResponseEntity<?> postProduct(@Valid @RequestBody Product body) { Product product = productService.createProduct(body); return ResponseEntity.status(HttpStatus.CREATED).body(product); } @PutMapping("/{id}") public ResponseEntity<?> putProduct(@PathVariable Long id, @Valid @RequestBody Product body) { Optional<Product> product = productService.updateProduct(id, body); if(!product.isPresent()) { return ResponseEntity.notFound().build(); } return ResponseEntity.ok().build(); } @DeleteMapping("/{id}") public ResponseEntity<?> deleteProduct(@PathVariable Long id) { if(!productService.deleteProduct(id)) { return ResponseEntity.notFound().build(); } return ResponseEntity.ok().build(); } }
package com.tencent.mm.sdk.e; import android.content.ContentValues; import android.database.Cursor; import com.tencent.mm.sdk.e.c.a; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import junit.framework.Assert; public abstract class i<T extends c> extends j implements d<T> { private final e diF; public int field_MARK_CURSOR_CHECK_IGNORE = 1; public final a sKB; private final String table; public i(e eVar, a aVar, String str, String[] strArr) { int i = 0; this.diF = eVar; this.sKB = aVar; this.sKB.sKz = bi.oW(this.sKB.sKz) ? "rowid" : this.sKB.sKz; this.table = str; List a = a(this.sKB, getTableName(), this.diF); for (int i2 = 0; i2 < a.size(); i2++) { if (!this.diF.fV(this.table, (String) a.get(i2))) { x.i("MicroMsg.SDK.MAutoStorage", "updateColumnSQLs table failed %s, sql %s", this.table, a.get(i2)); } } if (strArr != null && strArr.length > 0) { while (i < strArr.length) { this.diF.fV(this.table, strArr[i]); i++; } } } public String getTableName() { return this.table; } public static String a(a aVar, String str) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("CREATE TABLE IF NOT EXISTS " + str + " ( "); stringBuilder.append(aVar.sql); stringBuilder.append(");"); return stringBuilder.toString(); } public static List<String> a(a aVar, String str, e eVar) { List<String> arrayList = new ArrayList(); if (eVar == null || str == null) { boolean z; String str2 = "MicroMsg.SDK.MAutoStorage"; String str3 = "dk getUpdateSQLs db==null :%b table:%s"; Object[] objArr = new Object[2]; if (eVar == null) { z = true; } else { z = false; } objArr[0] = Boolean.valueOf(z); objArr[1] = str; x.e(str2, str3, objArr); return arrayList; } Cursor b = eVar.b("PRAGMA table_info( " + str + " )", new String[0], 2); if (b == null) { return arrayList; } Map hashMap = new HashMap(); int columnIndex = b.getColumnIndex("name"); int columnIndex2 = b.getColumnIndex("type"); while (b.moveToNext()) { hashMap.put(b.getString(columnIndex), b.getString(columnIndex2)); } b.close(); for (Entry entry : aVar.sKA.entrySet()) { String str4 = (String) entry.getValue(); String str5 = (String) entry.getKey(); if (str4 != null && str4.length() > 0) { String str6 = (String) hashMap.get(str5); if (str6 == null) { arrayList.add("ALTER TABLE " + str + " ADD COLUMN " + str5 + " " + str4 + ";"); hashMap.remove(str5); } else if (!str4.toLowerCase().startsWith(str6.toLowerCase())) { x.e("MicroMsg.SDK.MAutoStorage", "conflicting alter table on column: " + str5 + ", " + str6 + "<o-n>" + str4); hashMap.remove(str5); } } } return arrayList; } public final boolean fV(String str, String str2) { if (str.length() == 0) { Xr("null or nill table"); return false; } else if (str2 != null && str2.length() != 0) { return this.diF.fV(str, str2); } else { Xr("null or nill sql"); return false; } } public boolean b(T t) { return a((c) t, true); } public boolean a(T t, boolean z) { ContentValues wH = t.wH(); if (wH == null || wH.size() <= 0) { Xr("insert failed, value.size <= 0"); return false; } t.sKx = this.diF.insert(getTableName(), this.sKB.sKz, wH); if (t.sKx <= 0) { Xr("insert failed"); return false; } wH.put("rowid", Long.valueOf(t.sKx)); if (z) { Xp(wH.getAsString(this.sKB.sKz)); } return true; } public boolean a(T t, boolean z, String... strArr) { boolean z2 = false; ContentValues wH = t.wH(); if (wH == null || wH.size() <= 0) { Xr("delete failed, value.size <= 0"); return false; } else if (strArr == null || strArr.length <= 0) { Xq("delete with primary key"); if (this.diF.delete(getTableName(), this.sKB.sKz + " = ?", new String[]{bi.oV(wH.getAsString(this.sKB.sKz))}) > 0) { z2 = true; } if (!z2 || !z) { return z2; } doNotify(); return z2; } else { StringBuilder a = a(wH, strArr); if (a == null) { Xr("delete failed, check keys failed"); return false; } else if (this.diF.delete(getTableName(), a.toString(), a(strArr, wH)) <= 0 || !z) { Xr("delete failed"); return false; } else { Xp(this.sKB.sKz); return true; } } } public boolean a(T t, String... strArr) { return a((c) t, true, strArr); } public boolean delete(long j) { boolean z = true; if (this.diF.delete(getTableName(), "rowid = ?", new String[]{String.valueOf(j)}) <= 0) { z = false; } if (z) { doNotify(); } return z; } public final boolean b(long j, T t) { Cursor a = this.diF.a(getTableName(), this.sKB.columns, "rowid = ?", new String[]{String.valueOf(j)}, null, null, null, 2); if (a.moveToFirst()) { t.d(a); a.close(); return true; } a.close(); return false; } public boolean b(T t, String... strArr) { ContentValues wH = t.wH(); Cursor a; if (wH == null || wH.size() <= 0) { Xr("get failed, value.size <= 0"); return false; } else if (strArr == null || strArr.length <= 0) { Xq("get with primary key"); a = this.diF.a(getTableName(), this.sKB.columns, this.sKB.sKz + " = ?", new String[]{bi.oV(wH.getAsString(this.sKB.sKz))}, null, null, null, 2); if (a.moveToFirst()) { t.d(a); a.close(); return true; } a.close(); return false; } else { StringBuilder a2 = a(wH, strArr); if (a2 == null) { Xr("get failed, check keys failed"); return false; } a = this.diF.a(getTableName(), this.sKB.columns, a2.toString(), a(strArr, wH), null, null, null, 2); if (a.moveToFirst()) { t.d(a); a.close(); return true; } a.close(); Xq("get failed, not found"); return false; } } public final boolean a(long j, T t, boolean z) { ContentValues wH = t.wH(); if (wH == null || wH.size() <= 0) { Xr("update failed, value.size <= 0"); return false; } Cursor query = this.diF.query(getTableName(), this.sKB.columns, "rowid = ?", new String[]{String.valueOf(j)}, null, null, null); if (c.a(wH, query)) { query.close(); Xq("no need replace , fields no change"); return true; } boolean z2; query.close(); if (this.diF.update(getTableName(), wH, "rowid = ?", new String[]{String.valueOf(j)}) > 0) { z2 = true; } else { z2 = false; } if (!z2 || !z) { return z2; } doNotify(); return z2; } public boolean a(long j, T t) { return a(j, (c) t, true); } public boolean b(T t, boolean z, String... strArr) { boolean z2 = false; ContentValues wH = t.wH(); if (wH == null || wH.size() <= 0) { Xr("update failed, value.size <= 0"); return false; } else if (strArr == null || strArr.length <= 0) { Xq("update with primary key"); if (b(wH)) { Xq("no need replace , fields no change"); return true; } if (this.diF.update(getTableName(), wH, this.sKB.sKz + " = ?", new String[]{bi.oV(wH.getAsString(this.sKB.sKz))}) > 0) { z2 = true; } if (!z2 || !z) { return z2; } doNotify(); return z2; } else { StringBuilder a = a(wH, strArr); if (a == null) { Xr("update failed, check keys failed"); return false; } else if (this.diF.update(getTableName(), wH, a.toString(), a(strArr, wH)) > 0) { if (z) { Xp(wH.getAsString(this.sKB.sKz)); } return true; } else { Xr("update failed"); return false; } } } public boolean c(T t, String... strArr) { return b(t, true, strArr); } public boolean a(T t) { Assert.assertTrue("replace primaryKey == null", !bi.oW(this.sKB.sKz)); ContentValues wH = t.wH(); if (wH != null) { int i; int size = wH.size(); int length = t.AX().sKy.length; if (wH.containsKey("rowid")) { i = 1; } else { i = 0; } if (size == i + length) { if (b(wH)) { Xq("no need replace , fields no change"); return true; } else if (this.diF.replace(getTableName(), this.sKB.sKz, wH) > 0) { Xp(this.sKB.sKz); return true; } else { Xr("replace failed"); return false; } } } Xr("replace failed, cv.size() != item.fields().length"); return false; } private boolean b(ContentValues contentValues) { Cursor query = this.diF.query(getTableName(), this.sKB.columns, this.sKB.sKz + " = ?", new String[]{bi.oV(contentValues.getAsString(this.sKB.sKz))}, null, null, null); boolean a = c.a(contentValues, query); query.close(); return a; } public Cursor axc() { return this.diF.query(getTableName(), this.sKB.columns, null, null, null, null, null); } public int getCount() { Cursor rawQuery = rawQuery("select count(*) from " + getTableName(), new String[0]); if (rawQuery == null) { return 0; } rawQuery.moveToFirst(); int i = rawQuery.getInt(0); rawQuery.close(); return i; } public final Cursor rawQuery(String str, String... strArr) { return this.diF.rawQuery(str, strArr); } private static StringBuilder a(ContentValues contentValues, String... strArr) { StringBuilder stringBuilder = new StringBuilder(); for (String str : strArr) { stringBuilder.append(str + " = ? AND "); if (contentValues.get(str) == null) { return null; } } stringBuilder.append(" 1=1"); return stringBuilder; } private static String[] a(String[] strArr, ContentValues contentValues) { String[] strArr2 = new String[strArr.length]; for (int i = 0; i < strArr2.length; i++) { strArr2[i] = bi.oV(contentValues.getAsString(strArr[i])); } return strArr2; } private void Xq(String str) { x.d("MicroMsg.SDK.MAutoStorage", getTableName() + ":" + str); } private void Xr(String str) { x.e("MicroMsg.SDK.MAutoStorage", getTableName() + ":" + str); } }
package com.mantouland.atool; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.Drawable; import android.os.Handler; import android.support.annotation.NonNull; import android.widget.ImageView; import com.mantouland.atool.cachestrategy.CacheStrategy; import com.mantouland.atool.cachestrategy.impl.MemCache; import com.mantouland.atool.cachestrategy.impl.StorCache; import com.mantouland.atool.callback.impl.PicCallBack; import com.mantouland.atool.compressstrategy.CompressStrategy; import com.mantouland.atool.compressstrategy.impl.ScaleCompress; import com.mantouland.atool.compressstrategy.option.CacheOption; import com.mantouland.atool.compressstrategy.option.CompressOption; import com.mantouland.atool.security.Impl.SecurityMD5; import com.mantouland.atool.security.Security; import java.util.ArrayList; import java.util.List; /** * Created by asparaw on 2019/4/2. */ public class APic { private APicBuilder builder; private static final int DEFAULT = 0; private static final Handler UIHandler= new Handler(); private String mAddress; private ImageView mImageView; private APic(APicBuilder aPicBuilder){ this.builder=aPicBuilder; } public static APicBuilder with(Context context){ return new APicBuilder(context); } public void startBitmap(){ } public APic load(@NonNull String address){ mAddress=address; return this; } public void into(@NonNull ImageView imageView){ mImageView=imageView; loadImageView(true); } public void into(@NonNull ImageView imageView,boolean isCompress){ mImageView=imageView; loadImageView(isCompress); } public void intoNoCompress(@NonNull ImageView imageView){ mImageView=imageView; loadImageView(false); } private Bitmap compress(Bitmap bitmap){ for (CompressStrategy compressStrategy:builder.compressStrategyList){ bitmap=compressStrategy.compress(bitmap,builder.compressOption); } return bitmap; } private void cache(Bitmap bitmap,final String url){ if (!builder.skipMemCache){ MemCache.getInstance().put(url,bitmap); } builder.cacheStrategy.put(url,bitmap); } void autoCompress(){ if (builder.compressOption!=null){ builder.compressOption = new CompressOption(); } builder.compressOption.setHeight(mImageView.getHeight()); builder.compressOption.setWidth(mImageView.getWidth()); boolean hasScale =false; for (CompressStrategy compressStrategy:builder.compressStrategyList){ if (compressStrategy instanceof ScaleCompress){ hasScale =true; break; } } if (hasScale) builder.compressStrategyList.add(0,ScaleCompress.getInstance()); } void loadImageView(boolean autoCompress){ //compress if (autoCompress) autoCompress(); //load pic mImageView.setTag(makeTag()); if (builder.placePic!=null){ mImageView.setImageDrawable(builder.placePic); } loadBitmap(new PicCallBack() { @Override public void onSuccess(Bitmap bitmap) { if (mImageView.getTag().equals(makeTag())){ mImageView.setImageBitmap(bitmap); } } @Override public void onFail(Exception e) { if (builder.errorPic!=null &&mImageView.getTag().equals(makeTag())){ mImageView.setImageDrawable(builder.errorPic); } e.printStackTrace(); } },makeTag()); } // void getImage(PicCallBack picCallBack){ loadBitmap(picCallBack,makeTag()); } private String makeTag(){ if (builder.compressStrategyList!=null){ return builder.security.encode(mAddress); }else { return builder.security.encode(mAddress+builder.compressOption); } } private void loadBitmap(final PicCallBack picCallBack,final String tag){ AExecutorPool.getInstance().execute(new Runnable() { @Override public void run() { Bitmap bitmap=null; //Load From Mem if (!builder.skipMemCache){ bitmap=MemCache.getInstance().get(tag); } //Load From CacheStrategy if (bitmap==null){ bitmap=builder.cacheStrategy.get(tag); } //Load From Http if (bitmap==null){ bitmap = tag.contains("http")? readHttp(mAddress):readFile(mAddress); } //Check if (bitmap!=null){ bitmap=compress(bitmap); cache(bitmap,tag); }else { runOnUIThread(picCallBack,null,new Exception("can't get pic url:"+tag)); } } }); } private Bitmap readHttp(String url){ return HTTPHelper.getInstance().doPic(url,DEFAULT); } private Bitmap readFile(String url){ return BitmapFactory.decodeFile(url); } private void runOnUIThread(final PicCallBack callback, final Bitmap bitmap, final Exception e) { UIHandler.post(new Runnable() { @Override public void run() { if (e == null) callback.onSuccess(bitmap); else callback.onFail(e); } }); }; public static class APicBuilder{ Context mContext; private Security security; private CacheStrategy cacheStrategy; private CompressOption compressOption; private CacheOption cacheOption; private List<CompressStrategy> compressStrategyList = new ArrayList<>(); private Drawable placePic; private Drawable errorPic; private boolean skipMemCache; private APicBuilder(Context context){ mContext=context; cacheOption=new CacheOption(); cacheOption.setPath(context.getExternalCacheDir().getPath()); } /*** * builder * */ public APicBuilder setSecurity(Security security) { this.security = security; return this; } public APicBuilder setCacheStrategy(CacheStrategy cacheStrategy) { this.cacheStrategy = cacheStrategy; if (cacheStrategy instanceof StorCache){ ((StorCache) cacheStrategy).setDir(cacheOption.getPath()); } return this; } public APicBuilder addCompressStrategy(CompressStrategy compressStrategy) { compressStrategyList.add(compressStrategy); return this; } public APicBuilder setCompressOption(CompressOption compressOption) { this.compressOption = compressOption; return this; } public APicBuilder setCacheOption(CacheOption cacheOption){ this.cacheOption = cacheOption; return this; } public APicBuilder setSkipMemCache(boolean skipMemCache) { this.skipMemCache = skipMemCache; return this; } //no use of @DrawableRes public APicBuilder setErrorPic( Drawable errorPic) { this.errorPic = errorPic; return this; } public APicBuilder setPlacePic( Drawable placePic) { this.placePic = placePic; return this; } //@IdRes public APicBuilder setErrorPic( int id){ this.errorPic = mContext.getResources().getDrawable(id); return this; } public APicBuilder setPlacePic(int id){ this.placePic = mContext.getResources().getDrawable(id); return this; } public APic build(){ try { check(); } catch (Exception e) { e.printStackTrace(); } return new APic(this); } public APic load(String address){ return build().load(address); } void check() throws Exception { if (mContext !=null){ throw new Exception("lack of context"); } if (!compressStrategyList.isEmpty()&&compressOption==null){ setCompressOption(new CompressOption()); } if (security!=null){ setSecurity(SecurityMD5.getInstance()); } if (cacheStrategy!=null){ // } } } }