text
stringlengths
10
2.72M
package com.meehoo.biz.core.basic.util; //import com.alibaba.fastjson.JSON; import com.meehoo.biz.common.io.JsonUtil; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Service; /** * @author zc * @date 2019-08-02 */ @Service public class RedisTemplateService { private StringRedisTemplate stringRedisTemplate; public RedisTemplateService(StringRedisTemplate stringRedisTemplate) { this.stringRedisTemplate = stringRedisTemplate; } public <T> boolean set(String key , T value){ try { //任意类型转换成String String val = beanToString(value); if(val==null||val.length()<=0){ return false; } stringRedisTemplate.opsForValue().set(key,val); return true; }catch (Exception e){ return false; } } public <T> T get(String key,Class<T> clazz){ try { String value = stringRedisTemplate.opsForValue().get(key); return stringToBean(value,clazz); }catch (Exception e){ return null ; } } @SuppressWarnings("unchecked") private <T> T stringToBean(String value, Class<T> clazz) { if(value==null||value.length()<=0||clazz==null){ return null; } if(clazz ==int.class ||clazz==Integer.class){ return (T)Integer.valueOf(value); } else if(clazz==long.class||clazz==Long.class){ return (T)Long.valueOf(value); } else if(clazz==String.class){ return (T)value; }else { return JsonUtil.fromJson(value,clazz); } } /** * * @return String */ private <T> String beanToString(T value) { if(value==null){ return null; } Class <?> clazz = value.getClass(); if(clazz==int.class||clazz==Integer.class){ return ""+value; } else if(clazz==long.class||clazz==Long.class){ return ""+value; } else if(clazz==String.class){ return (String)value; }else { return JsonUtil.toJson(value); } } }
package br.imd.visao; import java.awt.Container; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.Map; import javax.swing.JInternalFrame; import javax.swing.JLabel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; import com.mxgraph.swing.mxGraphComponent; import com.mxgraph.util.mxConstants; import com.mxgraph.view.mxEdgeStyle; import com.mxgraph.view.mxGraph; import br.imd.modelo.Arvore; import br.imd.modelo.Computador; import br.imd.modelo.Dia; import br.imd.modelo.Usuario; public class TelaGraficoUsuario extends JInternalFrame { public TelaGraficoUsuario(Arvore arvore, int idUsuario) { super("Gráfico de eventos por usuário", false, true); /*********************************************************************** * * Grafico * * ***********************************************************************/ mxGraph graph = new mxGraph(); Object parent = graph.getDefaultParent(); Usuario usuario = arvore.getUsuarios().get(idUsuario); graph.setAllowDanglingEdges(false); graph.setCellsEditable(false); graph.setCellsMovable(false); //Linhas ortogonais Map<String, Object> style = graph.getStylesheet().getDefaultEdgeStyle(); style.put(mxConstants.STYLE_EDGE, mxEdgeStyle.TopToBottom); style.put(mxConstants.STYLE_ROUNDED, true); graph.getModel().beginUpdate(); try { Object v1 = graph.insertVertex(parent, null, usuario.getUser(), (usuario.getDias().size()*40)+160, 20, 100, 20); int x = 0; for(Dia atual: usuario.getDias()){ Object v2 = graph.insertVertex(parent, null, atual.getData(), (x*80)+160, 100, 70, 20); graph.insertEdge(parent, null, "", v1, v2); x++; } }finally{ graph.getModel().endUpdate(); } /************************************************************************** * * Criação do nó pc apartir do click * **************************************************************************/ final mxGraphComponent graphComponent = new mxGraphComponent(graph); getContentPane().add(graphComponent); graphComponent.getGraphControl().addMouseListener(new MouseAdapter(){ public void mouseReleased(MouseEvent e) { Object cell = graphComponent.getCellAt(e.getX(), e.getY()); if(e.getButton() == MouseEvent.BUTTON1){ if (cell != null && e.getY()<180 && e.getY()>100){ System.out.println("Expandir cell="+graph.getLabel(cell)); Dia dia = usuario.buscaDiaBinaria(graph.getLabel(cell)); int qtdx = dia.getComputadores().size(); int x = 0; for(Computador atual : dia.getComputadores()){ //ajusta deslocamento para os computadores if(x<(qtdx/2)){ x = x*(-1); } //criar vertex do computador Object vComputador = graph.insertVertex(parent, null, atual.getNomeComputador(), e.getX()+(x*80)-35 , 180, 70, 20); graph.insertEdge(parent, null, "", cell, vComputador); //criar vertex dos eventos Object vLogon = graph.insertVertex(parent, null, "Logon: " + atual.getLogons(), e.getX()-160, 280, 70, 20); Object vLogoff = graph.insertVertex(parent, null, "Logoff: " + atual.getLogoffs(), e.getX()-80, 280, 70, 20); Object vConnect = graph.insertVertex(parent, null, "Connect: " + atual.getConnects(), e.getX(), 280, 70, 20); Object vDesconnect = graph.insertVertex(parent, null, "Desconnect: " + atual.getDesconnects(), e.getX()+80, 280, 75, 20); Object vSite = graph.insertVertex(parent, null, "Sites: " + atual.getHttps().size(), e.getX()+160, 280, 70, 20); graph.insertEdge(parent, null, "", vComputador, vLogon); graph.insertEdge(parent, null, "", vComputador, vLogoff); graph.insertEdge(parent, null, "", vComputador, vConnect); graph.insertEdge(parent, null, "", vComputador, vDesconnect); graph.insertEdge(parent, null, "", vComputador, vSite); //Se existi eventos sites cria os vertex também if(atual.getHttps().size()>0){ int qtdURL = atual.getHttps().size(); int xURL = ((qtdURL/2)*115)*(-1); for(String url : atual.getHttps()){ //criar vertex do computador Object vURL = graph.insertVertex(parent, null, url, e.getX()+xURL , 350, 110, 20); graph.insertEdge(parent, null, "", vSite, vURL); xURL+= 115; } } x++; } } }else if(e.getButton() == MouseEvent.BUTTON3){ if (cell != null && e.getY()>=180){ System.out.println("Remover cell=" + graph.getLabel(cell)); graph.setSelectionCell(cell); graph.removeCells(); } } } }); /*************************************************************************** * * Finalização da tela * * ***************************************************************************/ this.setSize(700, 530); //this.setDefaultCloseOperation(this.EXIT_ON_CLOSE); this.setDefaultCloseOperation(JInternalFrame.DISPOSE_ON_CLOSE); } }
class Ani2 { public void prt(){System.out.println("ani2 prt!!");} } class Dog2 extends Ani2 { public void view() {System.out.println("view");} } public class ClassCastTest1 { public static void main(String[] args) { // TODO Auto-generated method stub //Ani2 ins=new Dog2(); Ani2 ins = new Dog2(); Dog2 ins2 = (Dog2)ins; ins2.prt(); ins2.view(); //Dog2 ins3 =(Dog2)new Ani2();//Exception in thread "main" view java.lang.ClassCastException: Ani2 cannot be cast to Dog2 at ClassCastTest1.main(ClassCastTest1.java:18) Ani2 ins3=new Ani2(); System.out.println(ins instanceof Dog2); System.out.println(ins2 instanceof Dog2); //해당 객체가 뒤에걸로 바꿀때 괜찬은지 여부 } }
//package StepDef; // //import java.util.concurrent.TimeUnit; //import org.apache.logging.log4j.LogManager; //import org.apache.logging.log4j.Logger; //import org.junit.Assert; //import org.openqa.selenium.OutputType; //import org.openqa.selenium.TakesScreenshot; // //import Base.WebDriverFactory; //import io.cucumber.java.After; //import io.cucumber.java.Before; //import io.cucumber.java.Scenario; //import io.cucumber.java.en.*; ////import pages.Refer_A_Friend_Page; //import pages.Sign_Up_Page; // //public class Sign_Up_Pom extends WebDriverFactory { // // private static final Logger logger = LogManager.getLogger(Sign_Up_Pom.class); // // Sign_Up_Page sign_Up_Page; //// Refer_A_Friend_Page refer_A_Friend_Page; // // @Before // public void setUp(Scenario scn) throws Exception { // this.scn = scn; // String browserName = WebDriverFactory.getBrowserName(); // driver = WebDriverFactory.getWebDriverForBrowser(browserName); // logger.info("Browser invoked."); // sign_Up_Page = new Sign_Up_Page(driver); //// refer_A_Friend_Page = new Refer_A_Friend_Page(driver); // } // // @Given("User opened browser") // @Deprecated // public void User_opened_browser() { // // /* // * System.setProperty("webdriver.chrome.driver", "Browser\\chromedriver.exe"); // * driver = new ChromeDriver(); driver.manage().window().maximize(); // * driver.manage().deleteAllCookies(); // * driver.manage().timeouts().implicitlyWait(Wait_Time_Second, // * TimeUnit.SECONDS); // */ // } // // @Given("User navigates to the application url") // public void user_navigates_to_the_application_url() { // // driver.get(Base_Url); // scn.log("Browser navigated to URL: " + Base_Url); // String expected = "http://automationpractice.com/index.php"; // String actual = driver.getCurrentUrl(); // Assert.assertEquals("Page URL validation", expected, actual); // scn.log("Page url validation successfull. Actual Url: " + actual); // logger.info("Page Url validation successfull. Expected and actual text matched. Text: " + actual); // logger.info("<User is navigates to the application url>"); // } // // @Given("User clicks on Sign in link at the top right corner of the application") // public void user_clicks_on_sign_in_link_at_the_top_right_corner_of_the_application() { // sign_Up_Page.Clk_Login_Link(); // } // // @When("User enters valid email address and click on create an account button") // public void user_enters_valid_email_address_and_click_on_create_an_account_button() { // sign_Up_Page.Txt_Sign_Up(); // driver.manage().timeouts().implicitlyWait(Wait_Time_Second, TimeUnit.SECONDS); // } // // @When("User fill the sign up form") // public void User_fill_the_sign_up_form() { // driver.manage().timeouts().implicitlyWait(Wait_Time_Second, TimeUnit.SECONDS); // sign_Up_Page.Sign_Up_Form(); // driver.manage().timeouts().implicitlyWait(Wait_Time_Second, TimeUnit.SECONDS); // // } // // @Then("User is sign up successfully") // public void user_is_sign_up_successfully() { // System.out.println("test5"); // logger.info("Sign Up Successfully"); // } // // @After(order = 1) // public void Clean_Up() { // WebDriverFactory.quitDriver(); // } // // @After(order = 2) // public void takeScreenShot(Scenario s) { // if (s.isFailed()) { // TakesScreenshot scrnShot = (TakesScreenshot) driver; // byte[] data = scrnShot.getScreenshotAs(OutputType.BYTES); // scn.attach(data, "image/png", "Failed Step Name: " + s.getName()); // } else { // scn.log("Test case is passed, no screen shot captured"); // } // } //} //
package com.k2data.k2app.utils; import com.k2data.k2app.exception.K2Exception; /** * 类相关的工具类 * * @author lidong9144@163.com 17-3-10. */ public class ClassUtils { /** * 判断是否是基本类型或其包装类型 * * @param clazz 要判断的类 * @return true 如果是基本类型或包装类型 */ public static boolean isPrimitiveOrWrapper(Class<?> clazz) { return Integer.TYPE.equals(clazz) || Integer.class.equals(clazz) || Double.TYPE.equals(clazz) || Double.class.equals(clazz) || Long.TYPE.equals(clazz) || Long.class.equals(clazz) || Float.TYPE.equals(clazz) || Float.class.equals(clazz) || Short.TYPE.equals(clazz) || Short.class.equals(clazz) || Byte.TYPE.equals(clazz) || Byte.class.equals(clazz) || Character.TYPE.equals(clazz) || Character.class.equals(clazz) || Boolean.TYPE.equals(clazz) || Boolean.class.equals(clazz); } /** * 转换基本类型为包装类型 * * @param type 基本类型 * @return 包装类型 */ @SuppressWarnings("unchecked") public static <T> Class<T> primitiveToWrapper(final Class<T> type) { if (type == null || !type.isPrimitive()) { return type; } if (type == Integer.TYPE) { return (Class<T>) Integer.class; } else if (type == Double.TYPE) { return (Class<T>) Double.class; } else if (type == Long.TYPE) { return (Class<T>) Long.class; } else if (type == Boolean.TYPE) { return (Class<T>) Boolean.class; } else if (type == Float.TYPE) { return (Class<T>) Float.class; } else if (type == Short.TYPE) { return (Class<T>) Short.class; } else if (type == Byte.TYPE) { return (Class<T>) Byte.class; } else if (type == Character.TYPE) { return (Class<T>) Character.class; } else { return type; } } /** * 转换包装类型为基本类型 * * @param type 基本类型 * @return 包装类型 */ @SuppressWarnings("unchecked") public static <T> Class<T> wrapperToPrimitive(final Class<T> type) { if (type == null || type.isPrimitive()) { return type; } if (type == Integer.class) { return (Class<T>) Integer.TYPE; } else if (type == Double.class) { return (Class<T>) Double.TYPE; } else if (type == Long.class) { return (Class<T>) Long.TYPE; } else if (type == Boolean.class) { return (Class<T>) Boolean.TYPE; } else if (type == Float.class) { return (Class<T>) Float.TYPE; } else if (type == Short.class) { return (Class<T>) Short.TYPE; } else if (type == Byte.class) { return (Class<T>) Byte.TYPE; } else if (type == Character.class) { return (Class<T>) Character.TYPE; } else { return type; } } /** * 获取对应{@link Class}的一个实例,该{@link Class}必须要有空的构造函数 * * @param clazz 需要创建实例的{@link Class} * @return 一个实例 */ public static <T> T newInstance(final Class<T> clazz) { try { return clazz.newInstance(); } catch (InstantiationException | IllegalAccessException ie) { throw new K2Exception(ie); } } /** * 用于判断是否是Proxy * CGLib 代理 判断字段 {@code $$EnhancerByCGLIB$$} * JDK 代理 判断字段 {@code $Proxy} * * @param clazz {@link Class}用来判断 * @return {@code true} 如果是Proxy */ public static boolean isProxy(final Class<?> clazz) { if (clazz == null) return false; final String name = clazz.getName(); return name.contains("$$EnhancerByCGLIB$$") || name.contains("$Proxy"); } /** * 获取一个类的原始类,避免取得{@code proxy} * * @param <T> 类名 * @param clazz 要被取原始类的{@link Class} * @return 原生类 */ @SuppressWarnings("unchecked") public static <T> Class<T> getOriginalClass(final Class<T> clazz) { if (isProxy(clazz)) { return (Class<T>) clazz.getSuperclass(); } else { return clazz; } } /** * 对于数组获取数组中数据的类型 * * @param arrayClazz 数组的类 * @return 数组中数据的实际类型 */ @SuppressWarnings("unchecked") public static <T> Class<T> getArrayClass(final Class<?> arrayClazz) { final String className = arrayClazz.getName(); if ("[I".equals(className)) { return (Class<T>) Integer.TYPE; } else if ("[J".equals(className)) { return (Class<T>) Long.TYPE; } else if ("[D".equals(className)) { return (Class<T>) Double.TYPE; } else if ("[F".equals(className)) { return (Class<T>) Float.TYPE; } else if ("[C".equals(className)) { return (Class<T>) Character.TYPE; } else if ("[S".equals(className)) { return (Class<T>) Short.TYPE; } else if ("[Z".equals(className)) { return (Class<T>) Boolean.TYPE; } else if ("[B".equals(className)) { return (Class<T>) Byte.TYPE; } else if ("[V".equals(className)) { return (Class<T>) Void.TYPE; } return (Class<T>) arrayClazz; } /** * 通过类名获取对应的类 * * @param className 类名 * @return 对应的类 */ @SuppressWarnings("unchecked") public static <T> Class<T> getClass(final String className) { final ClassLoader contextCL = Thread.currentThread().getContextClassLoader(); final ClassLoader loader = contextCL == null ? ClassLoader.getSystemClassLoader(): contextCL; try { final String abbreviation = getClassAbbreviation(className); if (className.equals(abbreviation)) { // 非基础类型 return (Class<T>) Class.forName(getFullyQualifiedName(className), false, loader); } else { // 基础类型 return (Class<T>) Class.forName("[" + abbreviation, false, loader).getComponentType(); } } catch(ClassNotFoundException cnfe) { throw new K2Exception(cnfe); } } /** * 是否是Java 自有的类型 * * @param clazz 要判断的类 * @return true 如果是JDK自有类型 */ public static boolean isJdkType(final Class<?> clazz) { if (clazz == null) return true; final String name = clazz.getName(); return clazz.isPrimitive() || name.startsWith("java.applet.") || name.startsWith("java.awt.") || name.startsWith("java.beans.") || name.startsWith("java.io.") || name.startsWith("java.lang.") || name.startsWith("java.math.") || name.startsWith("java.net.") || name.startsWith("java.nio.") || name.startsWith("java.rmi.") || name.startsWith("java.security.") || name.startsWith("java.sql.") || name.startsWith("java.text.") || name.startsWith("java.util.") || name.startsWith("java.rmi.") || name.startsWith("com.oracle.") || name.startsWith("com.sun.") || name.startsWith("javax.accessibility.") || name.startsWith("javax.activation.") || name.startsWith("javax.annotation.") || name.startsWith("javax.imageio.") || name.startsWith("javax.jws.") || name.startsWith("javax.lang.") || name.startsWith("javax.management.") || name.startsWith("javax.naming.") || name.startsWith("javax.print.") || name.startsWith("javax.rmi.") || name.startsWith("javax.script.") || name.startsWith("javax.security.") || name.startsWith("javax.smartcardio.") || name.startsWith("javax.sound.") || name.startsWith("javax.sql.") || name.startsWith("javax.swing.") || name.startsWith("javax.tools.") || name.startsWith("javax.transaction.") || name.startsWith("javax.xml.") || name.startsWith("org.ietf.") || name.startsWith("org.jcp.") || name.startsWith("org.omg.") || name.startsWith("org.w3c.") || name.startsWith("org.xml.") || name.startsWith("sun.applet.") || name.startsWith("sun.audio.") || name.startsWith("sun.awt.") || name.startsWith("sun.beans.") || name.startsWith("sun.corba.") || name.startsWith("sun.dc.") || name.startsWith("sun.font.") || name.startsWith("sun.instrument.") || name.startsWith("sun.io.") || name.startsWith("sun.java2d.") || name.startsWith("sun.jdbc.") || name.startsWith("sun.jkernel.") || name.startsWith("sun.management.") || name.startsWith("sun.misc.") || name.startsWith("sun.net.") || name.startsWith("sun.nio.") || name.startsWith("sun.org.") || name.startsWith("sun.print.") || name.startsWith("sun.reflect.") || name.startsWith("sun.rmi.") || name.startsWith("sun.security.") || name.startsWith("sun.swing.") || name.startsWith("sun.text.") || name.startsWith("sun.tools.") || name.startsWith("sun.usagetracker.") || name.startsWith("sun.util.") || name.startsWith("sunw.io.") || name.startsWith("sunw.util.") || name.startsWith("javax.net.") || name.startsWith("javax.crypto."); } /****************************************************************************************** * 内部私有的工具类 ******************************************************************************************/ /** * 获取类型的全部描述,用于从{@link ClassLoader}那里获取对应的{@link Class} * * @param className 类名 * @return 类型的全部描述 */ private static String getFullyQualifiedName(final String className) { if (className.endsWith("[]")) { // 对于Array、Entry等要加以判断 StringBuffer sb = new StringBuffer(); String name = className; while(name.endsWith("[]")) { name = name.substring(0, name.length() - 2); sb.append("["); } final String abbreviation = getClassAbbreviation(name); if (StringUtils.isBlank(abbreviation)) { sb.append("L").append(name).append(";"); } else { sb.append(abbreviation); } return sb.toString(); } return className; } /** * 获取类名的简写,用于从{@link ClassLoader}那里获取对应的{@link Class} * * @param className 类名 * @return 类名的简写,如果有的话 */ private static String getClassAbbreviation(final String className) { if ("int".equals(className)) { return "I"; } else if ("long".equals(className)) { return "J"; } else if ("double".equals(className)) { return "D"; } else if ("float".equals(className)) { return "F"; } else if ("char".equals(className)) { return "C"; } else if ("short".equals(className)) { return "S"; } else if ("boolean".equals(className)) { return "Z"; } else if ("byte".equals(className)) { return "B"; } else if ("void".equals(className)) { return "V"; } return className; } }
package org.firstinspires.ftc.teamcode.opmodes; import com.qualcomm.robotcore.eventloop.opmode.Autonomous; import com.qualcomm.robotcore.eventloop.opmode.Disabled; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.util.ElapsedTime; import org.firstinspires.ftc.teamcode.base_classes.AutoBot; /** * This is a basic opmode for auto. * PLEASE USE GETTERS AND SETTERS INSTEAD OF DIRECTLY SETTING VARIABLES * <p> * TODO: make robot able to deal with the fact that there is another robot on the same team * TODO: make robot carry block */ @Autonomous(name = "Basic Auto", group = "Auto") @Disabled public class BaseAuto extends LinearOpMode { public AutoBot robot = new AutoBot(this); public ElapsedTime runtime = new ElapsedTime(); /** * stage of auto: 0 is initial, 1 is strafing to position to sense blocks, 2 is strafing to * front of sky stone, 3 is approaching sky stone, 4 is backing up from sky stone, */ public int stageNum = 0; public float targetX; // x position of the target public float targetY; // y position of the target public float stoneXTolerance = 3; // how close (x-wise) (left/right) the robot needs to be in order to pick up a stone public float stoneYTolerance = 2; // how close (y-wise) the edge of the robot needs to be to the edge of a stone in order to pick up a stone public float safeDistance = 9; // how far the robot needs to go back before strafing back public float dropPosition = 12; // what x position the robot can drop the sky stone at /** * get the safe distance * * @return safe distance */ public float getSafeDistance() { return safeDistance; } /** * set the safe distance * * @param safeDistance */ public void setSafeDistance(float safeDistance) { this.safeDistance = safeDistance; } /** * get the drop position * * @return drop position */ public float getDropPosition() { return dropPosition; } /** * set the drop position * * @param dropPosition */ public void setDropPosition(float dropPosition) { this.dropPosition = dropPosition; } public float getStoneXTolerance() { return stoneXTolerance; } public void setStoneXTolerance(float stoneXTolerance) { this.stoneXTolerance = stoneXTolerance; } public float getStoneYTolerance() { return stoneYTolerance; } public void setStoneYTolerance(float stoneYTolerance) { this.stoneYTolerance = stoneYTolerance; } public float getTargetX() { return targetX; } public void setTargetX(float targetX) { this.targetX = targetX; } public float getTargetY() { return targetY; } public void setTargetY(float targetY) { this.targetY = targetY; } public int getStageNum() { return stageNum; } public void setStageNum(int stageNum) { this.stageNum = stageNum; } public AutoBot getRobot() { return robot; } public void setRobot(AutoBot robot) { this.robot = robot; } @Override public void runOpMode() { telemetry.addData("Status", "Initialized"); telemetry.update(); robot.init(); // robot.initTracking(); // Wait for the game to start (driver presses PLAY) waitForStart(); runtime.reset(); // run until the end of auto (driver presses STOP) while (opModeIsActive()) { robot.getNav().updateView(); // Show the elapsed game time and wheel power. telemetry.addData("Status", "Run Time: " + runtime.toString()); telemetry.update(); float robotX = this.getRobot().getNav().getRobotX(); float robotY = this.getRobot().getNav().getRobotY(); float alliance = this.getRobot().getNav().getAlliance(); switch (this.getStageNum()) { case 0: // if just starting up if (robotY > 0) { this.getRobot().strafeRight(1); this.getRobot().getNav().setAlliance(1); this.setStageNum(1); } else if (robotY < 0) { this.getRobot().strafeLeft(1); this.getRobot().getNav().setAlliance(-1); this.setStageNum(1); } case 1: if (this.getRobot().getNav().getSkyStonePosition(0) != -1 && this.getRobot().getNav().getSkyStonePosition(1) != -1) { this.setTargetX(Math.min(this.getRobot().getNav().getSkyStoneCenterX(0), this.getRobot().getNav().getSkyStoneCenterX(1))); this.setTargetY(this.getRobot().getNav().getSkyStoneCenterY(0)); this.setStageNum(2); } case 2: if (Math.abs(robotX - this.getTargetX()) <= this.getStoneXTolerance()) { this.setStageNum(3); this.getRobot().driveForwards(1); } else { if (robotX > this.getTargetX() && this.getRobot().getLeftPower() * alliance > 0) { this.getRobot().strafeRight(alliance); } else if (robotX < this.getTargetX() && this.getRobot().getLeftPower() * alliance < 0) { this.getRobot().strafeLeft(alliance); } } case 3: if (robotY * alliance - alliance * this.getRobot().getRobotLength() / 2 - 24 <= this.getStoneYTolerance()) { this.getRobot().stopDriving(); // TODO: grab stone this.setStageNum(4); this.getRobot().driveForwards(-1); } case 4: if (robotY * alliance >= this.getSafeDistance() + 24) { this.getRobot().strafeLeft(alliance); this.setStageNum(5); } case 5: if (robotX >= this.getDropPosition()) { this.getRobot().stopDriving(); // TODO: release stone this.setStageNum(6); // done } } } } }
package iofilestest.cheese; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; public class CheeseManagerTest { @Rule public TemporaryFolder tmp = new TemporaryFolder(); @Test public void testSaveToFileThrows() { Exception ex = assertThrows(IllegalArgumentException.class, () -> new CheeseManager().saveToFile(null, null)); assertEquals("Path is null.", ex.getMessage()); ex = assertThrows(IllegalArgumentException.class, () -> new CheeseManager().saveToFile(tmp.newFile().toPath(), null)); assertEquals("Cheeses is null.", ex.getMessage()); } @Test public void testSaveToFile() throws IOException { Path testFile = tmp.newFile("cheeses.bin").toPath(); List<Cheese> cheesesTest = new ArrayList<>(); cheesesTest.add(new Cheese("Cheese1", 1)); cheesesTest.add(new Cheese("Cheese2", 2)); cheesesTest.add(new Cheese("Cheese3", 3)); cheesesTest.add(new Cheese("Cheese4", 4)); new CheeseManager().saveToFile(testFile, cheesesTest); List<String> lines = Files.readAllLines(testFile); assertEquals(4, lines.size()); assertEquals("Cheese2;2.0", lines.get(1).toString()); } @Test public void testFindCheese() throws IOException { Path testFile = tmp.newFile("cheeses.bin").toPath(); Files.writeString(testFile, "Cheese1;1.0\n" + "Cheese2;2.0\n" + "Cheese3;3.0\n" + "Cheese4;4.0\n", StandardOpenOption.CREATE); assertEquals("Cheese3;3.0", new CheeseManager().findCheese(testFile, "Cheese3").toString()); assertEquals(null, new CheeseManager().findCheese(testFile, "Cheese5")); } }
package com.flowedu.error; public enum FlowEduErrorCode { NOT_AUTHENTICATE(401, "Not authenticated"), NOT_AUTHORIZED(403, "Not authorized"), INTERNAL_ERROR(500, "Internal server error"), BAD_REQUEST(400, "Bad request, parameter not accepted"), NOT_ALLOW_FILE_NAME_KOREAN(901, "not allow korean name"), CUSTOM_DATA_LIST_NULL(902, "data list is null!"), CUSTOM_IMAGE_FILE_NAME_KOREAN(903, "image file name is Korean!"), CUSTOM_IMAGE_FILE_EXTENSION_NOT_ALLOW(904, "file extension not allow!"), CUSTOM_IMAGE_FILE_SIZE_LIMIT(905, "ifile size limit error!"), CUSTOM_ASSIGNMENT_FILE_EXTENSION_NOT_ALLOW(906, "assignment file extension not allow!"), CUSTOM_PAYMENT_ACCESS_CODE_NULL(911, "payment access code is null!"); int code; String msg; FlowEduErrorCode(int code, String msg){ this.msg = msg; this.code = code; } public int code() { return code; } public String msg() { return msg; } }
package main.java.controller; import java.awt.Color; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.awt.Shape; import java.awt.geom.GeneralPath; import java.awt.geom.Ellipse2D; import java.awt.geom.Rectangle2D; import java.awt.BasicStroke; import main.java.model.Face; import main.java.model.Piece; /** Creates pieces by generating graphics given textual characteristics */ /* TODO: support a scale factor ? */ public class PieceSynthetizer { public static BufferedImage synthetize(Piece piece) { Face[] faces = piece.getFaces(); BufferedImage img = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB); Graphics2D graphics = img.createGraphics(); int[] xBgPoints = {0, 100, 50}; int[] yBgPoints = {0, 0, 50}; graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); graphics.setStroke(new BasicStroke(0)); for (int orientation = 0; orientation < 4; orientation++) { graphics.setColor(translateColor(faces[orientation].getBgColor())); graphics.fillPolygon(xBgPoints, yBgPoints, 3); graphics.setColor(translateColor(faces[orientation].getFgColor())); graphics.fill(translatePattern(faces[orientation].getPattern())); graphics.rotate(Math.PI / 2, 50, 50); } graphics.setColor(Color.BLACK); graphics.setStroke(new BasicStroke(2)); graphics.drawRect(0, 0, 99, 99); graphics.setStroke(new BasicStroke(0)); graphics.drawLine(1, 1, 99, 99); graphics.drawLine(99, 1, 1, 99); graphics.drawImage(img, 0, 0, 100, 100, null); return img; } private static Color translateColor(String colorName) { Color color; switch (colorName.toLowerCase()) { case "white": color = new Color(255, 255, 255); break; case "blue": color = new Color(50, 120, 255); break; case "red": color = new Color(255, 50, 50); break; case "green": color = new Color(30, 255, 80); break; case "purple": color = new Color(220, 80, 255); break; case "yellow": color = new Color(220, 255, 50); break; case "brown": color = new Color(180, 120, 30); break; case "cyan": color = new Color(75, 200, 230); break; default: //System.out.println("Translated unknown color to black"); color = Color.BLACK; break; } //System.out.println("Translate color: " + color); return color; } private static Shape translatePattern(String patternName) { GeneralPath shape = new GeneralPath(); switch (patternName.toLowerCase()) { case "triangle": shape.moveTo(30, 0); shape.lineTo(70, 0); shape.lineTo(50, 20); shape.closePath(); break; case "circle": shape = new GeneralPath(new Ellipse2D.Float(38, 8, 24, 24)); break; case "square": shape = new GeneralPath(new Rectangle2D.Float(40, 10, 20, 20)); break; case "zigzag": shape.moveTo(50, 0); shape.lineTo(35, 15); shape.lineTo(45, 25); shape.lineTo(35, 35); shape.lineTo(50, 50); shape.lineTo(65, 35); shape.lineTo(55, 25); shape.lineTo(65, 15); shape.lineTo(50, 0); shape.closePath(); break; case "arrow": shape.moveTo(40, 0); shape.lineTo(60, 0); shape.lineTo(60, 40); shape.lineTo(50, 50); shape.lineTo(40, 40); shape.closePath(); break; default: //System.out.println("Translated unknown pattern to arrow"); shape.moveTo(40, 0); shape.lineTo(60, 0); shape.lineTo(60, 40); shape.lineTo(50, 50); shape.lineTo(40, 40); break; } //System.out.println("Translate pattern: " + shape); return shape; } }
package yinq.situation.dataModel; /** * Created by YinQ on 2018/11/30. */ public class SleepSituationModel extends SituationModel { private SleepSituationDetModel det; public SleepSituationModel(){ } public SleepSituationDetModel getDet() { return det; } public void setDet(SleepSituationDetModel det) { this.det = det; } }
package com.xianzaishi.wms.tmscore.vo; import java.io.Serializable; import java.util.Date; import com.xianzaishi.wms.common.vo.QueryVO; public class WaveQueryVO extends QueryVO implements Serializable { private Long agencyId = null; private Short single = null; private Long operator = null; private Integer pickup = null; private Long areaId = null; private Date createTime = null; private Date finishTime = null; private Integer statu = null; public Long getAgencyId() { return agencyId; } public void setAgencyId(Long agencyId) { this.agencyId = agencyId; } public Short getSingle() { return single; } public void setSingle(Short single) { this.single = single; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getFinishTime() { return finishTime; } public void setFinishTime(Date finishTime) { this.finishTime = finishTime; } public Integer getStatu() { return statu; } public void setStatu(Integer statu) { this.statu = statu; } public Long getOperator() { return operator; } public void setOperator(Long operator) { this.operator = operator; } public Long getAreaId() { return areaId; } public void setAreaId(Long areaId) { this.areaId = areaId; } public Integer getPickup() { return pickup; } public void setPickup(Integer pickup) { this.pickup = pickup; } }
package edu.lewis.ap.newbold.griffin; import edu.jenks.dist.lewis.ap.*; public class HighSchoolClass extends AbstractHighSchoolClass{ public HighSchoolClass(Student[] students){ super(students); } public Student[] getValedictorian(){ double highestGPA = 0; int arrayPosition = 0; for(int i = 0; i < students.length; i++){ if(students[i].getGpa() > highestGPA){ highestGPA = students[i].getGpa(); } } int numOfValedictorians = checkGPA(highestGPA); Student[] valedictorian = new Student[numOfValedictorians]; for(int k = 0; k < students.length; k++){ double GPA = students[k].getGpa(); if(GPA == highestGPA){ valedictorian[arrayPosition] = students[k]; arrayPosition++; } } return valedictorian; } public double getHonorsPercent(){ double honorsStudents = 0; for(int g = 0; g < students.length; g++){ boolean honors = students[g].isHonors(); if(honors){ honorsStudents++; } } return ((honorsStudents/students.length)*100); } public double graduateWithHonorsPercent(){ double studentsWithHonors = 0; for(int i = 0; i < students.length; i++){ double gpa = students[i].getGpa(); if(gpa >= HONORS_GPA){ studentsWithHonors++; } } double percent = ((studentsWithHonors/students.length)*100); return percent; } public double graduateWithHighestHonorsPercent(){ double studentsWithHighestHonors = 0; for(int i = 0; i < students.length; i++){ double gpa = students[i].getGpa(); if(gpa >= HIGHEST_HONORS_GPA){ studentsWithHighestHonors++; } } double percent = ((studentsWithHighestHonors/students.length)*100); return percent; } public Student[] getHonorsStudents(){ int arrayPosition = 0; int numOfHonors = 0; for(int a = 0; a < students.length; a++){ boolean honors = students[a].isHonors(); if(honors){ numOfHonors++; } } Student[] honors = new Student[numOfHonors]; for(int y = 0; y < students.length; y++){ boolean hon = students[y].isHonors(); if(hon){ honors[arrayPosition] = students[y]; arrayPosition++; } } return honors; } private int checkGPA(double gpa){ int num = 0; for(int j = 0; j < students.length; j++){ double GPA = students[j].getGpa(); if(GPA == gpa){ num++; } } return num; } }
package com.mindtree.spring.dao; import java.util.List; import com.mindtree.spring.entity.Project; public interface ProjectDAO { public List<Project> getProjectData(); }
package com.beike.action.booking; import java.io.IOException; import java.text.ParseException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.beike.action.user.BaseUserAction; import com.beike.entity.booking.BookingBranch; import com.beike.entity.booking.BookingFormVO; import com.beike.entity.booking.BookingInfo; import com.beike.entity.user.User; import com.beike.service.booking.BookingService; import com.beike.util.DateUtils; import com.beike.util.StringUtils; import com.beike.util.json.JSONArray; import com.beike.util.json.JSONException; import com.beike.util.json.JSONObject; import com.beike.util.singletonlogin.SingletonLoginUtils; @Controller("bookingAction") public class BookingAction extends BaseUserAction { @Autowired private BookingService bookingService; static final Log logger = LogFactory.getLog(BookingAction.class); static final String HANDLE_RESULT = "handleresult"; static final String HANDLE_SUCCESS = "success"; static final String HANDLE_FAIL = "fail"; /** * 批量预订提交 * janwen * @param request * @param response * @throws IOException * @throws ParseException * @throws JSONException * */ @RequestMapping(value="/booking/saveBatchBooking.do",method = RequestMethod.POST) public void saveBatchBooking(HttpServletRequest request,HttpServletResponse response) throws IOException, ParseException, JSONException{ User user = SingletonLoginUtils.getMemcacheUser(request); JSONObject response_json = new JSONObject(); String error_message = "预订失败,请检查订单信息!"; String trxorder_id = request.getParameter("trxorder_id"); String goodsid = request.getParameter("goodsid"); String tobook = request.getParameter("tobook"); String branchid = request.getParameter("branchid"); String person = request.getParameter("person"); String phone = request.getParameter("phone"); String scheduled_consumption_datetime = request.getParameter("scheduled_consumption_datetime"); String message = request.getParameter("message"); Map<String,String> results = new HashMap<String, String>(); response.setContentType("application/json;charset=UTF-8"); response.setCharacterEncoding("utf-8"); try { message = StringUtils.neNullAndDigital(message, true,1000) ? message : ""; if(user != null && StringUtils.neNullAndDigital(trxorder_id, false,null) && StringUtils.neNullAndDigital(goodsid, false,null) && StringUtils.neNullAndDigital(tobook, false,null) && StringUtils.neNullAndDigital(branchid, false,null) && StringUtils.neNullAndDigital(person, true,15) && StringUtils.neNullAndDigital(phone, false,11) && StringUtils.neNullAndDigital(scheduled_consumption_datetime, true,29) && DateUtils.isAfterToday(scheduled_consumption_datetime)){ BookingFormVO bfv = new BookingFormVO(); bfv.setTobook(new Integer(tobook)); bfv.setBranch_id(new Long(branchid)); bfv.setMessage(message); bfv.setPhone(phone); bfv.setPerson(person); bfv.setGoods_id(new Long(goodsid)); bfv.setTrxorder_id(new Long(trxorder_id)); bfv.setScheduled_consumption_datetime(scheduled_consumption_datetime); bfv.setCreateucid(user.getId()); List<Long> trxgoods_ids = bookingService.getOrdersByTrxorderidAndGoodsid(user.getId(),new Long(trxorder_id), new Long(goodsid)); if(bookingService.isValidOrder(trxgoods_ids, bfv)){ results = bookingService.saveBooking(trxgoods_ids, bfv); response_json.put("response_json", results.get("result_message").toString()); response_json.put(HANDLE_RESULT, results.get("handle_result").toString()); bookingService.sendSMS(trxgoods_ids); }else{ response_json.put("response_json", error_message); response_json.put(HANDLE_RESULT, HANDLE_FAIL); } }else{ response_json.put("response_json", error_message); response_json.put(HANDLE_RESULT, HANDLE_FAIL); } response.getWriter().write(response_json.toString()); } catch (Exception e) { e.printStackTrace(); response_json.put("response_json", error_message); response_json.put(HANDLE_RESULT, HANDLE_FAIL); response.getWriter().write(response_json.toString()); } } /** * 单个预订申请提交 * janwen * @param request * @param response * @throws IOException * @throws ParseException * @throws JSONException * */ @RequestMapping(value="/booking/saveBooking.do",method = RequestMethod.POST) public void saveBooking(HttpServletRequest request,HttpServletResponse response) throws IOException, ParseException, JSONException{ User user = SingletonLoginUtils.getMemcacheUser(request); JSONObject response_json = new JSONObject(); String trxgoods_id = request.getParameter("trxgoods_id"); String goodsid = request.getParameter("goodsid"); String branchid = request.getParameter("branchid"); String person = request.getParameter("person"); String phone = request.getParameter("phone"); String scheduled_consumption_datetime = request.getParameter("scheduled_consumption_datetime"); String message = request.getParameter("message"); String error_message = "预订失败,请检查订单信息!"; response.setContentType("application/json;charset=UTF-8"); response.setCharacterEncoding("utf-8"); Map<String,String> results = new HashMap<String, String>(); try { message = StringUtils.neNullAndDigital(message, true,1000) ? message : ""; if(user != null && StringUtils.neNullAndDigital(trxgoods_id, false,null) && StringUtils.neNullAndDigital(goodsid, false,null) && StringUtils.neNullAndDigital(branchid, false,null) && StringUtils.neNullAndDigital(person, true,15) && StringUtils.neNullAndDigital(phone, false,11) && StringUtils.neNullAndDigital(scheduled_consumption_datetime, true,20) && DateUtils.isAfterToday(scheduled_consumption_datetime)){ BookingFormVO bfv = new BookingFormVO(); bfv.setGoods_id(new Long(goodsid)); bfv.setBranch_id(new Long(branchid)); bfv.setMessage(message); bfv.setPhone(phone); bfv.setCreateucid(user.getId()); bfv.setPerson(person); bfv.setScheduled_consumption_datetime(scheduled_consumption_datetime); List<Long> trxgoods_ids = new ArrayList<Long>(); trxgoods_ids.add(new Long(trxgoods_id)); if(bookingService.isValidOrder(trxgoods_ids, bfv)){ results = bookingService.saveBooking(trxgoods_ids, bfv); response_json.put(HANDLE_RESULT, results.get("handle_result").toString()); response_json.put("response_json", results.get("result_message").toString()); bookingService.sendSMS(trxgoods_ids); }else{ response_json.put("response_json", error_message); response_json.put(HANDLE_RESULT, HANDLE_FAIL); } }else{ response_json.put("response_json", error_message); response_json.put(HANDLE_RESULT, HANDLE_FAIL); } response.getWriter().write(response_json.toString()); } catch (NumberFormatException e) { e.printStackTrace(); response_json.put("response_json", error_message); response_json.put(HANDLE_RESULT, HANDLE_FAIL); response.getWriter().write(response_json.toString()); } } /** * 批量预订填写申请单 * janwen * @param request * @param response * @throws IOException * @throws JSONException * */ @RequestMapping(value="/booking/showBookingformBatch.do",method = RequestMethod.POST) public void showBookingformBatch(HttpServletRequest request,HttpServletResponse response) throws IOException, JSONException{ User user = SingletonLoginUtils.getMemcacheUser(request); JSONObject response_json = new JSONObject(); String trxorder_id = request.getParameter("trxorder_id"); String goodsid = request.getParameter("goodsid"); response.setContentType("application/json;charset=UTF-8"); response.setCharacterEncoding("utf-8"); try { if (user != null && StringUtils.neNullAndDigital(trxorder_id, false,null) && StringUtils.neNullAndDigital(goodsid, false,null)) { List<Long> trxgoods_ids = bookingService .getOrdersByTrxorderidAndGoodsid(user.getId(),new Long(trxorder_id), new Long(goodsid)); BookingFormVO bfv = new BookingFormVO(); bfv.setCreateucid(user.getId()); if (bookingService.isValidOrder(trxgoods_ids, bfv)) { Map g = bookingService.getBookingGoods(new Long(goodsid)); List<BookingBranch> branches = bookingService.getBranchesInfoByGoodsid(new Long(goodsid)); if(branches != null && branches.size() > 0){ response_json.put("goodsinfo", new JSONObject(g)); response_json.put("branches", new JSONArray(convert2JsonObject(branches))); response_json.put("orderTotal", trxgoods_ids.size()); response_json.put(HANDLE_RESULT, HANDLE_SUCCESS); }else{ response_json.put(HANDLE_RESULT, HANDLE_FAIL); } }else{ response_json.put(HANDLE_RESULT, HANDLE_FAIL); } }else{ response_json.put(HANDLE_RESULT, HANDLE_FAIL); } response.getWriter().write(response_json.toString()); } catch (Exception e) { e.printStackTrace(); response_json.put(HANDLE_RESULT, HANDLE_FAIL); response.getWriter().write(response_json.toString()); } } private static List<JSONObject> convert2JsonObject(List<BookingBranch> branches){ List<JSONObject> jsonObjects = new ArrayList<JSONObject>(); for(int i=0;i<branches.size();i++){ jsonObjects.add(new JSONObject(branches.get(i))); } return jsonObjects; } /** * 单个预订填写申请单 * janwen * @param request * @param response * @throws IOException * @throws JSONException * */ @RequestMapping(value="/booking/showBookingform.do",method = RequestMethod.POST) public void showBookingform(HttpServletRequest request,HttpServletResponse response) throws IOException, JSONException{ User user = SingletonLoginUtils.getMemcacheUser(request); JSONObject response_json = new JSONObject(); String trxgoods_id = request.getParameter("trxgoods_id"); String goodsid = request.getParameter("goodsid"); response.setContentType("application/json;charset=UTF-8"); response.setCharacterEncoding("utf-8"); try { if (user != null && StringUtils.neNullAndDigital(trxgoods_id, false,null) && StringUtils.neNullAndDigital(goodsid, false,null)) { List<Long> trxgoods_ids = new ArrayList<Long>(); trxgoods_ids.add(new Long(trxgoods_id)); BookingFormVO bfv = new BookingFormVO(); bfv.setCreateucid(user.getId()); if (bookingService.isValidOrder(trxgoods_ids, bfv)) { Map g = bookingService.getBookingGoods(new Long(goodsid)); List<BookingBranch> branches = bookingService.getBranchesInfoByGoodsid(new Long(goodsid)); if(branches != null && branches.size() > 0){ response_json.put("goodsinfo", new JSONObject(g)); response_json.put("branches", new JSONArray(convert2JsonObject(branches))); response_json.put(HANDLE_RESULT, HANDLE_SUCCESS); }else{ response_json.put(HANDLE_RESULT, HANDLE_FAIL); } }else{ response_json.put(HANDLE_RESULT, HANDLE_FAIL); } }else{ response_json.put(HANDLE_RESULT, HANDLE_FAIL); } response.getWriter().write(response_json.toString()); } catch (Exception e) { e.printStackTrace(); response_json.put(HANDLE_RESULT, HANDLE_FAIL); response.getWriter().write(response_json.toString()); } } /** * 取消预订 * janwen * @param request * @param response * @throws IOException * @throws JSONException * */ @RequestMapping(value="/booking/cacelBooking.do",method = RequestMethod.POST) public void cancelBooking(HttpServletRequest request,HttpServletResponse response) throws IOException, JSONException{ JSONObject json = new JSONObject(); String bookingid = request.getParameter("bookingid"); User user = SingletonLoginUtils.getMemcacheUser(request); response.setContentType("application/json;charset=UTF-8"); response.setCharacterEncoding("utf-8"); try { if(user != null && StringUtils.neNullAndDigital(bookingid, false,null)){ BookingInfo bi = bookingService.getBookingRecordByID(new Long(bookingid),user.getId()); if(bi != null && bookingService.cancelBooking(bi)){ json.put(HANDLE_RESULT, HANDLE_SUCCESS); }else{ json.put(HANDLE_RESULT, HANDLE_FAIL); } }else{ json.put(HANDLE_RESULT,HANDLE_FAIL); } response.getWriter().write(json.toString()); } catch (Exception e) { e.printStackTrace(); json.put(HANDLE_RESULT,HANDLE_FAIL); response.getWriter().write(json.toString()); } } @RequestMapping(value="/booking/getBookingRecord.do",method = RequestMethod.POST) public void getBookingRecord(HttpServletRequest request,HttpServletResponse response) throws IOException, JSONException{ String bookingid = request.getParameter("bookingid"); JSONObject json = new JSONObject(); User user = SingletonLoginUtils.getMemcacheUser(request); response.setContentType("application/json;charset=UTF-8"); response.setCharacterEncoding("utf-8"); try { if(user != null && StringUtils.neNullAndDigital(bookingid, false,null)){ BookingInfo bi = bookingService.getBookingRecordByID(new Long(bookingid),user.getId()); if(bi != null){ List<BookingBranch> branches = bookingService.getBranchesInfoByGoodsid(bi.getGoods_id()); json.put("branches",new JSONArray(convert2JsonObject(branches))); json.put("bookingInfo", new JSONObject(bi)); json.put(HANDLE_RESULT,HANDLE_SUCCESS); }else{ json.put(HANDLE_RESULT,HANDLE_FAIL); } }else{ json.put(HANDLE_RESULT,HANDLE_FAIL); } response.getWriter().write(json.toString()); } catch (Exception e) { e.printStackTrace(); json.put(HANDLE_RESULT,HANDLE_FAIL); response.getWriter().write(json.toString()); } } @RequestMapping(value="/booking/showTip.do",method = RequestMethod.POST) public void showTip(HttpServletRequest request,HttpServletResponse response) throws IOException, JSONException{ String bookingid = request.getParameter("bookingid"); JSONObject json = new JSONObject(); User user = SingletonLoginUtils.getMemcacheUser(request); response.setContentType("application/json;charset=UTF-8"); response.setCharacterEncoding("utf-8"); try { if(user != null && StringUtils.neNullAndDigital(bookingid, false,null)){ BookingInfo bi = bookingService.showTip(new Long(bookingid),user.getId()); if(bi != null){ json.put("bookingInfo", new JSONObject(bi)); json.put(HANDLE_RESULT,HANDLE_SUCCESS); }else{ json.put(HANDLE_RESULT,HANDLE_FAIL); } }else{ json.put(HANDLE_RESULT,HANDLE_FAIL); } response.getWriter().write(json.toString()); } catch (Exception e) { e.printStackTrace(); json.put(HANDLE_RESULT,HANDLE_FAIL); response.getWriter().write(json.toString()); } } /** * 重新预订提交 * janwen * @param request * @param response * @throws IOException * @throws ParseException * @throws JSONException * */ @RequestMapping(value="/booking/reBooking.do",method = RequestMethod.POST) public void reBooking(HttpServletRequest request,HttpServletResponse response) throws IOException, ParseException, JSONException{ User user = SingletonLoginUtils.getMemcacheUser(request); JSONObject response_json = new JSONObject(); String trxgoods_id = request.getParameter("trxgoods_id"); String goodsid = request.getParameter("goodsid"); String branchid = request.getParameter("branchid"); String person = request.getParameter("person"); String phone = request.getParameter("phone"); String bookedid = request.getParameter("bookingid"); String scheduled_consumption_datetime = request.getParameter("scheduled_consumption_datetime"); String message = request.getParameter("message"); response.setContentType("application/json;charset=UTF-8"); response.setCharacterEncoding("utf-8"); String error_message = "预订失败,请检查订单信息!"; Map<String,String> results = new HashMap<String, String>(); try { message = StringUtils.neNullAndDigital(message, true,1000) ? message : ""; if(user != null && StringUtils.neNullAndDigital(trxgoods_id, false,null) && StringUtils.neNullAndDigital(goodsid, false,null) && StringUtils.neNullAndDigital(branchid, false,null) && StringUtils.neNullAndDigital(person, true,15) && StringUtils.neNullAndDigital(phone, false,11) && StringUtils.neNullAndDigital(scheduled_consumption_datetime, true,20) && StringUtils.neNullAndDigital(bookedid, false,null) && DateUtils.isAfterToday(scheduled_consumption_datetime)){ BookingFormVO bfv = new BookingFormVO(); bfv.setBranch_id(new Long(branchid)); bfv.setMessage(message); bfv.setPhone(phone); bfv.setPerson(person); bfv.setCreateucid(user.getId()); bfv.setScheduled_consumption_datetime(scheduled_consumption_datetime); List<Long> trxgoods_ids = new ArrayList<Long>(); trxgoods_ids.add(new Long(trxgoods_id)); if(bookingService.isValidOrder(trxgoods_ids, bfv)){ BookingInfo bi = bookingService.getBookingRecordByID(new Long(bookedid), user.getId()); if(bi != null){ bi.setCreateucid(user.getId()); bfv.setGoods_id(bi.getGoods_id()); if(bookingService.reBooking(bi)){ results = bookingService.saveBooking(trxgoods_ids, bfv); response_json.put(HANDLE_RESULT, results.get("handle_result").toString()); response_json.put("response_json", results.get("result_message").toString()) ; bookingService.sendSMS(trxgoods_ids); }else{ response_json.put(HANDLE_RESULT, HANDLE_FAIL); response_json.put("response_json", error_message) ; } }else{ response_json.put(HANDLE_RESULT, HANDLE_FAIL); response_json.put("response_json", error_message) ; } }else{ response_json.put("response_json", error_message); response_json.put(HANDLE_RESULT, HANDLE_FAIL); } }else{ response_json.put("response_json", error_message); response_json.put(HANDLE_RESULT, HANDLE_FAIL); } response.getWriter().write(response_json.toString()); } catch (NumberFormatException e) { e.printStackTrace(); response_json.put("response_json", error_message); response_json.put(HANDLE_RESULT, HANDLE_FAIL); response.getWriter().write(response_json.toString()); } } }
public class NestedTc { public static void main(String[] args) { try // Nested try block { System.out.println("Nested try-catch"); try { int a = 20, b = 0, c; c = a/b; System.out.println(c); } catch(ArithmeticException e) { System.out.println("Division by 0 is not defined"); } try { int arr[] = {1,2,3,4,5}; System.out.println(arr[10]); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Index doesnot exists"); } } catch(Exception e) { System.out.println("Exception occured"); } } }
package com.class3601.social.models; import com.class3601.social.common.Messages; public class GameOwner { private String gameownerIdPrimarKey; private String username; private String gametitle; public GameOwner() { setUsername(Messages.UNKNOWN); setGametitle(Messages.UNKNOWN); } public void updateFromGameOwner(GameOwner gameowner) { setGameOwnerIdPrimarKey(gameowner.getGameOwnerIdPrimarKey()); setUsername(gameowner.getUsername()); setGametitle(gameowner.getGametitle()); } public GameOwner copy() { GameOwner gameowner = new GameOwner(); gameowner.updateFromGameOwner(this); return gameowner; } public boolean equals(GameOwner gameowner) { return getGameOwnerIdPrimarKey().equals(gameowner.getGameOwnerIdPrimarKey()); } public String getGameOwnerIdPrimarKey() { return gameownerIdPrimarKey; } public void setGameOwnerIdPrimarKey(String gameownerIdPrimarKey) { this.gameownerIdPrimarKey = gameownerIdPrimarKey; } public String getGametitle() { return gametitle; } public void setGametitle(String gametitle) { this.gametitle = gametitle; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } }
/* * 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 servlet; import Model.StAmFileList; import Model.StAssignmentFile; import com.crocodoc.Crocodoc; import com.crocodoc.CrocodocException; import com.crocodoc.CrocodocSession; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * * @author Orarmor */ public class anotherAmFile extends HttpServlet { /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession ss = request.getSession(false); String uuid = request.getParameter("uuid"); String safv_id = request.getParameter("safv_id"); String apiToken = "mGye5pCBUTgkhI7Zl0QL3oPJ"; Crocodoc.setApiToken(apiToken); System.out.print("Creating... "); String sessionKey = null; try { Map<String, Object> params = new HashMap<String, Object>(); params.put("isDownloadable", true); sessionKey = CrocodocSession.create(uuid,params); System.out.println("success :)"); System.out.println(" The session key is " + sessionKey + "."); } catch (CrocodocException e) { System.out.println("failed :("); System.out.println(" Error Code: " + e.getCode()); System.out.println(" Error Message: " + e.getMessage()); } System.out.println(sessionKey); ss.setAttribute("sessionKey", sessionKey); request.setAttribute("safv_id", safv_id); //update session StAssignmentFile stF = (StAssignmentFile) ss.getAttribute("sa"); stF = StAssignmentFile.getStAm(stF.getSt_am_id()); StAmFileList curSafv = StAmFileList.getSafvByListIdSafv(Integer.parseInt(safv_id), stF.getList_id()); ss.setAttribute("sa", stF); ss.setAttribute("curSafv", curSafv); getServletContext().getRequestDispatcher("/CheckAssignment.jsp?tab=AllAssignment").forward(request, response); } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
package com.example.HeavyArtillery; import android.content.Context; import android.content.DialogInterface; import android.view.View; /** * Created by Tim on 20-2-14. * */ public class OnClickListenerWithString implements View.OnClickListener { String variable; Context context; View v; public OnClickListenerWithString(String variable,View v){//Context context) { this.variable = variable; //this.context = context; this.v=v; } public OnClickListenerWithString(String variable){//Context context) { this.variable = variable; } @Override public void onClick(View v) { //read your lovely variable } }
import java.util.ArrayList; import java.util.Iterator; public class MyQueue<T> implements Iterable{ private static int count = 0; public ArrayList<T> list; /*** * Constructs a new queue */ public MyQueue() { list = (ArrayList<T>) new ArrayList<T>(); } /*** * Checks if the queue is empty * @return - returns true or false */ public final boolean isEmpty() { // TODO Auto-generated method stub //Check if the Queue is empty if (count == 0) { return true; } return false; } /*** * Return item at the beginning of the queue * @return - returns the item removed */ public final T dequeue() { // TODO Auto-generated method stub T itemRemoved = null; if (count != 0) { //if not empty decrement count and get removed item itemRemoved = this.list.remove(0); count--; } else { System.out.println("Cannot dequeue while MyQueue is empty"); } return itemRemoved; } /*** * Adds value to the end of our queue * @param item - item to add to our queue */ public final void enqueue(final T item) { //if not add it to end this.list.add(item); count++; } /*** * Create a string representation for queue */ public final String toString() { String output = ""; //Create a string representation for queue for (int i = 0; i < this.list.size(); i++) { output += this.list.get(i) + " "; } return output; } @Override public Iterator iterator() { return list.iterator(); } }
package com.gsccs.sme.plat.svg.dao; import com.gsccs.sme.plat.svg.model.SorderT; import com.gsccs.sme.plat.svg.model.SorderTExample; import java.util.List; import org.apache.ibatis.annotations.Param; public interface SorderTMapper { int countByExample(SorderTExample example); int deleteByExample(SorderTExample example); int deleteByPrimaryKey(String id); int insert(SorderT record); List<SorderT> selectByExample(SorderTExample example); List<SorderT> selectPageByExample(SorderTExample example); SorderT selectByPrimaryKey(String id); int updateByPrimaryKey(SorderT record); }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package cput.codez.angorora.eventstar.model; /** * * @author allen */ public final class Transport { private String id; private String eventId; private String providerName; private String providerContId; private String description; private Transport() { } private Transport(Builder build) { this.id=build.id; this.providerContId=build.providerContId; this.eventId=build.eventId; this.providerName=build.providerName; this.description=build.description; } public String getId() { return id; } public String getEventId() { return eventId; } public String getProviderName() { return providerName; } public String getProviderCont() { return providerContId; } public String getDescription() { return description; } public static class Builder{ private String id; private String eventId; private String providerName; private String providerContId; private String description; public Builder(String eventId) { this.eventId=eventId; } public Builder providerContact(String cont){ this.providerContId=cont; return this; } public Builder providername(String provName){ this.providerName=provName; return this; } public Builder descrip(String descrip){ this.description=descrip; return this; } public Transport build(){ return new Transport(this); } public Builder copier(Transport trans){ this.id=trans.id; this.providerContId=trans.providerContId; this.eventId=trans.eventId; this.providerName=trans.providerName; this.description=trans.description; return this; } } @Override public int hashCode() { int hash = 7; hash = 11 * hash + (this.id != null ? this.id.hashCode() : 0); return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Transport other = (Transport) obj; if ((this.id == null) ? (other.id != null) : !this.id.equals(other.id)) { return false; } return true; } }
package edu.cb.gabriel.mitchell; import edu.jenks.dist.cb.*; public class ArrayTester implements TestableArray{ public ArrayTester(){ } public int[] getColumn(int[][] arr2D, int c){ int[] vals = new int[arr2D[0].length + 1]; int index = 0; for (int row = 0; row < arr2D[0].length + 1; row++){ vals[index] = arr2D[row][c]; index++; } return vals; } public boolean hasAllValues(int[] arr1,int[] arr2){ boolean matches = false; int sameCount = 0; int i = 0; for ( int y = 0; y < arr1.length; y++){ for(i = 0; i < arr1.length; i++){ if(arr1[y] == arr2[i]){ sameCount++; } } } if(sameCount == arr1.length){ matches = true; } return matches; } public boolean containsDuplicates(int[] arr){ boolean hasDupe = false; int[] copy = new int[arr.length]; for (int i = 0; i < arr.length; i++){ copy[i] = arr[i]; if (copy[i] != arr[i]){ hasDupe = true; } } return hasDupe; } public boolean isLatin(int[][] square){ boolean answer = false; if( !containsDuplicates(square[0])){ int i = 0; answer = true; for(i = 0; i < square.length; i++){ if (!hasAllValues(square[i],square[0]) || !hasAllValues(square[0], getColumn(square, i))){ answer = false; } } } return answer; } }
package com.example.applligent.clouds; import android.app.Activity; import android.content.Context; import android.support.annotation.NonNull; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import java.util.List; public class ArtistList extends ArrayAdapter<Artist> { private Activity context; private List<Artist> artistList; public ArtistList(Activity context, List<Artist> artistList){ super(context, R.layout.list_view,artistList); this.context=context; this.artistList=artistList; } @NonNull @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = context.getLayoutInflater(); View listViewItem =inflater.inflate(R.layout.list_view,null,true); TextView name=(TextView)listViewItem.findViewById(R.id.name); TextView genre=(TextView)listViewItem.findViewById(R.id.genre); Artist artist = artistList.get(position); name.setText(artist.artistName); genre.setText(artist.artistGenre); return listViewItem; } }
package art4muslim.macbook.rahatydriver.session; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.util.Log; import art4muslim.macbook.rahatydriver.LoginActivity; import art4muslim.macbook.rahatydriver.MainActivity; import java.util.HashMap; public class SessionManager { // access token public static final String KEY_Acesstoken = "access_token"; // User name (make variable public to access from outside) public static final String KEY_NAME = "name"; // Email address (make variable public to access from outside) public static final String KEY_EMAIL = "email"; // Sharedpref file name private static final String PREF_NAME = "aymanPref"; // All Shared Preferences Keys private static final String IS_LOGIN = "IsLoggedIn"; public static final String Key_UserIMAGE="USERIMAGE"; private static final String Key_UserID="ID"; private static final String Key_UserName="NAME"; private static final String Key_UserSESSION="SESSION"; public static final String Key_UserPhone="USERPHONE"; private static final String Key_UserEmail="USEREMAIL"; private static final String Key_UserMAPX="Key_UserMAPX"; private static final String Key_UserMAPY="Key_UserMAPY"; private static final String Key_UserCITY_ID="USERCITYID"; private static final String Key_UserCITY_NAME="USERCITYNAME"; private static final String Key_LANGUAGE="LANGUAGE"; private static final String Key_ServiceID="ID_SERVICE"; private static final String Key_cityId="CityId"; private static final String Key_Currency="Currency"; // Shared Preferences SharedPreferences pref; // Editor for Shared preferences Editor editor; // Context Context _context; // Shared pref mode int PRIVATE_MODE = 0; // Constructor public SessionManager(Context context) { this._context = context; pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE); editor = pref.edit(); } public void saveAccessToken(String accessToken){ editor.putString(KEY_Acesstoken,accessToken); editor.commit(); } public String getAccessToken() { return pref.getString(KEY_Acesstoken, null); } /** * Create login session */ public void saveLoginState(boolean isLogin){ editor.putBoolean(IS_LOGIN, isLogin); editor.commit(); } public void createLoginSession(int id,String name, String phone, String phoneHome,String thumbnail, String status) { // Storing login value as TRUE // storing access token in pref editor.putInt(Key_UserID, id); Log.v("id", ""+id); // Storing name in pref editor.putString(KEY_NAME, name); // Storing phone in pref editor.putString(Key_UserPhone, phone); Log.v("key phone", phone); // Storing email in pref // editor.putString(Key_UserPhoneHome, phoneHome); // Log.v("key phoneHome", phoneHome); // Storing email in pref editor.putString(Key_UserIMAGE, thumbnail); Log.v("key thumbnail", thumbnail); // Storing status in pref // editor.putString(Key_UserSTATUS, status); Log.v("key status", status); // commit changes editor.commit(); } // to get user id public void saveUserId(int userId){ editor.putInt(Key_UserID,userId); editor.commit(); } // to get user id public void saveUserName(String userName){ editor.putString(Key_UserName,userName); editor.commit(); } public void saveUserSESSION(String userSession){ editor.putString(Key_UserSESSION,userSession); editor.commit(); } public void saveUser_phone(String user_phone){ editor.putString(Key_UserPhone,user_phone); editor.commit(); } public void saveUser_city_id(String user_city){ editor.putString(Key_UserCITY_ID,user_city); editor.commit(); } public void saveUser_city_name(String user_cityName){ editor.putString(Key_UserCITY_NAME,user_cityName); editor.commit(); } public void saveUserLanguage(String lng){ editor.putString(Key_LANGUAGE,lng); editor.commit(); } public void saveServiceId(int serviceId){ editor.putInt(Key_ServiceID,serviceId); editor.commit(); } public void savecityid(int cityid){ editor.putInt(Key_cityId,cityid); editor.commit(); } public void saveCurrencyCountry(String cityid){ editor.putString(Key_Currency,cityid); editor.commit(); } public void SaveDriverIdentityImage(String DriverIdentityImage){ editor.putString("DriverIdentityImage",DriverIdentityImage); editor.commit(); } public void SaveDriverLicence(String DriverLicence){ editor.putString("DriverLicence",DriverLicence); editor.commit(); } public void SaveCarLicensce(String CarLicensce){ editor.putString("CarLicensce",CarLicensce); editor.commit(); } public void SaveDriverPersonalImageID(String DriverPersonalImageID){ editor.putString("DriverPersonalImageID",DriverPersonalImageID); editor.commit(); } public void SaveCarFrontImage(String CarFrontImage){ editor.putString("CarFrontImage",CarFrontImage); editor.commit(); } public void SaveCarBackImage(String CarBackImage){ editor.putString("CarBackImage",CarBackImage); editor.commit(); } /**to retrive * Gson gson = new Gson(); String json = mPrefs.getString("MyObject", ""); MyObject obj = gson.fromJson(json, MyObject.class); * **/ public void SaveDriverIbfo(String myobject, String json){ editor.putString(myobject, json); editor.commit(); } public String getDriverInfo( String myobject){ return pref.getString(myobject, null); } public void DeleteImages(){ editor.remove("DriverIdentityImage"); editor.remove("DriverLicence"); editor.remove("CarLicensce"); editor.remove("DriverPersonalImageID"); editor.remove("CarFrontImage"); editor.remove("CarBackImage"); editor.remove("DriverPersonalImageID"); editor.commit(); } /** * Get stored session data */ public HashMap<String, String > getUserDetails() { HashMap<String, String> user = new HashMap<String, String>(); //access token user.put(KEY_Acesstoken, pref.getString(KEY_Acesstoken, null)); // Log.v("Key_UserID", user.put(Key_UserID,pref.getString(Key_UserID,null))); // user name user.put(KEY_NAME, pref.getString(KEY_NAME, null)); user.put(Key_UserPhone, pref.getString(Key_UserPhone, null)); //city id user.put(Key_cityId, String.valueOf(pref.getInt(Key_cityId,0))); user.put("DriverIdentityImage",pref.getString("DriverIdentityImage",null)); user.put("DriverLicence",pref.getString("DriverLicence",null)); user.put("CarLicensce",pref.getString("CarLicensce",null)); user.put("DriverPersonalImageID",pref.getString("DriverPersonalImageID",null)); user.put("CarFrontImage",pref.getString("CarFrontImage",null)); user.put("CarBackImage",pref.getString("CarBackImage",null)); // return user return user; } /** * Check login method wil check user login status * If false it will redirect user to login page * Else won't do anything */ public void checkLogin() { // Check login status if (this.isLoggedIn()) { // user is logged in redirect him to main Activity Intent i = new Intent(_context, MainActivity.class); // Closing all the Activities // i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // Add new Flag to start new Activity i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // Staring Login Activity _context.startActivity(i); // System.exit(0); } } public HashMap<String ,Integer> getUserId(){ HashMap<String, Integer> usrId = new HashMap<String, Integer>(); // customer or user id usrId.put(Key_UserID, pref.getInt(Key_UserID,0)); return usrId; } public String getUserName(){ // HashMap<String, String> usrId = new HashMap<String, String>(); // customer or user id // usrId.put(Key_Currency, pref.getString(Key_Currency)); return pref.getString(Key_UserName,""); } public String getUserSESSION(){ // HashMap<String, String> usrId = new HashMap<String, String>(); // customer or user id // usrId.put(Key_Currency, pref.getString(Key_Currency)); return pref.getString(Key_UserSESSION,""); } public String getUserPhone(){ // HashMap<String, String> usrId = new HashMap<String, String>(); // customer or user id // usrId.put(Key_Currency, pref.getString(Key_Currency)); return pref.getString(Key_UserPhone,""); } public String getUserCityId(){ // HashMap<String, String> usrId = new HashMap<String, String>(); // customer or user id // usrId.put(Key_Currency, pref.getString(Key_Currency)); return pref.getString(Key_UserCITY_ID,""); } public String getKey_UserCITY_NAME(){ // HashMap<String, String> usrId = new HashMap<String, String>(); // customer or user id // usrId.put(Key_Currency, pref.getString(Key_Currency)); return pref.getString(Key_UserCITY_NAME,""); } public HashMap<String ,Integer> getServiceId(){ HashMap<String, Integer> usrId = new HashMap<String, Integer>(); // customer or user id usrId.put(Key_ServiceID, pref.getInt(Key_ServiceID,0)); return usrId; } public String getKey_LANGUAGE(){ // HashMap<String, String> usrId = new HashMap<String, String>(); // customer or user id // usrId.put(Key_Currency, pref.getString(Key_Currency)); return pref.getString(Key_LANGUAGE,"ar"); } /** * Clear session details */ public void logoutUser() { // Clearing all data from Shared Preferences editor.clear(); editor.commit(); // After logout redirect user to Loing Activity Intent i = new Intent(_context, LoginActivity.class); // Closing all the Activities i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // Add new Flag to start new Activity i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // Staring Login Activity _context.startActivity(i); } /** * Quick check for login **/ // Get Login State public boolean isLoggedIn() { return pref.getBoolean(IS_LOGIN, false); } public void saveUser_email(String user_email) { editor.putString(Key_UserEmail,user_email); editor.commit(); } public String getUserEmail(){ return pref.getString(Key_UserEmail,"ar"); } public void saveUser_mapx(String user_mapx) { editor.putString(Key_UserMAPX,user_mapx); editor.commit(); } public String getUserMapx(){ return pref.getString(Key_UserMAPX,"0.0"); } public void saveUser_mapy(String user_mapy) { editor.putString(Key_UserMAPY,user_mapy); editor.commit(); } public String getUserMapy(){ return pref.getString(Key_UserMAPY,"0.0"); } }
import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Q118_PascalsTriangle { // Method 1 1ms 95.26% public List<List<Integer>> generate(int numRows) { List<List<Integer>> res = new ArrayList<>(); if (numRows == 0) { return res; } res.add(Arrays.asList(1)); for (int i = 1; i < numRows ; i++) { List<Integer> subList = new ArrayList<>(); List<Integer> preList = res.get(i - 1); for (int j = 0; j <= i; j++) { if (j == 0 || j == i) { subList.add(1); } else { subList.add(preList.get(j - 1) + preList.get(j)); } } res.add(subList); } return res; } }
package cn.edu.cqut.controller; import cn.edu.cqut.entity.Customer; import cn.edu.cqut.service.ICustomerService; import cn.edu.cqut.util.CrmResult; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import springfox.documentation.annotations.ApiIgnore; import java.util.Arrays; import java.util.List; import java.util.UUID; /** * <p> * 前端控制器 * </p> * * @author HQYJ * @since 2020-06-03 */ @RestController @RequestMapping("/customer") @CrossOrigin @Api(tags = "客户管理") public class CustomerController { private final ICustomerService customerService; @Autowired public CustomerController(ICustomerService customerService) { this.customerService = customerService; } @ApiOperation(value = "分页返回客户信息12456", notes = "分页查询客户信息,默认返回第一页,每页10行。还可以根据cusName模糊查询") @RequestMapping(value = "/customers", method = RequestMethod.POST) public CrmResult<Customer> getAllCustomer( @ApiParam(value = "要查询的页码", required = true) @RequestParam(defaultValue = "1") Integer page, //page请求的页码,默认为1 @ApiParam(value = "每页的行数", required = true) @RequestParam(defaultValue = "10") Integer limit,//limit每页的行数,默认为10 Customer customer) { QueryWrapper<Customer> qw = new QueryWrapper<>(); if (customer.getCusName() != null) { qw.like("cusName", customer.getCusName()); //第一个参数是字段名 } Page<Customer> pageCustomer = customerService.page( new Page<>(page, limit), qw); CrmResult<Customer> ret = new CrmResult<>(); ret.setCode(0); ret.setMsg(""); ret.setCount(pageCustomer.getTotal());//表里的记录总数 ret.setData(pageCustomer.getRecords()); //这页的数据列表 return ret; } @ApiIgnore @RequestMapping("/updateCustomer") public CrmResult<Customer> updateCustomer(Customer customer) { customerService.updateById(customer); //根据主键更新表 CrmResult<Customer> ret = new CrmResult<>(); ret.setCode(0); ret.setMsg("更新客户成功"); return ret; } @ApiIgnore @RequestMapping("/addCustomer") public CrmResult<Customer> addCustomer(Customer customer) { String cfId = UUID.randomUUID().toString().replace("_", "").substring(0, 4);// 随机生成长度为4的字符串 customer.setCusNo(cfId); customerService.save(customer); CrmResult<Customer> ret = new CrmResult<>(); ret.setCode(0); ret.setMsg("新增客户成功"); return ret; } @ApiIgnore @RequestMapping("/delCustomer") public CrmResult<Customer> delCustomer(String[] ids) { customerService.removeByIds(Arrays.asList(ids)); CrmResult<Customer> ret = new CrmResult<>(); ret.setCode(0); ret.setMsg("删除客户成功"); return ret; } @RequestMapping(value="/getCustomerWithContact",method = RequestMethod.POST) public List<Customer> getCustomerWithContact(){ return customerService.getCustomerWithContact(); } }
package org.usfirst.frc.team1306.robot.subsystems; import org.usfirst.frc.team1306.robot.RobotMap; import edu.wpi.first.wpilibj.Talon; import edu.wpi.first.wpilibj.command.Subsystem; /** * @Intake * * Subsystem that controls our intake mechanism which we use to take in and spit out boulders, * from the robot. All methods in this subsystem are used to accomplish those tasks. * * @author Ethan Dong and Jackson Goth */ public class Intake extends Subsystem { private Talon intakeMotor; //Front motor spinning mechanums private Talon indexerMotor; //Back motor spinning indexer wheels public Intake() { intakeMotor = new Talon(RobotMap.INTAKE_TALON_PORT); indexerMotor = new Talon(RobotMap.INDEXER_TALON_PORT); } /** * This method spin the intake forward and into the robot at positive 50% for the * front intake motor and negative 50% for the inner or back intake motors to * bring the ball into the shooter motors. */ public void spinInward() { intakeMotor.set(0.5); indexerMotor.set(-0.5); } /** * This method does the opposite of spinInward and spits the ball outward at 50% * power */ public void spinOutward() { intakeMotor.set(-0.5); indexerMotor.set(0.5); } /** * This method stops both front and back motor from spinning */ public void stop() { intakeMotor.set(0); indexerMotor.set(0); } @Override public void initDefaultCommand() { } }
package AStarSearch.tiles; import AStarSearch.Tile; import java.awt.*; /** * waterCounter -> quantos tile desse tipo existem no meu mapa * cost -> custo associado ao tile * code -> caracter associado ao tile */ public class WaterTile extends Tile { public static int waterCounter = 0; public static int cost = 180; public static char code = 'W'; public WaterTile() { this.tileCode = code; this.setCost(cost); this.color = new Color(0,154,205); waterCounter++; Tile.tileCodeMap.put(this.tileCode, this); } }
package ua.edu.npu.controller; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.CheckBox; import javafx.scene.control.Label; public class MainController { @FXML Label labelHello; @FXML CheckBox checkboxAgree; @FXML Button agreeButton; private int i = 0; public void buttonPressed(ActionEvent actionEvent) { i++; labelHello.setText("Button hello was pressed " + i + " time(s)"); } public void switchAgree(ActionEvent actionEvent) { if (checkboxAgree.isSelected()) { agreeButton.setDisable(false); } else { agreeButton.setDisable(true); } } }
/* * Created By Liang Shan Guang at 2019/4/22 23:30 * Description : 工厂模式 */ package 第4到27章_23大设计模式.第05章_工厂模式;
/* * MIT License * * Copyright (c) 2019-2022 nerve.network * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ package network.nerve.converter.manager; import com.fasterxml.jackson.core.JsonProcessingException; import io.nuls.base.data.NulsHash; import io.nuls.base.protocol.ProtocolLoader; import io.nuls.core.core.annotation.Autowired; import io.nuls.core.core.annotation.Component; import io.nuls.core.io.IoUtils; import io.nuls.core.log.Log; import io.nuls.core.model.StringUtils; import io.nuls.core.parse.JSONUtils; import io.nuls.core.rockdb.constant.DBErrorCode; import io.nuls.core.rockdb.service.RocksDBService; import io.nuls.core.thread.ThreadUtils; import io.nuls.core.thread.commom.NulsThreadFactory; import network.nerve.converter.config.ConverterConfig; import network.nerve.converter.constant.ConverterConstant; import network.nerve.converter.constant.ConverterDBConstant; import network.nerve.converter.core.api.ConverterCoreApi; import network.nerve.converter.core.heterogeneous.task.HtgConfirmTxTask; import network.nerve.converter.core.heterogeneous.task.HtgRpcAvailableHandlerTask; import network.nerve.converter.core.heterogeneous.task.HtgWaitingTxInvokeDataHandlerTask; import network.nerve.converter.core.thread.handler.SignMessageByzantineHandler; import network.nerve.converter.core.thread.task.CfmTxSubsequentProcessTask; import network.nerve.converter.core.thread.task.ExeProposalProcessTask; import network.nerve.converter.core.thread.task.TxCheckAndCreateProcessTask; import network.nerve.converter.core.thread.task.VirtualBankDirectorBalanceTask; import network.nerve.converter.model.bo.Chain; import network.nerve.converter.model.bo.ConfigBean; import network.nerve.converter.model.bo.HeterogeneousCfg; import network.nerve.converter.model.bo.VirtualBankDirector; import network.nerve.converter.model.po.ExeProposalPO; import network.nerve.converter.model.po.ProposalPO; import network.nerve.converter.model.po.TxSubsequentProcessPO; import network.nerve.converter.storage.*; import network.nerve.converter.utils.ChainLoggerUtil; import network.nerve.converter.utils.VirtualBankUtil; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import static network.nerve.converter.utils.ConverterUtil.addressToLowerCase; /** * 链管理类,负责各条链的初始化,运行,启动,参数维护等 * Chain management class, responsible for the initialization, operation, start-up, parameter maintenance of each chain, etc. * * @author qinyifeng * @date 2018/12/11 */ @Component public class ChainManager { @Autowired private ConfigStorageService configStorageService; @Autowired private VirtualBankStorageService virtualBankStorageService; @Autowired private TxSubsequentProcessStorageService txSubsequentProcessStorageService; @Autowired private ProposalVotingStorageService proposalVotingStorageService; @Autowired private ExeProposalStorageService exeProposalStorageService; @Autowired private PersistentCacheStroageService persistentCacheStroageService; @Autowired private ConverterConfig converterConfig; @Autowired private ConverterCoreApi converterCoreApi; private Map<Integer, Chain> chainMap = new ConcurrentHashMap<>(); /** * 初始化并启动链 * Initialize and start the chain */ public void initChain() throws Exception { Map<Integer, ConfigBean> configMap = configChain(); if (configMap == null || configMap.size() == 0) { return; } for (Map.Entry<Integer, ConfigBean> entry : configMap.entrySet()) { Chain chain = new Chain(); int chainId = entry.getKey(); chain.setConfig(entry.getValue()); initLogger(chain); initTable(chain); loadChainCacheData(chain); loadHeterogeneousCfgJson(chain); createScheduler(chain); chainMap.put(chainId, chain); chain.getLogger().debug("Chain:{} init success..", chainId); ProtocolLoader.load(chainId); if(chainId == converterConfig.getChainId()) { converterCoreApi.setNerveChain(chain); } } } private void initTable(Chain chain) { int chainId = chain.getConfig().getChainId(); try { // 虚拟银行成员表、虚拟银行变化记录对象 RocksDBService.createTable(ConverterDBConstant.DB_VIRTUAL_BANK_PREFIX + chainId); RocksDBService.createTable(ConverterDBConstant.DB_ALL_HISTORY_VIRTUAL_BANK_PREFIX + chainId); // 交易存储 RocksDBService.createTable(ConverterDBConstant.DB_TX_PREFIX + chainId); // 确认虚拟银行变更交易 业务存储表 RocksDBService.createTable(ConverterDBConstant.DB_CFM_VIRTUAL_BANK_PREFIX + chainId); // 确认提现交易状态业务数据表 RocksDBService.createTable(ConverterDBConstant.DB_CONFIRM_WITHDRAWAL_PREFIX + chainId); // 已调用成功异构链组件的交易/已执行的提案等 持久化表 防止2次调用 RocksDBService.createTable(ConverterDBConstant.DB_ASYNC_PROCESSED_PREFIX + chainId); // 等待调用组件的数据表 RocksDBService.createTable(ConverterDBConstant.DB_PENDING_PREFIX + chainId); // 虚拟银行调用异构链, 合并交易时, key与各交易的对应关系 RocksDBService.createTable(ConverterDBConstant.DB_MERGE_COMPONENT_PREFIX + chainId); // 确认补贴手续费交易业务 数据表 RocksDBService.createTable(ConverterDBConstant.DB_DISTRIBUTION_FEE_PREFIX + chainId); // 提案存储表 RocksDBService.createTable(ConverterDBConstant.DB_PROPOSAL_PREFIX + chainId); //投票中的提案 RocksDBService.createTable(ConverterDBConstant.DB_PROPOSAL_VOTING_PREFIX + chainId); // 提案功能投票信息表 RocksDBService.createTable(ConverterDBConstant.DB_VOTE_PREFIX + chainId); // 取消银行资格的地址表 RocksDBService.createTable(ConverterDBConstant.DB_DISQUALIFICATION_PREFIX + chainId); // 充值交易业务数据 RocksDBService.createTable(ConverterDBConstant.DB_RECHARGE_PREFIX + chainId); // 执行提案的交易hash 和 提案的对应关系 RocksDBService.createTable(ConverterDBConstant.DB_PROPOSAL_EXE + chainId); // 等待执行的提案 RocksDBService.createTable(ConverterDBConstant.DB_EXE_PROPOSAL_PENDING_PREFIX + chainId); // 重置虚拟银行异构链 RocksDBService.createTable(ConverterDBConstant.DB_RESET_BANK_PREFIX + chainId); // 异构链地址签名消息存储表 RocksDBService.createTable(ConverterDBConstant.DB_COMPONENT_SIGN + chainId); } catch (Exception e) { if (!DBErrorCode.DB_TABLE_EXIST.equals(e.getMessage())) { chain.getLogger().error(e); } } } /** * 获取加载数据库数据到缓存 * * @param chain */ private void loadChainCacheData(Chain chain) { // 加载虚拟银行成员 Map<String, VirtualBankDirector> mapVirtualBank = virtualBankStorageService.findAll(chain); if (null != mapVirtualBank && !mapVirtualBank.isEmpty()) { VirtualBankUtil.sortDirectorMap(mapVirtualBank); chain.getMapVirtualBank().putAll(mapVirtualBank); } try { chain.getLogger().info("MapVirtualBank : {}", JSONUtils.obj2json(chain.getMapVirtualBank())); } catch (JsonProcessingException e) { chain.getLogger().warn("MapVirtualBank log print error "); } // 加载待调用异构组件的交易 List<TxSubsequentProcessPO> listPending = txSubsequentProcessStorageService.findAll(chain); if (null != listPending && !listPending.isEmpty()) { chain.getPendingTxQueue().addAll(listPending); } try { chain.getLogger().info("PendingTxQueue : {}", JSONUtils.obj2json(chain.getPendingTxQueue())); } catch (JsonProcessingException e) { chain.getLogger().warn("PendingTxQueue log print error "); } // 加载投票中的提案 Map<NulsHash, ProposalPO> votingMap= proposalVotingStorageService.findAll(chain); if (null != votingMap && !votingMap.isEmpty()) { chain.getVotingProposalMap().putAll(votingMap); } try { chain.getLogger().info("VotingProposals : {}", JSONUtils.obj2json(chain.getVotingProposalMap().keySet())); } catch (JsonProcessingException e) { chain.getLogger().warn("VotingProposals log print error "); } // 加载待执行的提案 List<ExeProposalPO> exeProposalPOList = exeProposalStorageService.findAll(chain); chain.getExeProposalQueue().addAll(exeProposalPOList); chain.getLogger().info("exeProposalPOList size : {}", exeProposalPOList.size()); Integer changeBank = persistentCacheStroageService.getCacheState(chain, ConverterDBConstant.EXE_HETEROGENEOUS_CHANGE_BANK_KEY); if(null != changeBank){ chain.getHeterogeneousChangeBankExecuting().set(changeBank == 0 ? false : true); chain.getLogger().info("HeterogeneousChangeBankExecuting : {}", chain.getHeterogeneousChangeBankExecuting().get()); } Integer disqualifyBank = persistentCacheStroageService.getCacheState(chain, ConverterDBConstant.EXE_DISQUALIFY_BANK_PROPOSAL_KEY); if(null != disqualifyBank){ chain.getExeDisqualifyBankProposal().set(disqualifyBank == 0 ? false : true); chain.getLogger().info("ExeDisqualifyBankProposal : {}", chain.getExeDisqualifyBankProposal().get()); } Integer resetBank = persistentCacheStroageService.getCacheState(chain, ConverterDBConstant.RESET_VIRTUALBANK_KEY); if(null != resetBank){ chain.getResetVirtualBank().set(resetBank == 0 ? false : true); chain.getLogger().info("ResetVirtualBank : {}", chain.getResetVirtualBank().get()); } } private void loadHeterogeneousCfgJson(Chain chain) throws Exception { String configJson; if (converterConfig.isHeterogeneousMainNet()) { configJson = IoUtils.read(ConverterConstant.HETEROGENEOUS_MAINNET_CONFIG); } else { configJson = IoUtils.read(ConverterConstant.HETEROGENEOUS_TESTNET_CONFIG); } List<HeterogeneousCfg> list = JSONUtils.json2list(configJson, HeterogeneousCfg.class); String multySignAddressSet = converterConfig.getMultySignAddressSet(); if(StringUtils.isBlank(multySignAddressSet)) { throw new Exception("empty data of multySignAddress set"); } String[] multySignAddressArray = multySignAddressSet.split(","); for(String multySignAddressTemp : multySignAddressArray) { String[] addressInfo = multySignAddressTemp.split(":"); int chainId = Integer.parseInt(addressInfo[0]); String address = addressInfo[1]; for(HeterogeneousCfg cfg : list) { if(cfg.getChainId() == chainId && cfg.getType() == 1) { cfg.setMultySignAddress(addressToLowerCase(address)); break; } } } chain.setListHeterogeneous(list); try { chain.getLogger().info("HeterogeneousCfg : {}", JSONUtils.obj2json(list)); } catch (JsonProcessingException e) { chain.getLogger().warn("HeterogeneousCfg log print error "); } } /** * 停止一条链 * Delete a chain * * @param chainId 链ID/chain id */ public void stopChain(int chainId) { } /** * 读取配置文件创建并初始化链 * Read the configuration file to create and initialize the chain */ private Map<Integer, ConfigBean> configChain() { try { /* 读取数据库链信息配置/Read database chain information configuration */ Map<Integer, ConfigBean> configMap = configStorageService.getList(); /* 如果系统是第一次运行,则本地数据库没有存储链信息,此时需要从配置文件读取主链配置信息 If the system is running for the first time, the local database does not have chain information, and the main chain configuration information needs to be read from the configuration file at this time. */ if (configMap == null || configMap.size() == 0) { ConfigBean configBean = converterConfig; if (configBean == null) { return null; } configStorageService.save(configBean, configBean.getChainId()); configMap.put(configBean.getChainId(), configBean); } return configMap; } catch (Exception e) { Log.error(e); return null; } } public void createScheduler(Chain chain) { ScheduledThreadPoolExecutor collectorExecutor = ThreadUtils.createScheduledThreadPool(1, new NulsThreadFactory(ConverterConstant.CV_PENDING_THREAD)); collectorExecutor.scheduleWithFixedDelay(new CfmTxSubsequentProcessTask(chain), ConverterConstant.CV_TASK_INITIALDELAY, ConverterConstant.CV_TASK_PERIOD, TimeUnit.SECONDS); ScheduledThreadPoolExecutor exeProposalExecutor = ThreadUtils.createScheduledThreadPool(1, new NulsThreadFactory(ConverterConstant.CV_PENDING_PROPOSAL_THREAD)); exeProposalExecutor.scheduleWithFixedDelay(new ExeProposalProcessTask(chain), ConverterConstant.CV_TASK_INITIALDELAY, ConverterConstant.CV_TASK_PERIOD, TimeUnit.SECONDS); ScheduledThreadPoolExecutor calculatorExecutor = ThreadUtils.createScheduledThreadPool(1, new NulsThreadFactory(ConverterConstant.CV_SIGN_THREAD)); calculatorExecutor.scheduleAtFixedRate(new SignMessageByzantineHandler(chain), ConverterConstant.CV_SIGN_TASK_INITIALDELAY, ConverterConstant.CV_SIGN_TASK_PERIOD, TimeUnit.SECONDS); ScheduledThreadPoolExecutor checkExecutor = ThreadUtils.createScheduledThreadPool(1, new NulsThreadFactory(ConverterConstant.CV_CHECK_THREAD)); checkExecutor.scheduleAtFixedRate(new TxCheckAndCreateProcessTask(chain), ConverterConstant.CV_CHECK_TASK_INITIALDELAY, ConverterConstant.CV_CHECK_TASK_PERIOD, TimeUnit.SECONDS); ScheduledThreadPoolExecutor htgBalanceExecutor = ThreadUtils.createScheduledThreadPool(1, new NulsThreadFactory(ConverterConstant.CV_HTG_BALANCE_THREAD)); htgBalanceExecutor.scheduleAtFixedRate(new VirtualBankDirectorBalanceTask(chain), ConverterConstant.CV_HTG_BALANCE_TASK_INITIALDELAY, ConverterConstant.CV_HTG_BALANCE_TASK_PERIOD, TimeUnit.SECONDS); ScheduledThreadPoolExecutor confirmTxExecutor = ThreadUtils.createScheduledThreadPool(1, new NulsThreadFactory("htg-confirm-tx")); confirmTxExecutor.scheduleWithFixedDelay(new HtgConfirmTxTask(converterCoreApi), 60, 10, TimeUnit.SECONDS); ScheduledThreadPoolExecutor waitingTxExecutor = ThreadUtils.createScheduledThreadPool(1, new NulsThreadFactory("htg-waiting-tx")); waitingTxExecutor.scheduleWithFixedDelay(new HtgWaitingTxInvokeDataHandlerTask(converterCoreApi), 60, 10, TimeUnit.SECONDS); ScheduledThreadPoolExecutor rpcAvailableExecutor = ThreadUtils.createScheduledThreadPool(1, new NulsThreadFactory("htg-rpcavailable-tx")); rpcAvailableExecutor.scheduleWithFixedDelay(new HtgRpcAvailableHandlerTask(converterCoreApi), 60, 10, TimeUnit.SECONDS); } private void initLogger(Chain chain) { ChainLoggerUtil.init(chain); } public Map<Integer, Chain> getChainMap() { return chainMap; } public void setChainMap(Map<Integer, Chain> chainMap) { this.chainMap = chainMap; } public boolean containsKey(int key) { return this.chainMap.containsKey(key); } public Chain getChain(int key) { return this.chainMap.get(key); } }
package hp.Seals.GetSolutionApiVsDB; import com.google.common.base.Objects; public class SolutionPojo { private String event_code; private String insert_ts; private String short_description; // public getter and setter methods public String getEvent_code() { return event_code; } public void setEvent_code(String event_code) { this.event_code = event_code; } public String getInsert_ts() { return insert_ts; } public void setInsert_ts(String insert_ts) { this.insert_ts = insert_ts; } public String getShort_description() { return short_description; } public void setShort_description(String short_description) { this.short_description = short_description; } @Override public boolean equals(Object ob) { boolean isEqual = false; if(this.event_code.equals(event_code) && this.insert_ts.equals(insert_ts) && this.short_description.equals(short_description)) { isEqual = true; } return isEqual; } @Override public int hashCode() { return Objects.hashCode("event_code","insert_ts","short_description"); } @Override public String toString() { //return event_code + " , "+ insert_ts + " , " + short_description ; return "[ "+ event_code + ","+ insert_ts + " ] = " + short_description ; // return "[ \"event_code\" : " + "\"" + event_code + "\" , \"update_TS\" : " + "\"" + insert_ts + "\", \"short_Description\" : \" " // + "\"" + short_description + "\"" + " ]"; } }
package indi.jcl.magicblog.service.impl; import indi.jcl.magicblog.mapper.UserMapper; import indi.jcl.magicblog.service.IUserService; import indi.jcl.magicblog.vo.User; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.util.List; /** * Created by Magic Long on 2016/9/26. */ @Service @Transactional public class UserService implements IUserService { @Resource private UserMapper userMapper; @Override public User query(int userId) { return userMapper.selectOne(userId); } @Override public User login(String userName, String pwd) { User u = new User(); u.setUserName(userName); u.setPwd(pwd); List<User> list = userMapper.select(u); if(list!=null&&list.size()==0){ return null; } return list.get(0); } @Override public List<User> query(User user) { return userMapper.select(user); } @Override public void update(User user) { userMapper.update(user); } @Override public void add(User user) { userMapper.insert(user); } @Override public void delete(int userId) { userMapper.delete(userId); } }
package coals_crafting.fuel; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.event.furnace.FurnaceFuelBurnTimeEvent; import net.minecraftforge.common.MinecraftForge; import net.minecraft.item.ItemStack; import coals_crafting.item.NetheriteCoalItem; import coals_crafting.CoalsCraftingModElements; @CoalsCraftingModElements.ModElement.Tag public class NetheriteCoalFuelFuel extends CoalsCraftingModElements.ModElement { public NetheriteCoalFuelFuel(CoalsCraftingModElements instance) { super(instance, 72); MinecraftForge.EVENT_BUS.register(this); } @SubscribeEvent public void furnaceFuelBurnTimeEvent(FurnaceFuelBurnTimeEvent event) { if (event.getItemStack().getItem() == new ItemStack(NetheriteCoalItem.block, (int) (1)).getItem()) event.setBurnTime(16000); } }
package mobileappdevelopment.fhcampuswien.mad_ragetimer; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageSwitcher; import android.widget.ImageView; import android.widget.Toast; import android.widget.ViewSwitcher; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedHashSet; public class Category7Activity extends AppCompatActivity { ArrayList<Integer> array_image = new ArrayList<>(); HashSet<Integer> like = new LinkedHashSet<>(); ImageSwitcher sw; private Button prev, next, add; int i = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_category7); //Soccer Picture Category array_image.add(R.drawable.bild61); array_image.add(R.drawable.bild62); array_image.add(R.drawable.bild63); array_image.add(R.drawable.bild64); array_image.add(R.drawable.bild65); array_image.add(R.drawable.bild66); array_image.add(R.drawable.bild67); array_image.add(R.drawable.bild68); array_image.add(R.drawable.bild69); array_image.add(R.drawable.bild70); sw = (ImageSwitcher) findViewById(R.id.imageswitcher1); prev = (Button) findViewById(R.id.prev); next = (Button) findViewById(R.id.next); add = (Button) findViewById(R.id.add); sw.setFactory(new ViewSwitcher.ViewFactory() { @Override public View makeView() { ImageView imageView = new ImageView(getApplicationContext()); imageView.setScaleType(ImageView.ScaleType.FIT_CENTER); return imageView; } }); next.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (i < array_image.size()-1) { i++; sw.setImageResource(array_image.get(i)); } else i = 0; } }); prev.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (i < 1) { i = 0; } else { i--; sw.setImageResource(array_image.get(i)); } } }); sw.setImageResource(array_image.get(i)); } public void addPic(View view) { like.add(i); Toast.makeText(this, "" + like, Toast.LENGTH_SHORT).show(); } public void remove(View view) { like.remove(i); Toast.makeText(this, "" + like, Toast.LENGTH_SHORT).show(); } }
import java.awt.BorderLayout; import java.awt.EventQueue; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.border.EmptyBorder; import java.awt.CardLayout; import java.awt.Font; import javax.swing.JList; public class Cus_Main extends JFrame implements java.io.Serializable{ private JPanel contentPane; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { Cus_Main frame = new Cus_Main(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public Cus_Main() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 1307, 731); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(new CardLayout(0, 0)); JPanel main = new JPanel(); contentPane.add(main, "name_106940705007525"); main.setLayout(null); main.setVisible(true); JLabel lblNotifications = new JLabel("Notifications"); lblNotifications.setFont(new Font("Tahoma", Font.PLAIN, 30)); lblNotifications.setBounds(979, 49, 189, 55); main.add(lblNotifications); JLabel lblWelcome = new JLabel("Welcome"); lblWelcome.setFont(new Font("Tahoma", Font.PLAIN, 35)); lblWelcome.setBounds(428, 13, 158, 43); main.add(lblWelcome); JButton btnSubscribe = new JButton("Subscribe"); btnSubscribe.setFont(new Font("Tahoma", Font.PLAIN, 23)); btnSubscribe.setBounds(505, 135, 252, 55); main.add(btnSubscribe); JButton btnChangeSubscription = new JButton("Change Subscription"); btnChangeSubscription.setFont(new Font("Tahoma", Font.PLAIN, 23)); btnChangeSubscription.setBounds(505, 231, 252, 55); main.add(btnChangeSubscription); JButton btnPauseSubscription = new JButton("Pause Subscription"); btnPauseSubscription.setFont(new Font("Tahoma", Font.PLAIN, 23)); btnPauseSubscription.setBounds(505, 327, 252, 55); main.add(btnPauseSubscription); JButton btnStopSubscription = new JButton("Stop Subscription"); btnStopSubscription.setFont(new Font("Tahoma", Font.PLAIN, 23)); btnStopSubscription.setBounds(505, 428, 252, 55); main.add(btnStopSubscription); JButton btnViewMyInfo = new JButton("View My Info."); btnViewMyInfo.setFont(new Font("Tahoma", Font.PLAIN, 23)); btnViewMyInfo.setBounds(505, 522, 252, 43); main.add(btnViewMyInfo); JButton btnEditMyInfo = new JButton("Edit My Info"); btnEditMyInfo.setFont(new Font("Tahoma", Font.PLAIN, 23)); btnEditMyInfo.setBounds(505, 605, 252, 56); main.add(btnEditMyInfo); JScrollPane scrollPane = new JScrollPane(); scrollPane.setBounds(873, 125, 394, 538); main.add(scrollPane); JList list = new JList(); scrollPane.setViewportView(list); } }
package com.dexter.myhome.model; import java.util.Date; public class Issue { private String title; private String description; private Date issueDate; private String raisedBy; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Date getIssueDate() { return issueDate; } public void setIssueDate(Date issueDate) { this.issueDate = issueDate; } public String getRaisedBy() { return raisedBy; } public void setRaisedBy(String raisedBy) { this.raisedBy = raisedBy; } }
package com.citibank.ods.persistence.pl.dao; import java.math.BigInteger; import com.citibank.ods.common.dataset.DataSet; import com.citibank.ods.entity.pl.BaseTplCurAcctPrmntInstrEntity; import com.citibank.ods.entity.pl.TplCurAcctPrmntInstrMovEntity; // //©2002-2007 Accenture. All rights reserved. // /** * * @see package com.citibank.ods.persistence.pl.dao; * @version 1.0 * @author michele.monteiro,13/06/2007 * */ public interface TplCurAcctPrmntInstrMovDAO extends BaseTplCurAcctPrmntInstrDAO { public TplCurAcctPrmntInstrMovEntity insert( TplCurAcctPrmntInstrMovEntity tplCurAcctPrmntInstrMovEntity_ ); public DataSet list( BigInteger curAcctNbr_, BigInteger custNbr_, BigInteger prmntInstrCode_, String prmntInstrInvstCurAcctInd_, String lastUpdUserId_, String custFullName_ ); public void delete( BigInteger custNbr_, BigInteger prodCode_, BigInteger prodUnderCode_ ); public void deleteById(BigInteger prmntCode_ ); public boolean existsRelation( BigInteger prmntInstrCode_, BigInteger prodAcctCode_, BigInteger prodUnderAcctCode_ ); public boolean exists( BigInteger prodAcctCode_, BigInteger prodUnderAcctCode_, BigInteger custNbr_ ); public BaseTplCurAcctPrmntInstrEntity findById(BigInteger prmntCode_ ); }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.bytecode.magtimus.controller; import org.bytecode.magtimus.service.ImagenService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.ModelAndView; /** * * @author Jose David */ @Controller @RequestMapping("/image") public class Controlador { @Autowired private ImagenService service; @GetMapping("/all") public ModelAndView find(Pageable page){ ModelAndView md = new ModelAndView("index"); md.addObject("imgs", service.find(page)); return md; } @PostMapping("/upload") @ResponseBody public String ruta_subida( @RequestParam("img") MultipartFile file ){ return service.saveImage(file); } @PostMapping("/register") @ResponseBody public String inser(@RequestParam("titulo")String titulo, @RequestParam("ruta")String ruta) { service.guardarImg(titulo, ruta); return "/image/all?page=0&size=9"; } }
/** * COPYRIGHT (C) 2013 KonyLabs. All Rights Reserved. * * @author rbanking */ package com.classroom.services.web.security.permissions.expression; import org.aopalliance.intercept.MethodInvocation; import org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler; import org.springframework.security.access.expression.method.MethodSecurityExpressionOperations; import org.springframework.security.authentication.AuthenticationTrustResolver; import org.springframework.security.authentication.AuthenticationTrustResolverImpl; import org.springframework.security.core.Authentication; import com.classroom.services.web.security.permissions.IPermissionEvaluator; /** * Custom expressions handler */ public class MethodSecurityExpressionHandler extends DefaultMethodSecurityExpressionHandler { private final AuthenticationTrustResolver trustResolver = new AuthenticationTrustResolverImpl(); /* * (non-Javadoc) * * @see org.springframework.security.access.expression.method. * DefaultMethodSecurityExpressionHandler * #createSecurityExpressionRoot(org.springframework * .security.core.Authentication, * org.aopalliance.intercept.MethodInvocation) */ @Override protected MethodSecurityExpressionOperations createSecurityExpressionRoot( Authentication authentication, MethodInvocation invocation) { MethodSecurityExpressionRoot root = new MethodSecurityExpressionRoot( authentication); root.setThis(invocation); root.setRestPermissionEvaluator((IPermissionEvaluator) getPermissionEvaluator()); root.setTrustResolver(trustResolver); root.setRoleHierarchy(getRoleHierarchy()); return root; } }
package com.praktyki.log.app.data.converters; import com.praktyki.log.app.data.entities.ScheduleCalculationEventEntity; import com.praktyki.log.web.message.models.ScheduleCalculationEventModel; import org.springframework.stereotype.Component; @Component public class ScheduleCalculationEventConverterImpl implements ScheduleCalculationEventConverter { @Override public ScheduleCalculationEventModel convertToModel(ScheduleCalculationEventEntity scheduleCalculationEventEntity) { return new ScheduleCalculationEventModel( scheduleCalculationEventEntity.eventId, scheduleCalculationEventEntity.scheduleConfigurationEntity.capital, scheduleCalculationEventEntity.scheduleConfigurationEntity.installmentType, scheduleCalculationEventEntity.scheduleConfigurationEntity.installmentAmount, scheduleCalculationEventEntity.scheduleConfigurationEntity.interestRate, scheduleCalculationEventEntity.scheduleConfigurationEntity.withdrawalDate, scheduleCalculationEventEntity.scheduleConfigurationEntity.commissionRate, scheduleCalculationEventEntity.scheduleConfigurationEntity.age, scheduleCalculationEventEntity.scheduleConfigurationEntity.insurance, scheduleCalculationEventEntity.scheduleSummaryEntity.capitalInstallmentSum, scheduleCalculationEventEntity.scheduleSummaryEntity.interestInstallmentSum, scheduleCalculationEventEntity.scheduleSummaryEntity.loanPaidOutAmount, scheduleCalculationEventEntity.scheduleSummaryEntity.commissionAmount, scheduleCalculationEventEntity.scheduleSummaryEntity.insuranceTotalAmount, scheduleCalculationEventEntity.scheduleSummaryEntity.loanTotalCost, scheduleCalculationEventEntity.scheduleSummaryEntity.aprc, scheduleCalculationEventEntity.orderDate ); } }
package com.lsm.springboot.config; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; import org.springframework.data.redis.core.*; import redis.clients.jedis.JedisPoolConfig; @Configuration @Slf4j public class RedisConfig { @Value("${spring.redis.host}") private String host; @Value("${spring.redis.port}") private Integer port; @Value("${spring.redis.timeout}") private Integer timeout; @Value("${spring.redis.pool.max-active}") private Integer maxActive; @Value("${spring.redis.pool.max-idle}") private Integer maxIdle; @Value("${spring.redis.pool.max-wait}") private Integer maxWait; @Bean(name = "jedisConnectionFactory") public JedisConnectionFactory getConnectionFactory(){ JedisConnectionFactory factory = new JedisConnectionFactory(); JedisPoolConfig config = new JedisPoolConfig(); config.setMaxTotal(maxActive); config.setMaxIdle(maxIdle); config.setMaxWaitMillis(maxWait); factory.setPoolConfig(config); factory.setHostName(host); factory.setPort(port); // 选择数据库 factory.setUsePool(true); factory.setDatabase(2); log.info("JedisConnectionFactory bean init success."); return factory; } @Bean(name = "redisTemplate") public RedisTemplate<String, String> getRedisTemplate(JedisConnectionFactory jedisConnectionFactory){ return new StringRedisTemplate(jedisConnectionFactory); } /** * 对字符串(String)的操作 */ @Bean(name = "opsForValue") public ValueOperations<String, String> opsForValue(@Qualifier("redisTemplate") RedisTemplate<String, String> redisTemplate) { return redisTemplate.opsForValue(); } /** * 对哈希(Hash)的操作 */ @Bean(name = "opsForHash") public HashOperations<String, String, String> opsForHash(@Qualifier("redisTemplate") RedisTemplate<String, String> redisTemplate) { return redisTemplate.opsForHash(); } /** * 对列表(list)的操作 */ @Bean(name = "opsForList") public ListOperations<String, String> opsForList(@Qualifier("redisTemplate") RedisTemplate<String, String> redisTemplate) { return redisTemplate.opsForList(); } /** * 对集合(Set)的操作 */ @Bean(name = "opsForSet") public SetOperations<String, String> opsForSet(@Qualifier("redisTemplate") RedisTemplate<String, String> redisTemplate) { return redisTemplate.opsForSet(); } /** * 对有序集合(zset)的操作 */ @Bean(name = "opsForZSet") public ZSetOperations<String, String> opsForZSet(@Qualifier("redisTemplate") RedisTemplate<String, String> redisTemplate) { return redisTemplate.opsForZSet(); } }
//java NullPointerException when null is passed in method argument class Temp { public static void main(String[]args) { foo(null); } public static void foo(String s) { System.out.println(s.toLowerCase()); } }
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.format.support; import java.util.Set; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.context.EmbeddedValueResolverAware; import org.springframework.core.convert.support.ConversionServiceFactory; import org.springframework.format.AnnotationFormatterFactory; import org.springframework.format.Formatter; import org.springframework.format.FormatterRegistrar; import org.springframework.format.FormatterRegistry; import org.springframework.format.Parser; import org.springframework.format.Printer; import org.springframework.lang.Nullable; import org.springframework.util.StringValueResolver; /** * A factory providing convenient access to a {@code FormattingConversionService} * configured with converters and formatters for common types such as numbers and * datetimes. * * <p>Additional converters and formatters can be registered declaratively through * {@link #setConverters(Set)} and {@link #setFormatters(Set)}. Another option * is to register converters and formatters in code by implementing the * {@link FormatterRegistrar} interface. You can then configure provide the set * of registrars to use through {@link #setFormatterRegistrars(Set)}. * * <p>A good example for registering converters and formatters in code is * {@code JodaTimeFormatterRegistrar}, which registers a number of * date-related formatters and converters. For a more detailed list of cases * see {@link #setFormatterRegistrars(Set)} * * <p>Like all {@code FactoryBean} implementations, this class is suitable for * use when configuring a Spring application context using Spring {@code <beans>} * XML. When configuring the container with * {@link org.springframework.context.annotation.Configuration @Configuration} * classes, simply instantiate, configure and return the appropriate * {@code FormattingConversionService} object from a * {@link org.springframework.context.annotation.Bean @Bean} method. * * @author Keith Donald * @author Juergen Hoeller * @author Rossen Stoyanchev * @author Chris Beams * @since 3.0 */ public class FormattingConversionServiceFactoryBean implements FactoryBean<FormattingConversionService>, EmbeddedValueResolverAware, InitializingBean { @Nullable private Set<?> converters; @Nullable private Set<?> formatters; @Nullable private Set<FormatterRegistrar> formatterRegistrars; private boolean registerDefaultFormatters = true; @Nullable private StringValueResolver embeddedValueResolver; @Nullable private FormattingConversionService conversionService; /** * Configure the set of custom converter objects that should be added. * @param converters instances of any of the following: * {@link org.springframework.core.convert.converter.Converter}, * {@link org.springframework.core.convert.converter.ConverterFactory}, * {@link org.springframework.core.convert.converter.GenericConverter} */ public void setConverters(Set<?> converters) { this.converters = converters; } /** * Configure the set of custom formatter objects that should be added. * @param formatters instances of {@link Formatter} or {@link AnnotationFormatterFactory} */ public void setFormatters(Set<?> formatters) { this.formatters = formatters; } /** * <p>Configure the set of FormatterRegistrars to invoke to register * Converters and Formatters in addition to those added declaratively * via {@link #setConverters(Set)} and {@link #setFormatters(Set)}. * <p>FormatterRegistrars are useful when registering multiple related * converters and formatters for a formatting category, such as Date * formatting. All types related needed to support the formatting * category can be registered from one place. * <p>FormatterRegistrars can also be used to register Formatters * indexed under a specific field type different from its own &lt;T&gt;, * or when registering a Formatter from a Printer/Parser pair. * @see FormatterRegistry#addFormatterForFieldType(Class, Formatter) * @see FormatterRegistry#addFormatterForFieldType(Class, Printer, Parser) */ public void setFormatterRegistrars(Set<FormatterRegistrar> formatterRegistrars) { this.formatterRegistrars = formatterRegistrars; } /** * Indicate whether default formatters should be registered or not. * <p>By default, built-in formatters are registered. This flag can be used * to turn that off and rely on explicitly registered formatters only. * @see #setFormatters(Set) * @see #setFormatterRegistrars(Set) */ public void setRegisterDefaultFormatters(boolean registerDefaultFormatters) { this.registerDefaultFormatters = registerDefaultFormatters; } @Override public void setEmbeddedValueResolver(StringValueResolver embeddedValueResolver) { this.embeddedValueResolver = embeddedValueResolver; } @Override public void afterPropertiesSet() { this.conversionService = new DefaultFormattingConversionService(this.embeddedValueResolver, this.registerDefaultFormatters); ConversionServiceFactory.registerConverters(this.converters, this.conversionService); registerFormatters(this.conversionService); } private void registerFormatters(FormattingConversionService conversionService) { if (this.formatters != null) { for (Object candidate : this.formatters) { if (candidate instanceof Formatter<?> formatter) { conversionService.addFormatter(formatter); } else if (candidate instanceof AnnotationFormatterFactory<?> factory) { conversionService.addFormatterForFieldAnnotation(factory); } else { throw new IllegalArgumentException( "Custom formatters must be implementations of Formatter or AnnotationFormatterFactory"); } } } if (this.formatterRegistrars != null) { for (FormatterRegistrar registrar : this.formatterRegistrars) { registrar.registerFormatters(conversionService); } } } @Override @Nullable public FormattingConversionService getObject() { return this.conversionService; } @Override public Class<? extends FormattingConversionService> getObjectType() { return FormattingConversionService.class; } @Override public boolean isSingleton() { return true; } }
package com.test.base; import com.test.SolutionA; import junit.framework.TestCase; public class Example extends TestCase { private SolutionA solution; @Override protected void setUp() throws Exception { super.setUp(); } public void testSolutionA() { solution = new SolutionA(); assertSolution(); } private void assertSolution() { checkSolution("https://www.example.com/art"); checkSolution("https://leetcode.com/problems/design-tinyurl"); checkSolution("https://bone.example.net/?brother=agreement&beds=bird"); checkSolution("https://agreement.example.com/"); } private void checkSolution(String longUrl) { System.out.println("----------------------------------"); String shortUrl = solution.encode(longUrl); System.out.println("short = " + shortUrl); String result = solution.decode(shortUrl); System.out.println("result = " + result); assertEquals(result, longUrl); } @Override protected void tearDown() throws Exception { super.tearDown(); } }
package db; import java.sql.SQLException; import java.sql.Timestamp; import java.util.Date; import java.util.List; import java.util.Map; /** * The <b>DBI</b> class provides static utility methods for accessing a DBMS. */ public class DBI { private static OracleAPI api = new OracleAPI(); private DBI() { // utility class; prevent instantiation } /** * Executes the SQL statement "select Field from Table where ..." * and returns the first value from the first column as a String. * * @return the requested field's value from the first record */ public static String getString (final CharSequence select) { String result = null; try { result = api.getString (select); } catch (SQLException x) { System.err.println (x.getMessage () + ": " + select); x.printStackTrace (System.err); } return result; } /** * Executes the SQL statement and returns the value from the first column * of the first row as a number. The query should result in a single value; * such as "select count(*) from ..." */ public static double getDouble (final CharSequence select) { double result = 0; try { result = api.getDouble (select); } catch (SQLException x) { System.err.println (x.getMessage () + ": " + select); x.printStackTrace (System.err); } return result; } /** * Executes the SQL statement "select Field from Table where ..." * and returns the first value from the first column as a Date. * * @return the requested field's value from the first record */ public static Date getDate (final CharSequence select) { Date result = null; try { result = api.getDate (select); } catch (SQLException x) { System.err.println (x.getMessage () + ": " + select); x.printStackTrace (System.err); } return result; } /** * Executes the SQL statement "select Field from Table where ..." * and returns the first value from the first column as a Timestamp. * * @return the requested field's value from the first record */ public static Timestamp getTimestamp (final CharSequence select) { Timestamp result = null; try { result = api.getTimestamp (select); } catch (SQLException x) { System.err.println (x.getMessage () + ": " + select); x.printStackTrace (System.err); } return result; } /** * Executes the SQL statement and returns the values from the first * column as a List of Strings. * * @return a (possibly empty) list of the selected field's values * for all matching records */ public static List<String> getList (final CharSequence select) { List<String> result = null; try { result = api.getList (select); } catch (SQLException x) { System.err.println (x.getMessage () + ": " + select); x.printStackTrace (System.err); } return result; } /** * Executes the SQL statement, select Field1, Field2 from Table where etc, * and returns a Map using the values from the first column as the * key, and the values from the second column as the value. * * @return a mapping of the selected field values for all matching records */ public static Map<String, String> getMapping (final CharSequence select) { Map<String, String> result = null; try { result = api.getMapping (select); } catch (SQLException x) { System.err.println (x.getMessage () + ": " + select); x.printStackTrace (System.err); } return result; } /** * Executes the give SQL select statement (which should result in a single * row), "select * from Table where ...", and returns a Map using * the field names as the keys mapped to the values. * * Warning: Functions such as SUM(col) return blank names. To avoid this * problem, use 'select SUM(Field) as FieldSum ...' * * @return a mapping of the fields to values for a single row */ public static Map<String, String> getFieldMap (final CharSequence select) { Map<String, String> result = null; try { result = api.getFieldMap (select); } catch (SQLException x) { System.err.println (x.getMessage () + ": " + select); x.printStackTrace (System.err); } return result; } /** * Queries the given table, and returns a TableModel containing all records. */ public static Model getTableAll (final CharSequence tableName) { return getTable ("select * from " + tableName); } /** * Executes the given SQL select statement (such as "select * from Table where ..."), * and returns a TableModel containing the matching records. * * Warning: Functions such as SUM(col) return blank names. To avoid this * problem, use 'select SUM(Field) as FieldSum ...' */ public static Model getTable (final CharSequence select) { Model result = null; try { result = api.getTable (select); } catch (SQLException x) { System.err.println (x.getMessage () + ": " + select); x.printStackTrace (System.err); } return result; } /** * Executes the given SQL select statement (such as "select * from Table where ..."), * and returns a TableModel containing the matching records. * * Warning: Functions such as SUM(col) return blank names. To avoid this * problem, use 'select SUM(Field) as FieldSum ...' * * @param select CharSequence containing the select statement * @param start int containing the first row number (zero based) to be returned * @param max int containing the max number of rows to be returned */ public static Model getTable (final CharSequence select, int start, int max) { Model result = null; try { result = api.getTable (select, start, max); } catch (SQLException x) { System.err.println (x.getMessage () + ": " + select); x.printStackTrace (System.err); } return result; } /** * Executes the given SQL statement, and returns the number of records affected. */ public static int execute (final CharSequence update) { int result = 0; try { result = api.execute (update); } catch (SQLException x) { System.err.println (x.getMessage () + ": " + update); x.printStackTrace (System.err); } return result; } /** * The given SQL insert statement should contain an embedded token (%1$d) * representing a place-holder for a GUID. This method will generate a GUID, * replace the token with the GUID, and execute it. The GUID is returned if * the insert succeeded; otherwise null is returned. For example: * INSERT INTO MyTable (Key, Col2, Col3) VALUES ('%1$s', 2, 'Three') */ public static String insertWithGuid (final CharSequence insertFormat) { String result = null; try { result = api.insertWithGuid (insertFormat); } catch (SQLException x) { System.err.println (x.getMessage () + ": " + insertFormat); x.printStackTrace (System.err); } return result; } /** * Creates and executes an SQL statement to insert the given values into * the given table. A GUID is generated and used as the first value. This * serves as the Primary Key. The GUID is returned if the insert succeeded; * otherwise null is returned. */ public static String insertWithGuid (final String table, final Object... values) { String result = null; try { result = api.insertWithGuid (table, values); } catch (SQLException x) { System.err.println (x.getMessage () + ": " + table); x.printStackTrace (System.err); } return result; } public static void main (final String[] args) // for testing { } }
package br.microgamr.microgames.util; /** * Um observador do estado de um microgame. É implementado pela * {@link br.microgamr.screens.GameScreen}, que precisa ser notificada quando o jogo é pausado, * resumido, quando o tempo está acabando e quando seu estado * {@link br.microgamr.microgames.util.MicroGameState} muda. * * @author Flávio Coutinho <fegemo@cefetmg.br> */ public interface MicroGameStateObserver { /** * Chamado quando o estado * {@link br.microgamr.microgames.util.MicroGameState} do microgame * atual é alterado. Por exemplo, quando está * <code>SHOWING_INSTRUCTIONS</code> e passa para <code>PLAYING</code>. * * @param state o novo estado do microgame atual. */ void onStateChanged(MicroGameState state); /** * Chamada quando faltam 3s para o microgame acabar. */ void onTimeEnding(); /** * Chamada quando o microgame é pausado. */ void onGamePaused(); /** * Chamada quando o microgame é resumido, depois de uma pausa. */ void onGameResumed(); /** * Usada para mostrar uma mensagem na tela de jogo. * @param strMessage */ void showMessage(String strMessage); }
package com.wangyang.user.model; public class Student { private int id; private String username; private String password; private int classname; private int schoolname; private int collegename; private int ybid; private int studentid; private int state; private int identity; }
package com.ajhlp.app.integrationTools.services; import org.springframework.dao.DataAccessException; import com.ajhlp.app.integrationTools.model.DBConnection; public interface IDBConnectionEditService extends IBasicService { public void saveDBConn(DBConnection conn) throws DataAccessException; }
package org.exoplatform.management.idm.tasks; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.zip.ZipOutputStream; import org.apache.commons.compress.utils.IOUtils; import org.exoplatform.platform.organization.injector.DataInjectorService; import org.gatein.management.api.exceptions.OperationException; import org.gatein.management.api.operation.OperationNames; import org.gatein.management.api.operation.model.ExportTask; /** * @author <a href="mailto:bkhanfir@exoplatform.com">Boubaker Khanfir</a> * @version $Revision$ */ public class IDMExportTask implements ExportTask { private final DataInjectorService dataInjectorService; public IDMExportTask(DataInjectorService dataInjectorService) { this.dataInjectorService = dataInjectorService; } @Override public String getEntry() { return "idm.zip"; } @Override public void export(OutputStream outputStream) throws IOException { File zosFile = File.createTempFile("idm-users", ".zip"); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zosFile)); try { dataInjectorService.writeUsers(zos); dataInjectorService.writeProfiles(zos); dataInjectorService.writeOrganizationModelData(zos); } catch (Exception exception) { throw new OperationException(OperationNames.EXPORT_RESOURCE, "Error exporting users: " + exception.getMessage(), exception); } zos.close(); FileInputStream fileInputStream = new FileInputStream(zosFile); IOUtils.copy(fileInputStream, outputStream); } }
package apache_math_cluster; import org.apache.commons.math3.exception.DimensionMismatchException; import org.apache.commons.math3.ml.distance.DistanceMeasure; public class HaversineDistance extends Object implements DistanceMeasure { private static final long serialVersionUID = 1L; @Override public double compute(double[] a, double[] b) throws DimensionMismatchException { return distance(a, b); } public double distance(double[] p1, double[] p2 ) throws DimensionMismatchException { checkEqualLength(p1,p2); double distancelatitude = Math.toRadians(p2[0] - p1[0]); double distancelongitude = Math.toRadians(p2[1]- p1[1]); double startlatitude = Math.toRadians(p1[0]); double endlatitude = Math.toRadians(p2[0]); double a = Math.pow(Math.sin(distancelatitude/2), 2)+ Math.cos(startlatitude)* Math.cos(endlatitude)* Math.pow(Math.sin(distancelongitude/2), 2); double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); Double earthRadiusKM = 6371.00; return earthRadiusKM * c; } /** * * @param a * @param b */ public void checkEqualLength(double[]a, double[]b){ checkEqualLength(a,b,true); } /** * * @param a * @param b * @param abort * @return */ public static boolean checkEqualLength(double[]a, double[]b,boolean abort){ if(a.length == b.length){ return true; } else{ if(abort){ throw new DimensionMismatchException(a.length, b.length); } return false; } } }
package com.gaoshin.cj.api; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "cj-api") public class AdvertiserLookupResponse { private Advertisers advertisers; @XmlElement(name="advertisers") public Advertisers getAdvertisers() { return advertisers; } public void setAdvertisers(Advertisers advertisers) { this.advertisers = advertisers; } }
package com.vastrak.datetime; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.when; import java.sql.Timestamp; import java.time.Clock; import java.time.Duration; import java.time.Instant; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.Month; import java.time.Period; import java.time.Year; import java.time.YearMonth; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.time.format.FormatStyle; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.junit.FixMethodOrder; import org.junit.Rule; import org.junit.Test; import org.junit.runners.MethodSorters; import org.mockito.Mock; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class DateTimeAPITest { @Mock Clock mock_Clock; // Tells Mockito to create the mocks based on the @Mock annotation @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); private static final Log logger = LogFactory.getLog(DateTimeAPITest.class); @Test public void test001_LocalDate() { LocalDate localDate = LocalDate.now(); // 2019-07-04 LocalDate localDateGMT = LocalDate.now(ZoneId.of("GMT+02:00")); // 2019-07-04 LocalDate localDateT = LocalDateTime.now().toLocalDate(); // 2019-07-04 LocalDate todayPlusThreeMonth = localDate.plusMonths(3); // plusYears, plusWeeks, plusDays LocalDate todayMinusTwoWeeks = localDate.minusWeeks(2); // minus Calendar calendarPM = Calendar.getInstance(); calendarPM.setTime(new Date()); calendarPM.add(Calendar.MONTH, 3); // localDate.plusMonths(3); Calendar calendarMW = Calendar.getInstance(); calendarMW.setTime(new Date()); calendarMW.add(Calendar.DAY_OF_MONTH, -14); // localeDate.minusWeeks(2); // LocalDate: 2019-10-04. Calendar: Fri Oct 04 09:46:54 CEST 2019 logger.info("LocalDate: " + todayPlusThreeMonth + ". Calendar: " + calendarPM.getTime()); assertThat(localDate).isEqualTo(localDateGMT).isEqualTo(localDateT); assertThat(todayPlusThreeMonth.getYear()).isEqualTo(calendarPM.get(Calendar.YEAR)); assertThat(todayPlusThreeMonth.getMonth().ordinal()).isEqualTo(calendarPM.get(Calendar.MONTH)); assertThat(todayPlusThreeMonth.getDayOfMonth()).isEqualTo(calendarPM.get(Calendar.DAY_OF_MONTH)); assertThat(todayMinusTwoWeeks.getYear()).isEqualTo(calendarMW.get(Calendar.YEAR)); assertThat(todayMinusTwoWeeks.getMonth().ordinal()).isEqualTo(calendarMW.get(Calendar.MONTH)); assertThat(todayMinusTwoWeeks.getDayOfMonth()).isEqualTo(calendarMW.get(Calendar.DAY_OF_MONTH)); } @Test public void test002_LocalDateTimeStamp() { LocalDate localDate = LocalDate.parse("1986-10-12"); // Timestam: wrapper around java.util.Date that allows the JDBC API to identify // this as an SQL TIMESTAMP value. LocalDateTime dateTime = localDate.atTime(14, 25, 10); Timestamp timestamp = Timestamp.valueOf(dateTime); assertThat(Timestamp.valueOf("1986-10-12 14:25:10")).isEqualTo(timestamp); } @Test public void test003_formatterZonedDateTime() { ZonedDateTime zonedDateTime = ZonedDateTime.now(); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss.SS"); // 04/07/2019 11:53:53.87 String text = zonedDateTime.format(formatter); LocalDateTime localDateTime = LocalDateTime.parse(text, formatter); logger.info("formatter : " + text); // 04/07/2019 11:53:53.87 assertThat(localDateTime.toLocalDate()).isEqualTo(zonedDateTime.toLocalDate()); assertThat(localDateTime.getHour()).isEqualTo(zonedDateTime.getHour()); assertThat(localDateTime.getMinute()).isEqualTo(zonedDateTime.getMinute()); assertThat(localDateTime.getSecond()).isEqualTo(zonedDateTime.getSecond()); } @Test public void test004_LocalDateTime() { // A date without an explicitly specified time zone. LocalDate localDate = LocalDate.now(); // 2019-07-04 LocalDate localDateOf = LocalDate.of(1986, Month.JUNE, 21); // 1986-06-21 LocalDate localDateEpoch = LocalDate.ofEpochDay(localDate.toEpochDay()); // 2019-07-04 LocalDate localDateParse = LocalDate.parse("1986-06-21"); // 1986-06-21 // A date-time without a time-zone in the ISO-8601 calendar system, // such as 2007-12-03T10:15:30. LocalDateTime localDateTime = LocalDateTime.now(); // 2019-07-04T08:46:30.107 <- local time LocalDateTime localDateTimeOf = LocalDateTime.of(1986, Month.JUNE, 21, 17, 50); // 1986-06-21T17:50 LocalDateTime localDateTimeParse = LocalDateTime.parse("1986-06-21T17:50:31"); // 1986-06-21T17:50:31 // A time without a time-zone in the ISO-8601 calendar system, // such as 10:15:30. LocalTime localTime = LocalTime.now(); // 08:46:30.108 LocalTime localTimeOf = LocalTime.of(17, 50, 31); // 17:50:31 LocalTime localTimeParse = LocalTime.parse("17:50:31"); // A year in the ISO-8601 calendar system, such as 2007. Year year = Year.now(); // 2019 // A year-month in the ISO-8601 calendar system, such as 2007-12. YearMonth yearMonth = YearMonth.now(); // 2019-07 logger.info("Date " + localDate); logger.info("DateOf " + localDateOf); logger.info("DateEpoch " + localDateEpoch); logger.info("DateParse " + localDateParse); logger.info("DateTime " + localDateTime); logger.info("DateTimeOf " + localDateTimeOf); logger.info("DateTimeParse " + localDateTimeParse); logger.info("Time" + localTime); logger.info("TimeOf " + localTimeOf); logger.info("TimeParse " + localTimeParse); logger.info("Year " + year); logger.info("YearMonth " + yearMonth); } @Test public void test005_Instant() { // This class is immutable and thread-safe. // Output format is ISO-8601 // Parse into an Instant Instant instantBorn = Instant.parse("2009-03-17T16:00:00.00Z"); // 2009-03-17T16:00:00Z Instant instantPlus = instantBorn.plus(Duration.ofHours(5).plusMinutes(4)); // 2009-03-17T21:04:00Z Instant instantMinus = instantBorn.minus(Period.ofWeeks(3).minusDays(2)); // 2009-02-26T16:00:00Z Instant calculatedInstantPlus = Instant.parse("2009-03-17T21:04:00Z"); Instant calculatedInstantMinus = Instant.parse("2009-02-26T16:00:00Z"); assertThat(instantPlus).isEqualTo(calculatedInstantPlus); assertThat(instantMinus).isEqualTo(calculatedInstantMinus); logger.info("Instant: " + instantBorn + ": plus 5 hours 4 min. " + instantPlus); logger.info("Instant: " + instantBorn + ": minus 3 weeks and 2 days " + instantMinus); } @Test public void test006_DurationBetweenTwoInstants() { // A Duration measures an amount of time using time-based values (seconds, // nanoseconds). // A Period uses date-based values (years, months, days) Instant a = Instant.parse("2007-12-03T10:15:30.00Z"); Instant b = Instant.parse("2007-12-03T10:25:15.00Z"); // a + 9'45" Duration gapExpected = Duration.ofSeconds(60 * 9).plus(45, ChronoUnit.SECONDS); Duration gap = Duration.between(a, b); long minutes = Duration.between(a, b).toMinutes(); // truncate seconds // 9' long milli = Duration.between(a, b).toMillis(); // 585000 assertThat(gap).isEqualByComparingTo(gapExpected); logger.info("Gap minutes: " + minutes + ", milliseconds " + milli); } @Test public void test007_ChronoUnitBetweenTwoInstants() { // The ChronoUnit enum, defines the units used to measure time. // The ChronoUnit.between method is useful when you want to measure an amount // of time in a single unit of time only, such as days or seconds. Instant a = Instant.parse("2007-12-03T10:15:30.00Z"); Instant b = Instant.parse("2007-12-03T10:25:15.00Z"); // a + 9'45" Duration gapExpected = Duration.ofSeconds(60 * 9).plus(45, ChronoUnit.SECONDS); long gapm = ChronoUnit.MILLIS.between(a, b); long gaps = ChronoUnit.SECONDS.between(a, b); // gapm * 1000 assertThat(gapm).isEqualTo(gapExpected.toMillis()).isEqualTo(gaps * 1000); } @Test public void test008_PeriodBetweenTwoLocalDate() { // To define an amount of time with date-based values (years, months, days), // use the Period class. The Period class provides various get methods, // such as getMonths, getDays, and getYears, so that you can extract the // amount of time from the period. LocalDate today = LocalDate.parse("2019-07-07"); LocalDate yesterday = LocalDate.of(1986, Month.APRIL, 3); Period p = Period.between(yesterday, today); // 33 years, 3 months, 4 days long p2 = ChronoUnit.DAYS.between(yesterday, today); // 12148 days assertThat(p.getYears()).isEqualTo(33L); assertThat(p.getMonths()).isEqualTo(3L); assertThat(p.getDays()).isEqualTo(4L); assertThat(p2).isEqualTo(12148L); } @Test public void test009_convertLocalDateTimeToInstant() { LocalDateTime dateTime = LocalDateTime.of(2017, Month.MARCH, 07, 10, 55); // 2017/03/07 10:55; Instant instant = dateTime.atZone(ZoneId.of("GMT+02:00")).toInstant(); assertThat(instant.toString()).isEqualTo("2017-03-07T08:55:00Z"); } @Test public void test010_convertInstantToLocalDateTime() { // 2017/03/07 10:55; Instant instant = LocalDateTime.of(2017, Month.MARCH, 07, 10, 55).atZone(ZoneId.of("GMT+02:00")).toInstant(); LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.of("GMT+02:00")); assertThat(instant.getNano()).isEqualTo(localDateTime.getNano()); } /** * Generates a sequence of LocalDateTime, adding a number of minutes to a * LocalDateTime variable. LocalDateTime + minutes[0], LocalDateTime + * minutes[1], ... * <p> * Increment aren't accumulative * * @param start LocalDateTime to start adding minutes. * @param minutes Array of Integer with the minutes to add to LocalDateTime. * @return Set of LocalDateTime */ private Set<LocalDateTime> dateTimePlusArray(LocalDateTime start, int[] minutes) { if (minutes == null || start == null) { return null; } Set<LocalDateTime> timeSet = null; for (int i = 0; i < minutes.length; i++) { if (timeSet == null) { timeSet = new HashSet<>(); } Instant instant = start.atZone(ZoneId.of("GMT+02:00")).toInstant(); timeSet.add(LocalDateTime.ofInstant(instant.plus(minutes[i], ChronoUnit.MINUTES), ZoneId.of("GMT+02:00"))); } return timeSet; } @Test public void test011_DateTimePlusArray() { // start DateTime LocalDateTime localDateTime = LocalDateTime.parse("2019-03-13T16:00:00"); // minutes to add int[] minutes = { 1, 5, 10, 20, 30, 40, -10 }; Set<LocalDateTime> set = dateTimePlusArray(localDateTime, minutes); // expected! LocalDateTime next1 = LocalDateTime.parse("2019-03-13T16:01:00"); LocalDateTime next2 = LocalDateTime.parse("2019-03-13T16:05:00"); LocalDateTime next3 = LocalDateTime.parse("2019-03-13T16:10:00"); LocalDateTime next4 = LocalDateTime.parse("2019-03-13T16:20:00"); LocalDateTime next5 = LocalDateTime.parse("2019-03-13T16:30:00"); LocalDateTime next6 = LocalDateTime.parse("2019-03-13T16:40:00"); LocalDateTime next7 = LocalDateTime.parse("2019-03-13T15:50:00"); // check! assertThat(set).isNotNull().contains(next1, next2, next3, next4, next5, next6, next7).hasSize(7); assertThat(dateTimePlusArray(localDateTime, null)).isNull(); int[] v = {}; assertThat(dateTimePlusArray(localDateTime, v)).isNull(); } @Test public void test012_DateTimePlusArrayNullCases() { LocalDateTime localDateTimeNull = null; LocalDateTime localDateTimeNow = LocalDateTime.now(); int[] minutesEmpty = {}; int[] minutes = { 1 }; assertThat(dateTimePlusArray(localDateTimeNull, null)).isNull(); assertThat(dateTimePlusArray(localDateTimeNull, minutesEmpty)).isNull(); assertThat(dateTimePlusArray(localDateTimeNull, minutes)).isNull(); assertThat(dateTimePlusArray(localDateTimeNow, null)).isNull(); assertThat(dateTimePlusArray(localDateTimeNow, minutesEmpty)).isNull(); } @Test public void test013_DateTimeSort() { // LocalDateTime is immutable LocalDateTime now = LocalDateTime.parse("2019-03-13T16:00:00"); Set<LocalDateTime> setDateTime = dateTimePlusArray(now, new int[] { 15, 15, -15, 20, 5, -30 }); // +15min x 2 List<LocalDateTime> listDateTime = new ArrayList<>(setDateTime); Collections.sort(listDateTime); assertThat(setDateTime).containsOnlyOnce(LocalDateTime.parse("2019-03-13T16:15:00")); // only one +15min assertThat(listDateTime).isSorted(); assertThat(listDateTime).containsAll(setDateTime); } @Test public void test014_FormetStyles() { LocalDate localDate = LocalDate.of(2019, 7, 11); // jueves 11 de julio de 2019 String localDateFull = DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL).format(localDate); // 11 de julio de 2019 String localDateLong = DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG).format(localDate); // 11-jul-2019 String localDateMedium = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM).format(localDate); // 11/07/19 String localDateShort = DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT).format(localDate); ZonedDateTime zonedDateTime = ZonedDateTime.of(localDate, LocalTime.of(16, 05, 00), ZoneId.of("Europe/Madrid")); String zonedDateFull = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL).format(zonedDateTime); // jueves 11 de julio de 2019 16H05' CEST // this is ofLocalizedDate LocalDate retLocalDate = LocalDate .from(DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL).parse("jueves 11 de julio de 2019")); // and this is ofLacalizedDateTime ZonedDateTime retZonedDate = ZonedDateTime.from(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL) .parse("jueves 11 de julio de 2019 16H05' CEST")); assertThat(localDate).isEqualTo(retLocalDate); assertThat(zonedDateTime).isEqualTo(retZonedDate); String data = String.format("LocalDate: %s\nFull: %s\nLong: %s\nMedium: %s\nShort: %s\n", localDate, localDateFull, localDateLong, localDateMedium, localDateShort); data += String.format("ZonedDateTime: %s\nFull: %s\n", zonedDateTime, zonedDateFull); logger.info(data); } @Test public void test015_FixedClock() { String inst_expected = "2009-03-17T16:00:00Z"; Clock clock = Clock.fixed(Instant.parse(inst_expected), ZoneId.of("UTC")); Instant instant = Instant.now(clock); assertThat(instant.toString()).isEqualTo(inst_expected); } @Test public void test016_OverrideClockForTestingWithMock() { String inst1_expected = "2009-03-17T16:00:00Z"; String inst2_expected = "2009-03-17T16:00:25Z"; // +25 seg. String inst3_expected = "2009-03-17T16:00:50Z"; // +25 seg. Instant inst1 = Instant.parse(inst1_expected); Instant inst2 = inst1.plusSeconds(25); Instant inst3 = inst2.plusSeconds(25); when(mock_Clock.instant()).thenReturn(inst1, inst2, inst3); assertThat(mock_Clock.instant().toString()).isEqualTo(inst1_expected); assertThat(mock_Clock.instant().toString()).isEqualTo(inst2_expected); assertThat(mock_Clock.instant().toString()).isEqualTo(inst3_expected); } }
package org.epigeek.lguhc; import org.bukkit.GameMode; import org.bukkit.attribute.Attribute; import org.bukkit.entity.Player; import org.bukkit.potion.PotionEffect; import org.epigeek.lguhc.roles.A_Role; import org.epigeek.lguhc.roles.State; public class LgPlayer { private Player player; private A_Role role; private State state; LgPlayer(Player player) { this.player = player; this.role = null; this.state = State.ALIVE; } public Player getPlayer() { return player; } public A_Role getRole() { return role; } public void setRole(A_Role role) { this.role = role; } public void clearAllEffect() { for (PotionEffect effect : player.getActivePotionEffects()) player.removePotionEffect(effect.getType()); } public void setup() { clearAllEffect(); player.setGameMode(GameMode.SURVIVAL); player.getAttribute(Attribute.GENERIC_MAX_HEALTH).setBaseValue(20); player.setHealth(20); player.setFoodLevel(20); } public void kill() { } public State getState() { return state; } public void setState(State state) { this.state = state; } }
package com.sirma.itt.javacourse.objects.task2.shapes.polyline; import com.sirma.itt.javacourse.objects.task2.shapes.Figure; import com.sirma.itt.javacourse.objects.task2.shapes.Point; /** * Segment class AKA Line. * * @author simeon */ public class Segment extends Figure { private Point a; private Point b; /** * Constructor for segment. * * @param a * the first point * @param b * the second point */ public Segment(Point a, Point b) { super("Segment"); // TODO Auto-generated constructor stub } @Override public void draw() { // TODO Draw a line } /** * Getter method for a. * * @return the a */ public Point getA() { return a; } /** * Setter method for a. * * @param a * the a to set */ public void setA(Point a) { this.a = a; } /** * Getter method for b. * * @return the b */ public Point getB() { return b; } /** * Setter method for b. * * @param b * the b to set */ public void setB(Point b) { this.b = b; } }
package com.developworks.jvmcode; /** * <p>Title: newarray</p> * <p>Description: 创建一个数组</p> * <p>Author: ouyp </p> * <p>Date: 2018-05-20 16:12</p> */ public class newarray { public void newarray() { int[] arr = new int[10]; } } /** * public void newarray(); * Code: * 0: bipush 10 * 2: newarray int * 4: astore_1 * 5: return */
package com.skfeng.gradesign; import java.util.ArrayList; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Environment; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.skfeng.ndk.*; public class MainActivity extends Activity implements View.OnClickListener{ private ArrayList<FileInfo> choosed_files;//选择的文件的信息 private Button choose_file_button; private Button generate_fea_button; private Button cluster_button; private Button freq_button; private Button lda_button; private Button copy_button; private Intent fileChooserIntent ; private static final int REQUEST_CODE = 1; //请求码返回文件信息的请求码 public static final String EXTRA_FILE_CHOOSER = "file_chooser"; private static final String TAG="MainActivity"; private TextView show_choose_file; @Override protected void onCreate(Bundle savedInstanceState) { ExtractSiftFea.test1();//请开始工作吧! super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); choose_file_button=(Button)findViewById(R.id.select_file_button); show_choose_file=(TextView) findViewById(R.id.Test_chooses_files); generate_fea_button=(Button)findViewById(R.id.generate_sift_fea_button); generate_fea_button.setEnabled(false);//一开始先设置为不可用 cluster_button=(Button)findViewById(R.id.cluster_button); cluster_button.setEnabled(false); freq_button=(Button)findViewById(R.id.freq_button); freq_button.setEnabled(false); lda_button=(Button)findViewById(R.id.lda_button); copy_button=(Button)findViewById(R.id.copy_button); lda_button.setEnabled(false); copy_button.setEnabled(false); //show_choose_file choose_file_button.setOnClickListener(this); generate_fea_button.setOnClickListener(this);//忘了这一步造成了大麻烦 cluster_button.setOnClickListener(this); freq_button.setOnClickListener(this); lda_button.setOnClickListener(this); copy_button.setOnClickListener(this); fileChooserIntent=new Intent(this,fileChooserActivity.class); } @Override public void onClick(View v) { // TODO Auto-generated method stub System.out.println("调用public void onClick(View v)"); switch(v.getId()){ case R.id.select_file_button : if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) startActivityForResult(fileChooserIntent , REQUEST_CODE); else toast(getText(R.string.sdcard_unmonted_hint)); break; case R.id.generate_sift_fea_button: System.out.println("下面开始调用ExtractSiftFea.Gen_Sift_fea()"); Log.v(TAG, "下面开始调用ExtractSiftFea.Gen_Sift_fea()"); ExtractSiftFea.Gen_Sift_fea(); System.out.println("调用ExtractSiftFea.Gen_Sift_fea()完毕"); cluster_button.setEnabled(true);//可以聚类了 break; case R.id.cluster_button: System.out.println("下面开始调用ExtractSiftFea.cluster_kmeans()"); Log.v(TAG, "下面开始调用ExtractSiftFea.cluster_kmeans()"); ExtractSiftFea.cluster_kmeans(); System.out.println("调用ExtractSiftFea.cluster_kmeans()完毕"); freq_button.setEnabled(true); break; case R.id.freq_button: System.out.println("ExtractSiftFea.freq_count()"); Log.v(TAG, "下面开始调用ExtractSiftFea.freq_count()"); ExtractSiftFea.freq_count(); System.out.println("调用ExtractSiftFea.freq_count()完毕"); lda_button.setEnabled(true); break; case R.id.lda_button: System.out.println("ExtractSiftFea.final_lda()"); Log.v(TAG, "下面开始调用ExtractSiftFea.final_lda()"); ExtractSiftFea.final_lda(); System.out.println("调用ExtractSiftFea.final_lda()完毕"); copy_button.setEnabled(true); break; case R.id.copy_button: System.out.println("ExtractSiftFea.Cre_res()"); Log.v(TAG, "下面开始调用ExtractSiftFea.Cre_res()"); ExtractSiftFea.Cre_res(); System.out.println("调用ExtractSiftFea.Cre_res()完毕"); break; default : break ; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (1==requestCode&&RESULT_OK==resultCode) { finish_test(); generate_fea_button.setEnabled(true);//可以生成sift.fea文件了 } } private void toast(CharSequence hint){ Toast.makeText(this, hint , Toast.LENGTH_SHORT).show(); } private void finish_test() { for (FileInfo f_temp : Select_file_set.selected_files) { Log.v(MainActivity.TAG,f_temp.getFileName()); show_choose_file.append(f_temp.getFileName() + "\n"); } } }
package se.rtz.beans; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import org.junit.Assert; import org.junit.Test; public class BeanFactoryTest { @Test public void testNormal() { TestBean testBean = BeanFactory.createBean(TestBean.class); Assert.assertNull(testBean.getA()); testBean.setA("a"); Assert.assertEquals("a", testBean.getA()); Assert.assertEquals("TestBean [A=a]", testBean.toString()); int aHashCode = testBean.hashCode(); TestBean anotherBean = BeanFactory.createBean(TestBean.class); anotherBean.setA("a"); int anotherHashCode = anotherBean.hashCode(); Assert.assertEquals(aHashCode, anotherHashCode); Assert.assertEquals(testBean, anotherBean); anotherBean.setA("b"); Assert.assertNotEquals(testBean, anotherBean); boolean[] setterWasCalled = { false }; PropertyChangeListener listener = new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { setterWasCalled[0] = true; } }; testBean.addPropertyChangeListener(listener); testBean.setA("b"); Assert.assertTrue(setterWasCalled[0]); setterWasCalled[0] = false; testBean.removePropertyChangeListener(listener); testBean.setA("a"); Assert.assertFalse(setterWasCalled[0]); } @Test public void testNaive() { TestBean testBean = new TestBeanImpl(); Assert.assertNull(testBean.getA()); testBean.setA("a"); Assert.assertEquals("a", testBean.getA()); Assert.assertEquals("TestBean [a=a]", testBean.toString()); int aHashCode = testBean.hashCode(); TestBean anotherBean = new TestBeanImpl(); anotherBean.setA("a"); int anotherHashCode = anotherBean.hashCode(); Assert.assertEquals(aHashCode, anotherHashCode); Assert.assertEquals(testBean, anotherBean); anotherBean.setA("b"); Assert.assertNotEquals(testBean, anotherBean); boolean[] setterWasCalled = { false }; testBean.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { setterWasCalled[0] = true; } }); testBean.setA("b"); Assert.assertTrue(setterWasCalled[0]); } }
package com.spring.professional.exam.tutorial.module03.question26.service; import java.sql.Date; import javax.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.spring.professional.exam.tutorial.module03.question26.dao.EmployeDao; import com.spring.professional.exam.tutorial.module03.question26.ds.Employee; import com.spring.professional.exam.tutorial.module03.question26.ds.EmployeeKey; @Service public class EmployeeService { @Autowired private EmployeDao employeeDao; //@Transactional public void saveEmployee() { System.out.println("Saving employee..."); employeeDao.save(new Employee(new EmployeeKey("John", "Doe"), "John.Doe@corp.com", "555-55-55", Date.valueOf("2019-06-05"), 70000)); System.out.println("Employee saved"); //System.out.println("Throwing unchecked exception to rollback while method is annotated with @Transactional annotation ...."); //throw new IllegalArgumentException(); } public void listEmployee() { System.out.println("Searching for John Doe employee..."); employeeDao.findById(new EmployeeKey("John", "Doe")).ifPresent(System.out::println); } }
package props; public interface PersistentProps { public PersistentProps copy(String name); public boolean equals(Object obj); public String getName(); public void setName(String name); public String getProp(); public void setProp(String value); public void deleteProp(); }
package com.esum.common.soappull.message; import java.io.Serializable; public class PullConstants implements Serializable { /** NameSpace 2*/ public static String NS2 = "ecvan"; /** NameSpace 2 의 URL */ public static String NS2_URL = "http://soap.esumtech.com/xsd/ecvan"; /** NameSpace 2 의 스키마 저장 경로 */ public static String NS2_LOCATION = "http://soap.esumtech.com/xsd/ecvan http://soap.esumtech.com/xsd/ecvan.xsd"; /** 파일 송신 코드 */ public static final String SND_REQ_CODE = "11"; /** 파일 송신 응답 코드 */ public static final String SND_RESP_CODE = "12"; /** 파일 수신 통보 코드 */ public static final String RCV_REQ_CODE = "41"; /** 파일 수신 코드 */ public static final String RCV_RESP_CODE = "42"; /** 파일 수신완료 요청 코드 */ public static final String COMP_REQ_CODE = "43"; /** 파일 수신완료 응답 코드 */ public static final String COMP_RESP_CODE = "44"; // HTTP 사용 정보 public static final String HTTP_ACTION = "HttpAction"; // HTTP_ACTION의 value public static final String HTTP_ACTION_BIG = "H1"; public static final String HTTP_ACTION_SMALL = "H2"; public static final String RESP_OK = "OK"; public static final String RESP_NO = "NO"; public static final String SEP = "|"; }
package com.gxjtkyy.standardcloud.api.service; import com.gxjtkyy.standardcloud.common.constant.DocTemplate; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.mongodb.core.query.Update; import org.springframework.test.context.junit4.SpringRunner; /** * @Package com.gxjtkyy.service * @Author lizhenhua * @Date 2018/6/11 18:35 */ @SpringBootTest @RunWith(SpringRunner.class) public class TemplateServiceTest { @Autowired private MongoTemplate mongoTemplate; @Test public void getTemplateById() throws Exception { } @Test public void update() throws Exception{ Query query = Query.query(Criteria.where("_id").is("d6c6c2d49f6445708a2ab6c51cb12ee8")); Update update = Update.update("content.attach", "MongoTemplate"); mongoTemplate.upsert(query, update, DocTemplate.PRO_STAND.getTableName()); } }
package com.globalmediasoft.android.core; import android.app.Activity; import android.content.SharedPreferences; import android.content.res.Resources; public class GMSCoreSettings { protected static Activity activity; protected static String appSIDSettings; protected static SharedPreferences getSettingsPreference() { return activity.getSharedPreferences(appSIDSettings, 0); } public static Activity getActivity() { return activity; } public static void setActivity(Activity activity) { GMSCoreSettings.activity = activity; } public static Resources getResources() { if (activity != null) { return activity.getResources(); } return null; } public static void setInt(String key, int value) { getSettingsPreference().edit().putInt(key, value).commit(); } public static void setFloat(String key, float value) { getSettingsPreference().edit().putFloat(key, value).commit(); } public static void setLong(String key, long value) { getSettingsPreference().edit().putLong(key, value).commit(); } public static void setBoolean(String key, boolean value) { getSettingsPreference().edit().putBoolean(key, value).commit(); } public static void setString(String key, String value) { getSettingsPreference().edit().putString(key, value).commit(); } public static void set(String key, String value) { setString(key, value); } public static int getInt(String key, int defValue) { return getSettingsPreference().getInt(key, defValue); } public static float getFloat(String key, float defValue) { return getSettingsPreference().getFloat(key, defValue); } public static long getLong(String key, long defValue) { return getSettingsPreference().getLong(key, defValue); } public static boolean getBoolean(String key, boolean defValue) { return getSettingsPreference().getBoolean(key, defValue); } public static String getString(String key, String defValue) { return getSettingsPreference().getString(key, defValue); } public static String get(String key, String defValue) { return getString(key, defValue); } }
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.http.converter; import java.io.ByteArrayInputStream; import java.lang.reflect.Type; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.junit.jupiter.api.Test; import org.springframework.core.ParameterizedTypeReference; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.core.io.support.ResourceRegion; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpRange; import org.springframework.http.MediaType; import org.springframework.util.StringUtils; import org.springframework.web.testfixture.http.MockHttpOutputMessage; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; /** * Test cases for {@link ResourceRegionHttpMessageConverter} class. * * @author Brian Clozel */ public class ResourceRegionHttpMessageConverterTests { private final ResourceRegionHttpMessageConverter converter = new ResourceRegionHttpMessageConverter(); @Test public void canReadResource() { assertThat(converter.canRead(Resource.class, MediaType.APPLICATION_OCTET_STREAM)).isFalse(); assertThat(converter.canRead(Resource.class, MediaType.ALL)).isFalse(); assertThat(converter.canRead(List.class, MediaType.APPLICATION_OCTET_STREAM)).isFalse(); assertThat(converter.canRead(List.class, MediaType.ALL)).isFalse(); } @Test public void canWriteResource() { assertThat(converter.canWrite(ResourceRegion.class, null, MediaType.APPLICATION_OCTET_STREAM)).isTrue(); assertThat(converter.canWrite(ResourceRegion.class, null, MediaType.ALL)).isTrue(); assertThat(converter.canWrite(Object.class, null, MediaType.ALL)).isFalse(); } @Test public void canWriteResourceCollection() { Type resourceRegionList = new ParameterizedTypeReference<List<ResourceRegion>>() {}.getType(); assertThat(converter.canWrite(resourceRegionList, null, MediaType.APPLICATION_OCTET_STREAM)).isTrue(); assertThat(converter.canWrite(resourceRegionList, null, MediaType.ALL)).isTrue(); assertThat(converter.canWrite(List.class, MediaType.APPLICATION_OCTET_STREAM)).isFalse(); assertThat(converter.canWrite(List.class, MediaType.ALL)).isFalse(); Type resourceObjectList = new ParameterizedTypeReference<List<Object>>() {}.getType(); assertThat(converter.canWrite(resourceObjectList, null, MediaType.ALL)).isFalse(); } @Test public void shouldWritePartialContentByteRange() throws Exception { MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); Resource body = new ClassPathResource("byterangeresource.txt", getClass()); ResourceRegion region = HttpRange.createByteRange(0, 5).toResourceRegion(body); converter.write(region, MediaType.TEXT_PLAIN, outputMessage); HttpHeaders headers = outputMessage.getHeaders(); assertThat(headers.getContentType()).isEqualTo(MediaType.TEXT_PLAIN); assertThat(headers.getContentLength()).isEqualTo(6L); assertThat(headers.get(HttpHeaders.CONTENT_RANGE)).hasSize(1); assertThat(headers.get(HttpHeaders.CONTENT_RANGE).get(0)).isEqualTo("bytes 0-5/39"); assertThat(outputMessage.getBodyAsString(StandardCharsets.UTF_8)).isEqualTo("Spring"); } @Test public void shouldWritePartialContentByteRangeNoEnd() throws Exception { MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); Resource body = new ClassPathResource("byterangeresource.txt", getClass()); ResourceRegion region = HttpRange.createByteRange(7).toResourceRegion(body); converter.write(region, MediaType.TEXT_PLAIN, outputMessage); HttpHeaders headers = outputMessage.getHeaders(); assertThat(headers.getContentType()).isEqualTo(MediaType.TEXT_PLAIN); assertThat(headers.getContentLength()).isEqualTo(32L); assertThat(headers.get(HttpHeaders.CONTENT_RANGE)).hasSize(1); assertThat(headers.get(HttpHeaders.CONTENT_RANGE).get(0)).isEqualTo("bytes 7-38/39"); assertThat(outputMessage.getBodyAsString(StandardCharsets.UTF_8)).isEqualTo("Framework test resource content."); } @Test public void partialContentMultipleByteRanges() throws Exception { MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); Resource body = new ClassPathResource("byterangeresource.txt", getClass()); List<HttpRange> rangeList = HttpRange.parseRanges("bytes=0-5,7-15,17-20,22-38"); List<ResourceRegion> regions = new ArrayList<>(); for(HttpRange range : rangeList) { regions.add(range.toResourceRegion(body)); } converter.write(regions, MediaType.TEXT_PLAIN, outputMessage); HttpHeaders headers = outputMessage.getHeaders(); assertThat(headers.getContentType().toString()).startsWith("multipart/byteranges;boundary="); String boundary = "--" + headers.getContentType().toString().substring(30); String content = outputMessage.getBodyAsString(StandardCharsets.UTF_8); String[] ranges = StringUtils.tokenizeToStringArray(content, "\r\n", false, true); assertThat(ranges[0]).isEqualTo(boundary); assertThat(ranges[1]).isEqualTo("Content-Type: text/plain"); assertThat(ranges[2]).isEqualTo("Content-Range: bytes 0-5/39"); assertThat(ranges[3]).isEqualTo("Spring"); assertThat(ranges[4]).isEqualTo(boundary); assertThat(ranges[5]).isEqualTo("Content-Type: text/plain"); assertThat(ranges[6]).isEqualTo("Content-Range: bytes 7-15/39"); assertThat(ranges[7]).isEqualTo("Framework"); assertThat(ranges[8]).isEqualTo(boundary); assertThat(ranges[9]).isEqualTo("Content-Type: text/plain"); assertThat(ranges[10]).isEqualTo("Content-Range: bytes 17-20/39"); assertThat(ranges[11]).isEqualTo("test"); assertThat(ranges[12]).isEqualTo(boundary); assertThat(ranges[13]).isEqualTo("Content-Type: text/plain"); assertThat(ranges[14]).isEqualTo("Content-Range: bytes 22-38/39"); assertThat(ranges[15]).isEqualTo("resource content."); } @Test public void partialContentMultipleByteRangesInRandomOrderAndOverlapping() throws Exception { MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); Resource body = new ClassPathResource("byterangeresource.txt", getClass()); List<HttpRange> rangeList = HttpRange.parseRanges("bytes=7-15,0-5,17-20,20-29"); List<ResourceRegion> regions = new ArrayList<>(); for(HttpRange range : rangeList) { regions.add(range.toResourceRegion(body)); } converter.write(regions, MediaType.TEXT_PLAIN, outputMessage); HttpHeaders headers = outputMessage.getHeaders(); assertThat(headers.getContentType().toString()).startsWith("multipart/byteranges;boundary="); String boundary = "--" + headers.getContentType().toString().substring(30); String content = outputMessage.getBodyAsString(StandardCharsets.UTF_8); String[] ranges = StringUtils.tokenizeToStringArray(content, "\r\n", false, true); assertThat(ranges[0]).isEqualTo(boundary); assertThat(ranges[1]).isEqualTo("Content-Type: text/plain"); assertThat(ranges[2]).isEqualTo("Content-Range: bytes 7-15/39"); assertThat(ranges[3]).isEqualTo("Framework"); assertThat(ranges[4]).isEqualTo(boundary); assertThat(ranges[5]).isEqualTo("Content-Type: text/plain"); assertThat(ranges[6]).isEqualTo("Content-Range: bytes 0-5/39"); assertThat(ranges[7]).isEqualTo("Spring"); assertThat(ranges[8]).isEqualTo(boundary); assertThat(ranges[9]).isEqualTo("Content-Type: text/plain"); assertThat(ranges[10]).isEqualTo("Content-Range: bytes 17-20/39"); assertThat(ranges[11]).isEqualTo("test"); assertThat(ranges[12]).isEqualTo(boundary); assertThat(ranges[13]).isEqualTo("Content-Type: text/plain"); assertThat(ranges[14]).isEqualTo("Content-Range: bytes 20-29/39"); assertThat(ranges[15]).isEqualTo("t resource"); } @Test // SPR-15041 public void applicationOctetStreamDefaultContentType() throws Exception { MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); ClassPathResource body = mock(); given(body.getFilename()).willReturn("spring.dat"); given(body.contentLength()).willReturn(12L); given(body.getInputStream()).willReturn(new ByteArrayInputStream("Spring Framework".getBytes())); HttpRange range = HttpRange.createByteRange(0, 5); ResourceRegion resourceRegion = range.toResourceRegion(body); converter.write(Collections.singletonList(resourceRegion), null, outputMessage); assertThat(outputMessage.getHeaders().getContentType()).isEqualTo(MediaType.APPLICATION_OCTET_STREAM); assertThat(outputMessage.getHeaders().getFirst(HttpHeaders.CONTENT_RANGE)).isEqualTo("bytes 0-5/12"); assertThat(outputMessage.getBodyAsString(StandardCharsets.UTF_8)).isEqualTo("Spring"); } }
package com.example.demo.security; public class IncorrectUsernameOrPasswordException extends RuntimeException{ public IncorrectUsernameOrPasswordException() { super("Incorrect username or password"); } }
package com.actionModeViewModel.recyclerFragment; import android.graphics.Color; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.actionmode.viewmodel.R; import com.actionModeViewModel.ItemModel; import com.actionModeViewModel.recyclerFragment.RecyclerViewAdapter.RecyclerViewHolder; import java.util.List; public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewHolder> { private List<ItemModel> mItemModels; RecyclerViewAdapter() { } void updateData(List<ItemModel> itemModels) { this.mItemModels = itemModels; notifyDataSetChanged(); } public void toggleSelection(int position) { mItemModels.get(position).toggle(); notifyItemChanged(position); } @Override public RecyclerViewHolder onCreateViewHolder( ViewGroup viewGroup, int viewType) { LayoutInflater mInflater = LayoutInflater.from(viewGroup.getContext()); ViewGroup mainGroup = (ViewGroup) mInflater.inflate(R.layout.item_row, viewGroup, false); return new RecyclerViewHolder(mainGroup); } @Override public void onBindViewHolder(RecyclerViewHolder holder, int position) { //Setting text over text view holder.title.setText(mItemModels.get(position).getTitle()); holder.sub_title.setText(mItemModels.get(position).getSubTitle()); holder.itemView.setBackgroundColor( mItemModels.get(position).isSelected() ? Color.LTGRAY : Color.TRANSPARENT); } @Override public int getItemCount() { return (null != mItemModels ? mItemModels.size() : 0); } public ItemModel getItem(int position) { return mItemModels.get(position); } class RecyclerViewHolder extends RecyclerView.ViewHolder { TextView title, sub_title; RecyclerViewHolder(View view) { super(view); this.title = view.findViewById(R.id.title); this.sub_title = view.findViewById(R.id.sub_title); } } }
package ResponseTimeBenchmarking; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.time.Instant; import javax.swing.JTextArea; public class Connection extends Thread { private final String url; private final int id; private final int run; private ResultArray result; private GUI gui; public Connection(int id, int run, ResultArray result, String url, GUI gui) { this.url = url; this.id = id; this.run = run; this.result = result; this.gui = gui; } @Override public void run() { openConnection(this.url); } public void openConnection(String url) { String inputLine; try { URL urlObj = new URL(url); HttpURLConnection httpCon = (HttpURLConnection) urlObj.openConnection(); httpCon.setRequestMethod("GET"); long lStartTime = Instant.now().toEpochMilli(); httpCon.connect(); final int responseCode = httpCon.getResponseCode(); BufferedReader in = new BufferedReader(new InputStreamReader(httpCon.getInputStream())); StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { } in.close(); long lEndTime = Instant.now().toEpochMilli(); long output = lEndTime - lStartTime; result.add(output); this.gui.textOut.append("Thread "+id+" - Run "+run+" : Sending 'GET' Request To: "+url+" - Elapsed Time : "+output+" ms\n"); } catch (Exception ex) { this.gui.labelErrText.setText(ex.getMessage()); this.gui.dialogOut.setVisible(true); } } }
package com.szakdolgozat.service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.util.Pair; import org.springframework.stereotype.Service; import com.szakdolgozat.components.ShoppingCart; import com.szakdolgozat.domain.Product; @Service public class ShoppingCartServiceImpl implements ShoppingCartService { private static final Double CARGO_SIZE = 14900000D; private ProductService ps; private OrderService os; private DeliveryService ds; private HashMap<String, ShoppingCart> userCartMap; private static final Logger LOG = LoggerFactory.getLogger(ShoppingCartServiceImpl.class); @Autowired public ShoppingCartServiceImpl(ProductService ps, OrderService os, DeliveryService ds) { this.ps = ps; this.os = os; this.ds = ds; this.userCartMap = new HashMap<String, ShoppingCart>(); } @Override public int addToCart(long productId, String email) { Product product = ps.getProductForCart(productId); if(product != null) { ShoppingCart cart = getCart(email); cart.addToCart(product); return 1; } return 0; } @Override public void emptyCart(String email) { ShoppingCart cart = getCart(email); cart.emptyCart(); } @Override public ShoppingCart getCart(String email) { return getOrCreateCart(email); } private boolean checkIfUserHasCar(String email) { if(userCartMap.containsKey(email)) return true; return false; } private void addCartForUser(String email) { userCartMap.put(email, new ShoppingCart()); } private ShoppingCart getOrCreateCart(String email) { if(!checkIfUserHasCar(email)) addCartForUser(email); return userCartMap.get(email); } @Override public String removeFromCart(long productId, String email) { ShoppingCart cart = userCartMap.get(email); Product product = ps.getProductById(productId); if(product != null) { Object result = cart.removeProduct(product); if(result != null) { return "ok"; } else { LOG.error("Couldn't remove product (" + productId + ")"); } } LOG.error("Couldn't find product (" + productId + ")"); return "error"; } @Override public String changeAmount(long productId, int quantity, String email) { ShoppingCart cart = getCart(email); Product product = ps.getProductById(productId); if(product != null) { cart.addToCart(product, quantity); return "ok"; } LOG.error("Couldn't change product's amount"); return "error"; } @Override public String makeOrders(String email) { ShoppingCart cart = getCart(email); if(!cart.getItems().isEmpty()) { String result = ""; List<Pair<Product, Integer>> missingList = os.getMissingProductList(cart.getItems()); if(missingList.isEmpty()) { double sumVolume = cart.sumVolume(); if(sumVolume > CARGO_SIZE) { List<HashMap<Product, Integer>> carts = takeCartIntoPieces(cart); for (HashMap<Product, Integer> subCart : carts) { os.makeAnOrder(email,subCart); } cart.emptyCart(); return "A rendelés nem fér egy kocsiban, ezért " + carts.size() + " különböző fuvarral lesz kiszállítva."; } else { result = os.makeAnOrder(email, cart.getItems()); if(result.equals("ok")) { cart.emptyCart(); } } return "ok"; } else { result += "MISSING"; for (Pair<Product, Integer> pair : missingList) { result += ";" + pair.getFirst().getName() + ":" + pair.getSecond() + ":" + pair.getFirst().getId() ; } return result; } } LOG.error("The cart is empty"); return "Nincs semmi a kocsiban"; } /** * Takes the {@link ShoppingCart}'s items into more orders. * @param cart : the ShoppingCart to be sorted into more orders * @return List of orders to be created */ private List<HashMap<Product, Integer>> takeCartIntoPieces(ShoppingCart cart) { List<HashMap<Product, Integer>> orderList = new ArrayList<HashMap<Product, Integer>>(); Map<Product, Integer> itemsInActualCart = cart.getItems(); Set<Product> productsInCart = itemsInActualCart.keySet(); List<Double> spaceLeft = new ArrayList<Double>(); //at least 2 orders orderList.add(new HashMap<Product, Integer>()); orderList.add(new HashMap<Product, Integer>()); spaceLeft.add(CARGO_SIZE); spaceLeft.add(CARGO_SIZE); double volumeOfProductInCart = 0; for(Product product : productsInCart) { volumeOfProductInCart = cart.getVolumeOfProduct(product); if(volumeOfProductInCart > CARGO_SIZE) { //take product into more "orders" takeProductIntoPieces(orderList,spaceLeft,volumeOfProductInCart,product,itemsInActualCart.get(product)); } else { addToOrder(orderList,spaceLeft,volumeOfProductInCart,product,itemsInActualCart.get(product)); } } return orderList; } /** * Takes the <i>amountOfProd</i> {@link Product} form the cart into more orders<br/> * as it's size would be too large for one order. * Adds the <<i>product</i> to the <i>orderList</i> and calls {@link #addToOrder} * @param orderList : the list of orders where the product will be added * @param spaceLeft : space left for new products in orders of orderList * @param volumeOfProductInCart : the volume taken by the products that wanted to be placed * @param product : {@link Product} to be placed in an order * @param amountOfProd */ private void takeProductIntoPieces(List<HashMap<Product, Integer>> orderList, List<Double> spaceLeft, double volumeOfProductInCart, Product product, Integer amountOfProd) { double volumeOfOneProduct = product.getVolume(); int maxNumberOfProductsInOneOrder = new Double(CARGO_SIZE / volumeOfOneProduct).intValue(); int productLeftForSorting = amountOfProd; int amountOfProductToOrder = 0; int numberOfOrdersToMake = Math.floorDiv(amountOfProd, maxNumberOfProductsInOneOrder); if(amountOfProd % maxNumberOfProductsInOneOrder != 0) numberOfOrdersToMake++; for(int i = 0; i < numberOfOrdersToMake; i++) { if(productLeftForSorting - maxNumberOfProductsInOneOrder >= 0) { productLeftForSorting -= maxNumberOfProductsInOneOrder; amountOfProductToOrder = maxNumberOfProductsInOneOrder; } else { amountOfProductToOrder = productLeftForSorting; } addToOrder(orderList, spaceLeft, volumeOfOneProduct * amountOfProductToOrder, product, amountOfProductToOrder); } } /** * Adds the product to an "Order" in orderList based on the volume(spaceLeft) left in that order<br/> * If there is not enough space in orders for the whole amount of product than make a new order * @param orderList : the list of orders where the product will be added * @param spaceLeft : space left for new products in orders of orderList * @param volumeOfProductInCart : the volume taken by the products that wanted to be placed * @param product : {@link Product} to be placed in an order * @param amountOfProd */ private void addToOrder(List<HashMap<Product, Integer>> orderList, List<Double> spaceLeft, double volumeOfProductInCart, Product product, int amountOfProd) { HashMap<Product, Integer> order; boolean placed = false; for (int i = 0; i < spaceLeft.size(); i++) { if(spaceLeft.get(i) - volumeOfProductInCart >= 0) {//if the order fit in an order, put in it spaceLeft.set(i, spaceLeft.get(i) - volumeOfProductInCart); orderList.get(i).put(product, amountOfProd); placed = true; break; } } if(!placed) {//if the product doesn't fit in any order than make a new one order = new HashMap<Product, Integer>(); order.put(product, amountOfProd); orderList.add(order); spaceLeft.add(CARGO_SIZE - volumeOfProductInCart); } } }
/* * Copyright (c) 2018, WSO2 LLC. (http://www.wso2.com). * * WSO2 LLC. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.identity.user.export.core.internal.service.impl; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import org.osgi.service.component.annotations.ReferenceCardinality; import org.osgi.service.component.annotations.ReferencePolicy; import org.wso2.carbon.identity.core.util.IdentityUtil; import org.wso2.carbon.identity.user.export.core.UserExportException; import org.wso2.carbon.identity.user.export.core.dto.UserInformationDTO; import org.wso2.carbon.identity.user.export.core.service.UserInformationProvider; import org.wso2.carbon.user.api.Claim; import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreManager; import org.wso2.carbon.user.core.UserRealm; import org.wso2.carbon.user.core.service.RealmService; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** * Provide basic information of user. */ @Component( name = "org.wso2.carbon.user.export.basic", immediate = true, service = UserInformationProvider.class ) public class BasicUserInformationProvider extends AbstractUserInformationProvider { private static final Log log = LogFactory.getLog(BasicUserInformationProvider.class); protected static final String CHALLENGE_QUESTION_URIS_CLAIM = "http://wso2.org/claims/challengeQuestionUris"; protected static final String QUESTION_CHALLENGE_SEPARATOR = "Recovery.Question.Password.Separator"; protected static final String DEFAULT_CHALLENGE_QUESTION_SEPARATOR = "!"; protected RealmService realmService; @Override public UserInformationDTO getRetainedUserInformation(String username, String userStoreDomain, int tenantId) throws UserExportException { Claim[] userClaimValues; try { userClaimValues = getUserStoreManager(tenantId, userStoreDomain).getUserClaimValues(username, null); } catch (UserStoreException e) { throw new UserExportException("Error while retrieving the user information.", e); } if (userClaimValues != null) { Map<String, String> attributes = Arrays.stream(userClaimValues).collect(Collectors.toMap (Claim::getClaimUri, Claim::getValue)); List<String> challengeQuestionUris = getChallengeQuestionUris(attributes); if (challengeQuestionUris.size() > 0) { for (String challengeQuestionUri : challengeQuestionUris) { attributes.remove(challengeQuestionUri); } } attributes.remove(CHALLENGE_QUESTION_URIS_CLAIM); return new UserInformationDTO(attributes); } else { return new UserInformationDTO(); } } @Override public String getType() { return "basic"; } protected List<String> getChallengeQuestionUris(Map<String, String> attributes) { String challengeQuestionUrisClaim = attributes.get(CHALLENGE_QUESTION_URIS_CLAIM); return getChallengeQuestionUris(challengeQuestionUrisClaim); } protected List<String> getChallengeQuestionUris(String challengeQuestionUrisClaim) { if (StringUtils.isNotEmpty(challengeQuestionUrisClaim)) { String challengeQuestionSeparator = challengeQuestionSeparator(); String[] challengeQuestionUriList = challengeQuestionUrisClaim.split(challengeQuestionSeparator); return Arrays.asList(challengeQuestionUriList); } else { return new ArrayList<>(); } } protected UserStoreManager getUserStoreManager(int tenantId, String userStoreDomain) throws UserExportException { UserStoreManager userStoreManager; try { String tenantDomain = realmService.getTenantManager().getDomain(tenantId); userStoreManager = getUserRealm(tenantDomain).getUserStoreManager().getSecondaryUserStoreManager (userStoreDomain); } catch (UserStoreException e) { throw new UserExportException("Error while retrieving the user store manager.", e); } if (log.isDebugEnabled()) { log.debug("Retrieved user store manager for tenant id: " + tenantId); } return userStoreManager; } protected UserRealm getUserRealm(String tenantDomain) throws UserExportException { UserRealm realm; try { int tenantId = realmService.getTenantManager().getTenantId(tenantDomain); realm = (UserRealm) realmService.getTenantUserRealm(tenantId); } catch (UserStoreException e) { throw new UserExportException( "Error occurred while retrieving the Realm for " + tenantDomain + " to handle claims", e); } return realm; } protected String challengeQuestionSeparator() { String challengeQuestionSeparator = IdentityUtil.getProperty(QUESTION_CHALLENGE_SEPARATOR); if (StringUtils.isEmpty(challengeQuestionSeparator)) { challengeQuestionSeparator = DEFAULT_CHALLENGE_QUESTION_SEPARATOR; } return challengeQuestionSeparator; } @Reference( name = "user.realmservice.default", service = org.wso2.carbon.user.core.service.RealmService.class, cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.DYNAMIC, unbind = "unsetRealmService") public void setRealmService(RealmService realmService) { if (log.isDebugEnabled()) { log.debug("Setting the Realm Service"); } this.realmService = realmService; } public void unsetRealmService(RealmService realmService) { if (log.isDebugEnabled()) { log.debug("Unsetting the Realm Service"); } this.realmService = null; } }
/** * Copyright (C) 2015-2016, Zhichun Wu * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.github.cassandra.jdbc.provider.datastax.codecs; import com.datastax.driver.core.DataType; import com.datastax.driver.core.ProtocolVersion; import com.datastax.driver.core.TypeCodec; import com.datastax.driver.core.exceptions.InvalidTypeException; import org.joda.time.Days; import org.joda.time.LocalDate; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import java.nio.ByteBuffer; import java.sql.Date; import static com.datastax.driver.core.CodecUtils.*; import static com.datastax.driver.core.ParseUtils.*; import static javax.xml.bind.DatatypeConverter.parseLong; import static org.joda.time.Days.daysBetween; public class JavaSqlDateCodec extends TypeCodec<Date> { public static final JavaSqlDateCodec instance = new JavaSqlDateCodec(); private static final LocalDate EPOCH = new LocalDate(1970, 1, 1); private static final DateTimeFormatter FORMATTER = DateTimeFormat.forPattern("yyyy-MM-dd").withZoneUTC(); private JavaSqlDateCodec() { super(DataType.date(), Date.class); } @Override public ByteBuffer serialize(Date value, ProtocolVersion protocolVersion) { if (value == null) return null; Days days = daysBetween(EPOCH, LocalDate.fromDateFields(value)); int unsigned = fromSignedToUnsignedInt(days.getDays()); return cint().serializeNoBoxing(unsigned, protocolVersion); } @Override public Date deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) { if (bytes == null || bytes.remaining() == 0) return null; int unsigned = cint().deserializeNoBoxing(bytes, protocolVersion); int signed = fromUnsignedToSignedInt(unsigned); return new Date(EPOCH.plusDays(signed).toDate().getTime()); } @Override public String format(Date value) { if (value == null) return "NULL"; return quote(FORMATTER.print(LocalDate.fromDateFields(value))); } @Override public Date parse(String value) { if (value == null || value.isEmpty() || value.equalsIgnoreCase("NULL")) return null; // single quotes are optional for long literals, mandatory for date patterns // strip enclosing single quotes, if any if (isQuoted(value)) { value = unquote(value); } if (isLongLiteral(value)) { long raw; try { raw = parseLong(value); } catch (NumberFormatException e) { throw new InvalidTypeException(String.format("Cannot parse date value from \"%s\"", value)); } int days; try { days = fromCqlDateToDaysSinceEpoch(raw); } catch (IllegalArgumentException e) { throw new InvalidTypeException(String.format("Cannot parse date value from \"%s\"", value)); } return new Date(EPOCH.plusDays(days).toDate().getTime()); } try { return new Date(LocalDate.parse(value, FORMATTER).toDate().getTime()); } catch (RuntimeException e) { throw new InvalidTypeException(String.format("Cannot parse date value from \"%s\"", value)); } } }
package pageObjects; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; public class LandingPage { public WebDriver driver; By signin = By.xpath("/html/body/header/div[1]/div/nav/ul/li[4]/a/span"); By title = By.xpath("//*[@id='content']/div/div/h2"); By navigationbar = By.xpath("//*[@id='homepage']/header/div[2]/div/nav/ul"); public LandingPage(WebDriver driver) { this.driver=driver; } public WebElement getlogin() { return driver.findElement(signin); } public WebElement gettitle() { return driver.findElement(title); } public WebElement getnavigationbar() { return driver.findElement(navigationbar); } }
package cn.test.enumTest.strategyEnum; import lombok.extern.slf4j.Slf4j; /** * Created by xiaoni on 2019/4/26. * 策略模式枚举类:更加安全,更加灵活;比switch case书写麻烦。 * * 根据天计算加班工资(1.5倍正常工资),周一到周五是8小时外的时间,周末都算加班。 */ @Slf4j public enum PayrollDay { MONDAY(PayType.WEEKDAY), TUESDAY(PayType.WEEKDAY), WEDNESDAY(PayType.WEEKDAY), THURSDAY(PayType.WEEKDAY), FRIDAY(PayType.WEEKDAY), SATURDAY(PayType.WEEKDAY), SUNDAY(PayType.WEEKDAY), ; private final PayType payType; PayrollDay(PayType payType) { this.payType = payType; } private enum PayType { WEEKDAY { @Override double overtimePay(double hours, double payRate) { return hours <= HOURS_PER_SHIFT ? 0 : (hours - HOURS_PER_SHIFT) * payRate / 2; } }, WEEKEND { @Override double overtimePay(double hours, double payRate) { return hours * payRate / 2; } }; //每天正常工作时长 private static final int HOURS_PER_SHIFT = 8; /** * 计算加班小时多出的那0.5部分工资 * * @param hours * @param payRate * @return */ abstract double overtimePay(double hours, double payRate); /** * 计算总应付工资 * @param hoursWorked 工作时长 * @param payRate 工资 * @return */ double pay(double hoursWorked, double payRate) { double basePay = hoursWorked * payRate; return basePay + overtimePay(hoursWorked, payRate); } } public static void main(String[] args) { double hoursWorked = 10; double payRate = 1; log.info("{}的工作时长{}的加班工资多出的部分为{}", PayrollDay.FRIDAY.toString(), hoursWorked, PayrollDay.FRIDAY.payType.overtimePay(hoursWorked, payRate)); log.info("{}的工作时长{}的应付总工资为{}", PayrollDay.FRIDAY.toString(), hoursWorked,PayrollDay.FRIDAY.payType.pay(hoursWorked, payRate)); } }
package Problem_2109; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.PriorityQueue; public class Main { static class data implements Comparable<data>{ int p, d; public data(int p, int d) { this.p = p; this.d = d; } @Override public int compareTo(data o) { if(this.d > o.d ) return -1; if(this.d < o.d ) return 1; return this.p < o.p ? 1 : -1; } } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String bf = br.readLine(); int N = Integer.parseInt(bf); data[] arr = new data[N]; for(int i = 0; i <N; i++) { bf = br.readLine(); arr[i] = new data(Integer.parseInt(bf.split(" ")[0]),Integer.parseInt(bf.split(" ")[1])); } Arrays.sort(arr); PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder()); int cnt = 0; int uniIdx = 0; for(int i = 10000 ; i >= 1; i--) { while(uniIdx < N && i <= arr[uniIdx].d) { pq.add(arr[uniIdx++].p); } if(!pq.isEmpty()) cnt += pq.poll(); } System.out.println(cnt); } }
public class WordSearch2 { static String[] words = {"india", "china"}; static char[] ch1 = words[0].toCharArray(); static char[] ch2 = words[1].toCharArray(); static char[][] myChars = { {'i','a','d','c','a'}, {'n','i','a','h','j'}, {'d','d','i','i','e'}, {'i','n','d','n','a'}, {'a','i','n','a','a'}, {'c','h','i','n','a'}}; static void forward(){ findforwardIndia(); findforwardChina(); } // static void backward(){ // findbackIndia(); // findbackChina(); // } // // static void findbackIndia(){ // int r = 0, c; // //System.out.println("Inside findindia function"); // // for(int row = 0 ; row < myChars.length ; row++){ // int flag = 0; // for(int col = myChars[row].length-1 ; col >= 0; col--){ // if(ch1[col]==myChars[row][col]){ // flag++; // r = row; // c = col; // } // } // if(flag==5){ // System.out.println("Found india"); // for(c = myChars[r].length-1; c >= 0; c--){ // if(ch1[c]==myChars[r][c]){ // System.out.println(ch1[c] + " at" + " (" + r + ","+ c + ") " ); // } // } // } // } // // } // // static void findbackChina(){ // // int r = 0, c; // //System.out.println("Inside findchina function"); // // for(int row = 0 ; row < myChars.length ; row++){ // int flag = 0; // for(int col = myChars[row].length-1; col >= 0; col--){ // if(ch2[col]==myChars[row][col]){ // flag++; // r = row; // c = col; // } // } // if(flag==5){ // System.out.println("Found china"); // for(c = myChars[r].length-1; c >=0; c--){ // if(ch2[c]==myChars[r][c]){ // System.out.println(ch2[c] + " at" + " (" + r + ","+ c + ") " ); // } // } // } // } // // } static void findforwardIndia(){ int r = 0, c; //System.out.println("Inside findindia function"); for(int row = 0 ; row < myChars.length; row++){ int flag = 0; for(int col = 0; col <myChars[row].length; col++){ if(ch1[col]==myChars[row][col]){ flag++; r = row; c = col; } } if(flag==5){ System.out.println("Found india"); for(c = 0; c <myChars[r].length; c++){ if(ch1[c]==myChars[r][c]){ System.out.println(ch1[c] + " at" + " (" + r + ","+ c + ") " ); } } } } } static void findforwardChina(){ int r = 0, c; //System.out.println("Inside findchina function"); for(int row = 0 ; row < myChars.length; row++){ int flag = 0; for(int col = 0; col <myChars[row].length; col++){ if(ch2[col]==myChars[row][col]){ flag++; r = row; c = col; } } if(flag==5){ System.out.println("Found china"); for(c = 0; c <myChars[r].length; c++){ if(ch2[c]==myChars[r][c]){ System.out.println(ch2[c] + " at" + " (" + r + ","+ c + ") " ); } } } } } public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("Trying to find india and china in forward direction"); forward(); //backward(); } }
package com.gjm.file_cloud.service; import com.gjm.file_cloud.entity.File; import org.springframework.data.domain.Page; import javax.validation.Valid; import java.util.List; public interface FileService { void addFile(@Valid File file); Page<File> getFiles(int pageNumber); List<String> getFileNames(); long getFileCount(); List<String> getFileNamesPaged(int pageNumber); File getFileByName(String name); byte[] getZippedFiles(); int getPagesCount(); void deleteFile(String name); }
import java.util.*; public class Main { static Scanner sc = new Scanner(System.in); public static void main(String[] args) { Persona cristina = new Persona(1L, "Cristina", "Lopez", 21); Persona juan = new Persona(2L, "Juan", "Fernandez", 25); Persona pedro = new Persona(3L, "Pedro", "Rodriguez", 22); Persona julia = new Persona(4L, "Julia", "Iglesias", 20); Persona carol = new Persona(5L, "Carol", "Hernandez", 19); Persona ana = new Persona(6L, "Ana", "Sanchez", 24); Persona antonio = new Persona(7L, "Antonio", "Vega", 25); Persona marc = new Persona(8L, "Marc", "Martinez", 19); SocialNetWork socialNetWork = new SocialNetWork(); socialNetWork.addPersona(cristina); socialNetWork.addPersona(juan); socialNetWork.addPersona(ana); socialNetWork.addPersona(marc); socialNetWork.addPersona(antonio); socialNetWork.addPersona(pedro); socialNetWork.addPersona(carol); socialNetWork.addPersona(julia); System.out.println("Mostrar personas por id: "); System.out.println("Id 1: " + socialNetWork.getPersona(1L)); System.out.println("Id 2: " + socialNetWork.getPersona(2L)); System.out.println("Id 3: " + socialNetWork.getPersona(3L)); System.out.println("Id 4: " + socialNetWork.getPersona(4L)); System.out.println("Id 5: " + socialNetWork.getPersona(5L)); System.out.println("Id 6: " + socialNetWork.getPersona(6L)); System.out.println("Id 7: " + socialNetWork.getPersona(7L)); System.out.println("Id 8: " + socialNetWork.getPersona(8L)); System.out.println("Mostrar persona por nombre: "); System.out.println("Nombre Cristina: " + socialNetWork.getPersona("Cristina")); System.out.println("Nombre Juan: " + socialNetWork.getPersona("Juan")); System.out.println("Nombre Ana: " + socialNetWork.getPersona("Ana")); System.out.println("Nombre Marc: " + socialNetWork.getPersona("Marc")); System.out.println("Nombre Antonio: " + socialNetWork.getPersona("Antonio")); System.out.println("Nombre Pedro: " + socialNetWork.getPersona("Pedro")); System.out.println("Nombre Carol: " + socialNetWork.getPersona("Carol")); System.out.println("Nombre Julia: " + socialNetWork.getPersona("Julia")); socialNetWork.addParejas(cristina, juan); socialNetWork.addParejas(antonio, pedro); socialNetWork.addParejas(ana, marc); socialNetWork.addAmigos(juan, antonio); socialNetWork.addAmigos(juan, marc); socialNetWork.addAmigos(pedro, cristina); socialNetWork.addAmigos(pedro, julia); socialNetWork.addAmigos(carol, julia); socialNetWork.addAmigos(ana, antonio); socialNetWork.addAmigos(ana, julia); socialNetWork.addAmigos(antonio, marc); System.out.println("1. Mostrar la pareja "); /*socialNetWork.addParejas(antonio, pedro); nos lanza una excepción y finaliza la ejecución porqué antonio ya tiene una pareja y el boolean nos devuelve cierto porqué el es una Key en el biMap de parejas */ /*socialNetWork.addParejas(pedro, antonio); nos lanza una excepción y finaliza la ejecución porqué antonio ya tiene una pareja y el boolean nos devuelve cierto porqué el es un Value en el biMap de parejas*/ System.out.println("La pareja de Cristina es: " + socialNetWork.getParejas(cristina)); System.out.println("La pareja de Juan es: " + socialNetWork.getParejas(juan)); System.out.println("La pareja de Ana es: " + socialNetWork.getParejas(ana)); System.out.println("La pareja de Marc es: " + socialNetWork.getParejas(marc)); System.out.println("La pareja de Antonio es: " + socialNetWork.getParejas(antonio)); System.out.println("La pareja de Pedro es: " + socialNetWork.getParejas(pedro)); System.out.println("La pareja de Carol es: " + socialNetWork.getParejas(carol)); System.out.println("La pareja de Julia es: " + socialNetWork.getParejas(julia)); System.out.println("2. Mostrar todos los amigos de la persona "); System.out.println("Los amigos de Cristina son : " + socialNetWork.getAmigos(cristina)); System.out.println("Los amigos de Juan son : " + socialNetWork.getAmigos(juan)); System.out.println("Los amigos de Ana son : " + socialNetWork.getAmigos(ana)); System.out.println("Los amigos de Marc son : " + socialNetWork.getAmigos(marc)); System.out.println("Los amigos de Antonio son : " + socialNetWork.getAmigos(antonio)); System.out.println("Los amigos de Pedro son : " + socialNetWork.getAmigos(pedro)); System.out.println("Los amigos de Carol son : " + socialNetWork.getAmigos(carol)); System.out.println("Los amigos de Julia son : " + socialNetWork.getAmigos(julia)); System.out.println("3. Mostrar los amigos de la pareja: "); System.out.println("Los amigos de la pareja de Cristina son: " + socialNetWork.getAmigosPareja(cristina)); System.out.println("Los amigos de la pareja de Juan son: " + socialNetWork.getAmigosPareja(juan)); System.out.println("Los amigos de la pareja de Ana son: " + socialNetWork.getAmigosPareja(ana)); System.out.println("Los amigos de la pareja de Marc son: " + socialNetWork.getAmigosPareja(marc)); System.out.println("Los amigos de la pareja de Antonio son: " + socialNetWork.getAmigosPareja(antonio)); System.out.println("Los amigos de la pareja de Pedro son: " + socialNetWork.getAmigosPareja(pedro)); System.out.println("Los amigos de la pareja de Carol son: " + socialNetWork.getAmigosPareja(carol)); System.out.println("Los amigos de la pareja de Julia son: " + socialNetWork.getAmigosPareja(julia)); System.out.println("4. Muestra la pareja de los amigos de la persona: "); System.out.println("Las parejas de los amigos de Cristina son: " + socialNetWork.getParejaAmigos(cristina)); System.out.println("Las parejas de los amigos de Juan son: " + socialNetWork.getParejaAmigos(juan)); System.out.println("Las parejas de los amigos de Ana son: " + socialNetWork.getParejaAmigos(ana)); System.out.println("Las parejas de los amigos de Marc son: " + socialNetWork.getParejaAmigos(marc)); System.out.println("Las parejas de los amigos de Antonio son: " + socialNetWork.getParejaAmigos(antonio)); System.out.println("Las parejas de los amigos de Pedro son: " + socialNetWork.getParejaAmigos(pedro)); System.out.println("Las parejas de los amigos de Carol son: " + socialNetWork.getParejaAmigos(carol)); System.out.println("Las parejas de los amigos de Julia son: " + socialNetWork.getParejaAmigos(julia)); } }
package com.aaront.java.clone; /** * @author tonyhui * @since 16/7/18 */ public class Email implements Cloneable { public String content; public String title; public Email(String title, String content) { this.title = title; this.content = content; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } @Override protected Email clone() { try { return (Email) super.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); return new Email("", ""); } } }
package dw2.projetweb.servlets; import dw2.projetweb.beans.User; import dw2.projetweb.forms.FormUser; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; @WebServlet("/User_connexion") public class User_connexion extends HttpServlet { private FormUser formU = new FormUser(); public User_connexion() { super(); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.getServletContext().getRequestDispatcher("/WEB-INF/Site/user_connexion.jsp").forward(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { User u = new User(); HttpSession session = req.getSession(); try { u = formU.connexion(req); } catch (Exception e) { e.printStackTrace(); } req.setAttribute("formU", formU); req.setAttribute("User", u); if (formU.getErreurs().isEmpty()) { session.setAttribute("sessionU", u); this.getServletContext().getRequestDispatcher("/EspaceUtilisateur").forward(req, resp); } else { this.getServletContext().getRequestDispatcher("/WEB-INF/Site/user_connexion.jsp").forward(req, resp); } } }
package pl.edu.pw.elka.minedBlocks.dtos; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.util.List; @Data @NoArgsConstructor @AllArgsConstructor @JsonIgnoreProperties(ignoreUnknown = true) public class MinedBlocksDto { @JsonProperty(value = "result") private List<MinedBlockDto> minedBlocksRewards; }
/*********************************************************** * @Description : * @author : 梁山广(Liang Shan Guang) * @date : 2020/5/16 23:52 * @email : liangshanguang2@gmail.com ***********************************************************/ package 第03章_简单工厂模式.第3节_简单工厂模式结构与实现; public class Client { public static void main(String[] args) { Product product; product = Factory.getProduct("A"); product.methodSame(); product.methodDiff(); } }
/* * Created on 2004. 5. 24. */ package com.esum.ebms.v2.transaction; import java.io.Serializable; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageListener; import javax.jms.ObjectMessage; import javax.xml.soap.SOAPException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.esum.ebms.v2.msh.AsyncInboundProcess; import com.esum.ebms.v2.msh.HandlerUtil; import com.esum.ebms.v2.msh.HttpMessageSender; import com.esum.ebms.v2.msh.InboundProcess; import com.esum.ebms.v2.msh.MSHException; import com.esum.ebms.v2.msh.SyncInboundProcess; import com.esum.ebms.v2.packages.EbXMLMessage; import com.esum.ebms.v2.packages.container.element.ErrorList; import com.esum.ebms.v2.packages.container.validation.MessageValidator; import com.esum.ebms.v2.packages.exception.EbXMLValidationException; import com.esum.ebms.v2.service.MessageService; import com.esum.ebms.v2.service.Routing; import com.esum.ebms.v2.service.ServiceContext; import com.esum.ebms.v2.storage.RoutingInfoRecord; import com.esum.ebms.v2.storage.RoutingSearch; import com.esum.ebms.v2.storage.StorageException; import com.esum.ebms.v2.transaction.log.TransactionConstants; import com.esum.ebms.v2.transaction.log.TransactionLog; import com.esum.ebms.v2.transaction.log.TransactionLogFactory; import com.esum.framework.common.util.MessageIDGenerator; /** * Inbound Transaction. * * Copyright(c) eSum Technologies., inc. All rights reserved. */ public class InboundTransaction extends Transaction implements MessageListener { protected static Logger log = LoggerFactory.getLogger(InboundTransaction.class); private TransactionLog transactionLog = TransactionLogFactory.getInstance(); public InboundTransaction(InboundTransactionGroup group, String txName){ super(group.getNodeId(), group, txName); log.debug(traceId + " Starting Inbound Transaction..."); } public void onMessage(Message message) { Serializable object = null; try { object = ((ObjectMessage) message).getObject(); MessageService context = (MessageService)object; long startTime = System.currentTimeMillis(); log.info(traceId + "["+context.getMessageId()+"] Received Inbound message. Starting Inbound Transaction process..."); execute(context); log.debug(traceId+"["+context.getMessageId()+"] Finished Inbound Transaction process. Process Time: " + (System.currentTimeMillis() - startTime) + "ms."); } catch (TransactionException e) { log.error(traceId + " onMessage()", e); } catch (Exception e){ log.error(traceId + " onMessage()", e); } finally { try { message.acknowledge(); } catch (JMSException e) { log.error(traceId + " onMessage()", e); } } } public void execute(ServiceContext context) throws TransactionException { MessageService messageService = (MessageService)context; EbXMLMessage ebXMLMessage = messageService.getEbXMLMessage(); int messageType = messageService.getMessageType(); if(messageType==MessageService.EBXML_PING || messageType==MessageService.EBXML_MESSAGE_STATUS_REQUEST) { RoutingInfoRecord routing = null; log.debug(traceId + "["+messageService.getMessageId()+"] Searching Routing Info..."); try { routing = RoutingSearch.getRoutingInfo(messageService.getMessageType(), HandlerUtil.makeResponseRouting(ebXMLMessage)); } catch (StorageException e) { throw new TransactionException(e.getErrorCode(), "execute()", e); } log.debug(traceId + "["+messageService.getMessageId()+"] Inbound message process."); InboundProcess inboundProcess = null; try { inboundProcess = new AsyncInboundProcess(getName(), messageService, routing); inboundProcess.execute(); } catch (MSHException e) { throw new TransactionException(e.getErrorCode(), "execute()", e); } return; } Routing routing = null; RoutingInfoRecord routingInfo = null; long stime = System.currentTimeMillis(); try { routing = HandlerUtil.makeRouting(traceId, ebXMLMessage); log.debug(traceId + "["+messageService.getMessageId()+"] Made Routing from the ebXML message."); log.debug(traceId + "["+messageService.getMessageId()+"] before validating message."); MessageValidator.getInstance().validateEbXMLMessage(ebXMLMessage); log.debug(traceId + "["+messageService.getMessageId()+"] after validating message."); log.debug(traceId + "["+messageService.getMessageId()+"] Searching Routing Info..."); routingInfo = RoutingSearch.getRoutingInfo(messageService.getMessageType(), routing); log.info(traceId + "["+messageService.getMessageId()+"] Found Routing Info. Routing Info: " + routingInfo); log.debug(traceId+"["+messageService.getMessageId()+"] Updating transaction log."); transactionLog.updateRequestInfo(traceId, messageService.getTxId(), TransactionConstants.TRANSFER_TYPE_INBOUND, routingInfo, ebXMLMessage); log.info(traceId+"["+messageService.getMessageId()+"] Routing found and transaction updated. elapsed time is "+(System.currentTimeMillis()-stime)+" ms."); } catch (EbXMLValidationException e) { log.error(traceId + "execute()", e); try { RoutingInfoRecord rInfo = new RoutingInfoRecord(); rInfo.setCpaId(routing.cpaId); rInfo.setFromPartyInfoId(RoutingSearch.getPartyInfoId(routing.fromPartyList)); rInfo.setToPartyInfoId(RoutingSearch.getPartyInfoId(routing.toPartyList)); rInfo.setFromRole(routing.fromRole); rInfo.setToRole(routing.toRole); rInfo.addService(routing.service, routing.serviceType, routing.action); transactionLog.updateRequestInfo(traceId, messageService.getTxId(), TransactionConstants.TRANSFER_TYPE_INBOUND, rInfo, ebXMLMessage); } catch (StorageException se) { log.error(traceId + "execute()", e); } try { EbXMLMessage errEbXMLMessage = e.getErrorListMessage(messageService.getEbXMLMessage(), null); if(messageService.isAsync()) { executeAsyncErrorList(messageService.getTxId(), messageService.getMessageType(), routing, errEbXMLMessage); } else { MessageService errMessageService = new MessageService(traceId, errEbXMLMessage); TransactionManager.getInstance().addTransactionResult(messageService.getMessageId(), errMessageService); transactionLog.updateResponseTxId(traceId, messageService.getTxId(), messageService.getTxId(), null); } transactionLog.storeErrorLog(traceId, messageService.getTxId(), e); } catch (Exception ex) { log.error(traceId + "execute()", e); } return; } catch (StorageException e) { log.error(traceId + "execute()", e); try { RoutingInfoRecord rInfo = new RoutingInfoRecord(); rInfo.setCpaId(routing.cpaId); rInfo.setFromPartyInfoId(RoutingSearch.getPartyInfoId(routing.fromPartyList)); rInfo.setToPartyInfoId(RoutingSearch.getPartyInfoId(routing.toPartyList)); rInfo.setFromRole(routing.fromRole); rInfo.setToRole(routing.toRole); rInfo.addService(routing.service, routing.serviceType, routing.action); transactionLog.updateRequestInfo(traceId, messageService.getTxId(), TransactionConstants.TRANSFER_TYPE_INBOUND, rInfo, ebXMLMessage); } catch (StorageException se) { log.error(traceId + "execute()", e); } try { EbXMLValidationException ve = new EbXMLValidationException(ErrorList.ERROR_CODE_INCONSISTENT, ErrorList.SEVERITY_ERROR, "CPA Error!! Please check the CPA information."); EbXMLMessage errEbXMLMessage = ve.getErrorListMessage(messageService.getEbXMLMessage(), null); if(messageService.isAsync()) { executeAsyncErrorList(messageService.getTxId(), messageService.getMessageType(), routing, errEbXMLMessage); } else { MessageService errMessageService = new MessageService(traceId, errEbXMLMessage); TransactionManager.getInstance().addTransactionResult(messageService.getMessageId(), errMessageService); transactionLog.updateResponseTxId(traceId, messageService.getTxId(), messageService.getTxId(), null); } transactionLog.storeErrorLog(traceId, messageService.getTxId(), e); } catch (Exception ex) { log.error(traceId + "execute()", e); } return; } InboundProcess inboundProcess = null; try { if(messageService.isAsync()) { log.debug(traceId + "["+messageService.getMessageId()+"] This message is processed by the asynchronous method."); inboundProcess = new AsyncInboundProcess(getName(), messageService, routingInfo); } else { log.debug(traceId + "["+messageService.getMessageId()+"] This message is processed by the synchronous method."); inboundProcess = new SyncInboundProcess(getName(), messageService, routingInfo); } inboundProcess.execute(); } catch (MSHException e) { throw new TransactionException(e.getErrorCode(), "execute()", e); } } /** * Async 수신 에서 오류시 routing 검색하여, 상대방 MSH URL 로 from/to 변경하여 전송 * AsyncInboundProcess 의 executeErrorList 는 라우팅 정보를 찾은후 발생한 오류를 처리하고 * 이 메소드는 라우팅 정보 찾기 전에 발생된 에러의 경우 ErrorList 를 보냄. */ public void executeAsyncErrorList(String txId, int messageType, Routing routing, EbXMLMessage errorMessage) throws MSHException { String traceId = "[" + txId + "] "; log.debug(traceId + "Starting the ErrorList process on asynchronous inbound..."); try { RoutingInfoRecord routingInfo = RoutingSearch.getRoutingInfo(messageType, routing); String contentId = null; try { contentId = errorMessage.getSoapMessage().getSOAPPart().getContentId(); } catch (SOAPException e) { throw new MSHException(MSHException.ERROR_SOAP_PROCESS, "executeErrorList()", e); } HttpMessageSender sender = new HttpMessageSender(TransactionGroup.INBOUND_TRANSACTION_TYPE+"-"+routing.getCpaId()); String errTxId = MessageIDGenerator.generateMessageID(); RoutingInfoRecord resRInfo = new RoutingInfoRecord(); resRInfo.setCpaId(errorMessage.getCPAId()); resRInfo.setFromPartyInfoId(routingInfo.getToPartyInfoId()); resRInfo.setToPartyInfoId(routingInfo.getFromPartyInfoId()); resRInfo.setRoutingInfoId(routingInfo.getRoutingInfoId()); TransactionLogFactory.getInstance().storeHTTPRequest(traceId, errTxId, TransactionConstants.TRANSFER_TYPE_OUTBOUND, resRInfo, errorMessage, true); TransactionLogFactory.getInstance().updateResponseTxId(traceId, errTxId, txId, errorMessage.getRefToMessageId()); // 에러리스트 전송 sender.send(traceId, null, errorMessage, contentId, routingInfo.getRoutingPath().getToMSHUrl(), routingInfo.getRoutingPath().getSourceIp()); TransactionLogFactory.getInstance().updateStatus(traceId, errTxId, TransactionConstants.STATUS_ERRORLIST_SEND); TransactionLogFactory.getInstance().updateStatus(traceId, txId, TransactionConstants.STATUS_ERRORLIST_SEND); } catch (TransactionException e) { throw new MSHException(e.getErrorCode(), "executeErrorList()", e); } catch (Exception e) { throw new MSHException(MSHException.ERROR_UNDEFINED_ERROR, "executeErrorList()", e); } log.debug(traceId + "Finished the ErrorList process on asynchronous inbound."); } public void close(){ // HttpClientTemplateFactory.getInstance().removeHttpClientTemplate(TransactionGroup.INBOUND_TRANSACTION_TYPE); } }
package com.esum.comp.nckims; import com.esum.framework.core.component.code.ComponentCode; /** * UA Dacom Error Codes. */ public class NcKimsCode extends ComponentCode { public static final String ERROR_RECEIVE_WS_MESSAGE = "NCKIMS1"; public static final String ERROR_SEND_COMPLETE_MSG = "NCKIMS2"; }
package com.sotrust.calculator; public class Calculator { public static void someMethod () { System.out.println("someMethod works perfectly"); } public void anotherMethod () { System.out.println("anotherMethod works perfectly too"); } public static void main(String[] args) { someMethod(); Calculator calculator = new Calculator(); calculator.anotherMethod(); System.out.println(add(4,5)); System.out.println(subtract(5, 2)); } public static int add (int a, int b) { return a + b; } public static int subtract (int a, int b) { return a - b; } }
package co.jijichat.vcard; public class UserProfile { private String nickname = null; private String bio = null; private long memberSince; public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public String getBio() { return bio; } public void setBio(String bio) { this.bio = bio; } public long getMemberSince() { return memberSince; } public void setMemberSince(long memberSince) { this.memberSince = memberSince; } @Override public String toString() { return "UserProfile [nickname=" + nickname + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((nickname == null) ? 0 : nickname.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; UserProfile other = (UserProfile) obj; if (nickname == null) { if (other.nickname != null) return false; } else if (!nickname.equals(other.nickname)) return false; return true; } }
package com.company.iba.ialeditor.model; import com.liferay.portal.kernel.util.Validator; import com.liferay.portal.model.ModelWrapper; import java.util.HashMap; import java.util.Map; /** * <p> * This class is a wrapper for {@link Language}. * </p> * * @author Brian Wing Shun Chan * @see Language * @generated */ public class LanguageWrapper implements Language, ModelWrapper<Language> { private Language _language; public LanguageWrapper(Language language) { _language = language; } @Override public Class<?> getModelClass() { return Language.class; } @Override public String getModelClassName() { return Language.class.getName(); } @Override public Map<String, Object> getModelAttributes() { Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put("langId", getLangId()); attributes.put("langName", getLangName()); attributes.put("langCode", getLangCode()); return attributes; } @Override public void setModelAttributes(Map<String, Object> attributes) { Long langId = (Long) attributes.get("langId"); if (langId != null) { setLangId(langId); } String langName = (String) attributes.get("langName"); if (langName != null) { setLangName(langName); } String langCode = (String) attributes.get("langCode"); if (langCode != null) { setLangCode(langCode); } } /** * Returns the primary key of this language. * * @return the primary key of this language */ @Override public long getPrimaryKey() { return _language.getPrimaryKey(); } /** * Sets the primary key of this language. * * @param primaryKey the primary key of this language */ @Override public void setPrimaryKey(long primaryKey) { _language.setPrimaryKey(primaryKey); } /** * Returns the lang ID of this language. * * @return the lang ID of this language */ @Override public long getLangId() { return _language.getLangId(); } /** * Sets the lang ID of this language. * * @param langId the lang ID of this language */ @Override public void setLangId(long langId) { _language.setLangId(langId); } /** * Returns the lang name of this language. * * @return the lang name of this language */ @Override public java.lang.String getLangName() { return _language.getLangName(); } /** * Sets the lang name of this language. * * @param langName the lang name of this language */ @Override public void setLangName(java.lang.String langName) { _language.setLangName(langName); } /** * Returns the lang code of this language. * * @return the lang code of this language */ @Override public java.lang.String getLangCode() { return _language.getLangCode(); } /** * Sets the lang code of this language. * * @param langCode the lang code of this language */ @Override public void setLangCode(java.lang.String langCode) { _language.setLangCode(langCode); } @Override public boolean isNew() { return _language.isNew(); } @Override public void setNew(boolean n) { _language.setNew(n); } @Override public boolean isCachedModel() { return _language.isCachedModel(); } @Override public void setCachedModel(boolean cachedModel) { _language.setCachedModel(cachedModel); } @Override public boolean isEscapedModel() { return _language.isEscapedModel(); } @Override public java.io.Serializable getPrimaryKeyObj() { return _language.getPrimaryKeyObj(); } @Override public void setPrimaryKeyObj(java.io.Serializable primaryKeyObj) { _language.setPrimaryKeyObj(primaryKeyObj); } @Override public com.liferay.portlet.expando.model.ExpandoBridge getExpandoBridge() { return _language.getExpandoBridge(); } @Override public void setExpandoBridgeAttributes( com.liferay.portal.model.BaseModel<?> baseModel) { _language.setExpandoBridgeAttributes(baseModel); } @Override public void setExpandoBridgeAttributes( com.liferay.portlet.expando.model.ExpandoBridge expandoBridge) { _language.setExpandoBridgeAttributes(expandoBridge); } @Override public void setExpandoBridgeAttributes( com.liferay.portal.service.ServiceContext serviceContext) { _language.setExpandoBridgeAttributes(serviceContext); } @Override public java.lang.Object clone() { return new LanguageWrapper((Language) _language.clone()); } @Override public int compareTo(com.company.iba.ialeditor.model.Language language) { return _language.compareTo(language); } @Override public int hashCode() { return _language.hashCode(); } @Override public com.liferay.portal.model.CacheModel<com.company.iba.ialeditor.model.Language> toCacheModel() { return _language.toCacheModel(); } @Override public com.company.iba.ialeditor.model.Language toEscapedModel() { return new LanguageWrapper(_language.toEscapedModel()); } @Override public com.company.iba.ialeditor.model.Language toUnescapedModel() { return new LanguageWrapper(_language.toUnescapedModel()); } @Override public java.lang.String toString() { return _language.toString(); } @Override public java.lang.String toXmlString() { return _language.toXmlString(); } @Override public void persist() throws com.liferay.portal.kernel.exception.SystemException { _language.persist(); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof LanguageWrapper)) { return false; } LanguageWrapper languageWrapper = (LanguageWrapper) obj; if (Validator.equals(_language, languageWrapper._language)) { return true; } return false; } /** * @deprecated As of 6.1.0, replaced by {@link #getWrappedModel} */ public Language getWrappedLanguage() { return _language; } @Override public Language getWrappedModel() { return _language; } @Override public void resetOriginalValues() { _language.resetOriginalValues(); } }
package com.esum.comp.smail.pop3; import java.io.File; import java.util.Iterator; import java.util.List; import javax.mail.Flags; import javax.mail.Folder; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Store; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.esum.common.lock.LockFactory; import com.esum.common.lock.Lockable; import com.esum.comp.ftp.FtpConfig; import com.esum.comp.smail.SMailCode; import com.esum.comp.smail.SMailConfig; import com.esum.comp.smail.SMailException; import com.esum.comp.smail.inbound.SMailInboundHandler; import com.esum.comp.smail.inbound.SMailInboundListener; import com.esum.comp.smail.table.SMailSvrInfoRecord; import com.esum.comp.smail.util.SMailUtil; import com.esum.framework.FrameworkSystemVariables; import com.esum.framework.common.util.DateUtil; import com.esum.framework.common.util.FileUtil; import com.esum.framework.common.util.MessageIDGenerator; import com.esum.framework.core.exception.SystemException; public class POP3Daemon extends Thread { private Logger log = LoggerFactory.getLogger(POP3Daemon.class); private boolean running; private SMailSvrInfoRecord pop3SvrInfo; private String traceId; private SMailInboundListener listener; private Lockable lock; public POP3Daemon(SMailInboundListener listener, SMailSvrInfoRecord pop3SvrInfo) throws SystemException { this.listener = listener; this.pop3SvrInfo = pop3SvrInfo; String nodeId = System.getProperty(FrameworkSystemVariables.NODE_ID); this.traceId = "["+SMailConfig.MODULE_NAME+"]["+nodeId+"]["+pop3SvrInfo.getSvrInfoId()+"] "; this.lock = LockFactory.getInstance().createLock(SMailConfig.LOCK_TABLE_NAME, nodeId, pop3SvrInfo.getSvrInfoId(), log); this.lock.initLock(); } public void close(){ if(log.isInfoEnabled()) log.info(traceId+"closing pop3 daemon."); running = false; interrupt(); } public void run() { int interval = (int)pop3SvrInfo.getPop3PollingInterval()*1000; int forcedUnlockInterval = FtpConfig.FORCED_UNLOCK_INTERVAL_SEC; if(log.isInfoEnabled()) log.info(traceId+"Start POP3 Daemon for " + pop3SvrInfo.getMailUserId()+ "@" + pop3SvrInfo.getMailServer() + ". Interval(" + interval + "msec)"); running = true; while (!Thread.interrupted() && running) { try { // check the lock of interface table. int lockResult = lock.lock(interval, null, forcedUnlockInterval); if (lockResult > 0) { log.debug(traceId + "Locked this interface."); try { process(); } finally { lock.unlock(); log.debug(traceId + "Released lock of this interface."); } } else { log.info(traceId + "This interface is now locked by other systems. Can't process."); } } catch (SystemException e) { log.error(traceId + "Error occured during lock/unlock processing..", e); } catch (Exception e) { log.error(traceId + "run()", e); } try { Thread.sleep(interval); } catch (Exception e) { log.warn(traceId+" POP3Daemon interruped."); break; } } if(log.isInfoEnabled()) log.info(traceId+" pop3 daemon stopped."); } private void process() { try { List<Store> storeList = POP3Manager.getStoreList(pop3SvrInfo); if (storeList==null || storeList.size() == 0) { log.info(traceId + "SMail Connector(POP3) can't connect to any mail server."); } else { onReceiveMail(storeList); } }catch(Exception e) { log.error(traceId + "Error in onReceiveMail()." + e.toString()); } } private void onReceiveMail(List<Store> storeList) { if(log.isDebugEnabled()) log.debug(traceId+"enter onReceiveMail()"); Iterator<Store> iter = storeList.iterator(); Store store = null; while(iter.hasNext()) { store = (Store)iter.next(); if(log.isDebugEnabled()) log.debug(traceId + "SMail Connector(POP3) connected to " + store.getURLName().getHost() + "."); Folder folder = null; POP3MessageInfo messageInfo = null; boolean result = false; try { folder = openFolder(store); if(log.isDebugEnabled()) log.debug(traceId + "INBOX folder opened."); int totalMessages = folder.getMessageCount(); if(log.isDebugEnabled()) log.debug(traceId+"INBOX message count is "+totalMessages); if (totalMessages <= 0) { folder.close(true); store.close(); continue; } if(log.isInfoEnabled()){ log.info(traceId + "Get mail from " + store.getURLName().getHost() + " via POP3. (Message Count: " + totalMessages +")"); } int msgCnt = totalMessages > SMailConfig.getMSGCNT_AT_ONCE() ? SMailConfig.getMSGCNT_AT_ONCE() : totalMessages; Message[] messages = folder.getMessages(1, msgCnt); Message message = null; for(int j=0; j<messages.length; j++) { message = messages[j]; try { messageInfo = new POP3MessageInfo(pop3SvrInfo); result = messageInfo.parseMessage(folder, message); if(result) { if(log.isDebugEnabled()) log.debug(traceId+" Received SMail."); SMailInboundHandler handler = null; List<byte[]> payloads = messageInfo.getPayloads(); List<String> payloadFileNames = messageInfo.getPayloadFileNames(); for (int i=0; i<payloads.size(); i++) { handler = new SMailInboundHandler(listener.getComponentId(), pop3SvrInfo, messageInfo.getSMailFrom(), payloads.get(i), payloadFileNames.get(i)); handler.process(); } } } catch (Exception e) { log.error(traceId + "Error occured in processing mail message.", e); //BACKUP 저장위치: 설정디렉토리 / error / 날짜 / generated messageId try { File mailboxHome = new File(SMailConfig.getMAILBOX(), "error"); if(!mailboxHome.isDirectory()) mailboxHome.mkdirs(); File mailboxPath = new File(mailboxHome, DateUtil.getCYMD(System.currentTimeMillis())); if(!mailboxPath.isDirectory()) { mailboxPath.mkdirs(); } String fname = MessageIDGenerator.generateMessageID(); FileUtil.writeToFile(new File(mailboxPath, fname), SMailUtil.getRawData(message)); log.warn("Mail with error in processing backup success. File name: " + fname); } catch (Exception ex) { log.error(traceId + "Failure to backup mail with error in processing.", ex); } } finally { //DELETE message.setFlags(new Flags(Flags.Flag.DELETED), true); } } } catch (MessagingException e) { log.info(traceId+"Can not read mail message.", e); log.error(traceId + "pop3 receive error", e); try { if(store!=null && store.isConnected()) store.close(); } catch (Exception e1) {} } catch (SMailException e) { log.error(traceId + "pop3 receive error", e); try { if(store!=null && store.isConnected()) store.close(); } catch (Exception e1) {} } finally{ try { if(folder!=null && folder.isOpen()) folder.close(true); } catch (Exception e) { } } } try { if(store!=null && store.isConnected()) store.close(); } catch (Exception e) {} } private Folder openFolder(Store store) throws SMailException { Folder folder = null; try { folder = store.getDefaultFolder(); folder = folder.getFolder("INBOX"); folder.open(Folder.READ_WRITE); } catch (MessagingException e) { throw new SMailException(SMailCode.ERROR_MESSAGING_ERROR, "openFolder()", e.toString()); } return folder; } }
package commands; import items.Item; import org.newdawn.slick.command.BasicCommand; import actionEngines.ActionEngine; import actionEngines.MenuActionEngine; public class MenuEquipItemCommand extends BasicCommand implements GenericCommand { private Item item; public MenuEquipItemCommand(Item item) { super("Equip item" + item); this.item = item; } @Override public void execute(ActionEngine actionEngine) { ((MenuActionEngine)actionEngine).equipItemInPlayerInventory(item); } }
package gameobjects; import javax.media.opengl.GL; import java.awt.Color; public class GameObject implements Drawable { public Color rgb; public Point position; public Point velocity; public boolean isFilled; public int lineWidth; /** * A parent class of all the game objects used in this game. * * @param position The position (x, y) of the object on the canvas. * @param velocity The speed of the object. * @param rgb The main color of the game object. * @param isFilled Draw outlined or filled object. * @param lineWidth The line width of the outlined object. */ GameObject(Point position, Point velocity, Color rgb, boolean isFilled, int lineWidth) { this.position = position; this.velocity = velocity; this.rgb = rgb; this.isFilled = isFilled; this.lineWidth = lineWidth; } @Override public void draw(GL gl) { gl.glLineWidth(lineWidth); } }
package com.hef.com; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import Dao.StudentDao; public class EditServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter pw=response.getWriter(); pw.print("<h1>Update Subjectmarks</h1>"); String sid=request.getParameter("id"); int id=Integer.parseInt(sid); Student s=StudentDao.getStudentById(id); pw.print("<form action='EsitServlet2'method='post'>"); pw.print("<table>"); pw.print("<tr><td></td><input type='hidden'name='id' value="+s.getId()+"/></td></tr>"); pw.print("<tr><td></td><input type='text'name='subjectname' value="+s.getSubjectname()+"/></td></tr>"); pw.print("<tr><td>Marks:</td><td><input type='marks'value="+s.getMarks()+"/></td></tr>"); pw.print("</td></tr>"); pw.print("<tr><td colspan='2'><input type='submit'value='Edit & Save'/></td></tr>"); pw.print("</table>"); pw.print("</form>"); pw.close(); } }
package com.xwj.service; import com.xwj.entity.Role; public interface RoleService { Role getRole(int id); }
package com.networks.ghosttears.activities; import android.content.Intent; import android.os.Build; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.MotionEvent; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import com.networks.ghosttears.R; import com.networks.ghosttears.gameplay_package.GhostTears; import com.networks.ghosttears.gameplay_package.ManagingImages; import com.networks.ghosttears.gameplay_package.ManagingSoundService; public class Pause_Menu extends AppCompatActivity { ManagingImages managingImages = new ManagingImages(); ManagingSoundService managingSoundService = new ManagingSoundService(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_pause__menu); // Setting windows features Window window = getWindow(); window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); FullScreencall(); Button resumeButton = (Button) findViewById(R.id.resume_button); Button restartButton = (Button) findViewById(R.id.restart_button); Button quitButton = (Button) findViewById(R.id.quit_button); resumeButton.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { managingSoundService.playButtonClickSound(view); closeActivity(); } } ); restartButton.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { managingSoundService.playButtonClickSound(view); Bundle bundle = getIntent().getExtras(); String gameType = ""; if(bundle.getString("gameType")!= null){ gameType = bundle.getString("gameType"); } if(gameType.equalsIgnoreCase("local")) { Intent restartGameIntent = new Intent(Pause_Menu.this, GamescreenLocal.class); startActivity(restartGameIntent); }else if(gameType.equalsIgnoreCase("singleplayer")){ Intent restartGameIntent = new Intent(Pause_Menu.this, GamescreenSinglePlayer.class); startActivity(restartGameIntent); } } } ); quitButton.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { managingSoundService.playButtonClickSound(view); Intent homeIntent = new Intent(Pause_Menu.this, Home.class); startActivity(homeIntent); ((GhostTears) Pause_Menu.this.getApplication()).setShouldPlay(false); } } ); resumeButton.setOnTouchListener(onTouchListener()); restartButton.setOnTouchListener(onTouchListener()); quitButton.setOnTouchListener(onTouchListener()); managingImages.loadButtonBackground(resumeButton,R.drawable.general_button_background); managingImages.loadButtonBackground(restartButton,R.drawable.brown_button_background); managingImages.loadButtonBackground(quitButton,R.drawable.brown_button_background); } private View.OnTouchListener onTouchListener(){ View.OnTouchListener onTouchListener = new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { managingImages.powerupsbuttontouched(view,motionEvent); return false; } }; return onTouchListener; } private void closeActivity(){ finish(); } public void FullScreencall() { if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api View v = this.getWindow().getDecorView(); v.setSystemUiVisibility(View.GONE); } else if (Build.VERSION.SDK_INT >= 19) { //for new api versions. View decorView = getWindow().getDecorView(); int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY; decorView.setSystemUiVisibility(uiOptions); } } }
/* * Fazer uma função que tem como parâmetro de entrada três números inteiros a, b, c e devolve (retorna) menor dentre os três números. */ package Lista3; import java.util.Scanner; public class Exercicio1 { static Scanner input = new Scanner(System.in); static int entrada(){ int n; System.out.print("Número: "); n = input.nextInt(); return n; } static int menor(int n1, int n2, int n3){ int menor=0; if((n1<=n2) &(n1<=n3)){ menor = n1; } else if((n2<=n3) & (n2<=n1)){ menor = n2; } else if((n3<=n2) & (n3<=n1)){ menor = n3; } return menor; } static void imprimir(int menor){ System.out.println("menor número ="+menor); } public static void main(String[] args) { int n1=entrada(); int n2=entrada(); int n3=entrada(); int m = menor(n1, n2, n3); imprimir(m); } }
/** https://codeforces.com/problemset/problem/81/A #deque #implementation */ import java.io.*; import java.util.Deque; import java.util.LinkedList; public class Plugin { public static void main(String[] args) { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); // faster than scanner. // Scanner sc = new Scanner(System.in); // String str = sc.nextLine(); PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); try { String str = br.readLine(); Deque<Character> queue = new LinkedList<>(); for (char c : str.toCharArray()) { if (!queue.isEmpty()) { if (queue.peekLast() == c) { queue.pollLast(); } else { queue.addLast(c); } } else { queue.addLast(c); } } while (!queue.isEmpty()) { // System.out.print(queue.pollFirst()); pw.print(queue.pollFirst); // faster than System.out.print } } catch (IOException e) { } } }
package com.krt.gov.strategy.constant; public class StrategyConst { public static final int STRATEGY_MANUAL = 1; public static final int STRATEGY_TIME = 2; public static final int STRATEGY_CONDITION = 3; public static final String FULL_WEEK = "1,2,3,4,5,6,7"; public static final int STRATEGY_ENABLE = 1; public static final int STRATEGY_DISABLE = 0; }
package tj.teacherjournal; /** * Created by risatgajsin on 19.04.2018. */ public class Protection { }
package structural.proxy.my; public class ProxyImage implements Image{ private RealImage realImage; private String fileName; public ProxyImage(String fileName) { this.fileName = fileName; } @Override public void display() { // 延迟初始化 if (realImage == null) { realImage = new RealImage(fileName); } // 预处理 System.out.println("Loading image"); realImage.display(); // 后处理 System.out.println("Close image"); } }
package co.simplon.hote.model; import java.util.ArrayList; public class ReservationManager { private final static ReservationManager INSTANCE = new ReservationManager(); private ArrayList<Client>infoResa = new ArrayList<Client>(); public ReservationManager() { } public ArrayList<Client> getInfoResa() { return infoResa; } public void setInfoResa(ArrayList<Client> infoResa) { this.infoResa = infoResa; } public static ReservationManager getInstance() { return INSTANCE; } //--methode pour ajouter les reservations à la liste public void addInfo (Client client){ infoResa.add(client); } }
package org.opencv.samples.tutorial3; import android.app.Activity; import android.os.Bundle; public class ImageGrid extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.image_grid_view); } }
package org.seforge.monitor.web; import java.util.Date; import java.util.Set; import javax.persistence.TypedQuery; import org.seforge.monitor.domain.Resource; import org.seforge.monitor.domain.ResourceGroup; import org.seforge.monitor.extjs.JsonObjectResponse; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import flexjson.JSONSerializer; import flexjson.transformer.DateTransformer; @RequestMapping("/embedded/list_subresources") @Controller public class ListSubresources { @RequestMapping(method = RequestMethod.GET) public ResponseEntity<String> generateMetrics(@RequestParam("id") Integer id) { HttpStatus returnStatus; JsonObjectResponse response = new JsonObjectResponse(); if (id == null) { returnStatus = HttpStatus.BAD_REQUEST; response.setMessage("No Resource Id provided."); response.setSuccess(false); response.setTotal(0L); } else { try { TypedQuery<Resource> result = Resource.findResourcesByResourceIdEquals(id); Resource r = result.getSingleResult(); Set<ResourceGroup> rgs = r.getResourceGroups(); returnStatus = HttpStatus.OK; response.setMessage("The group information is found."); response.setSuccess(true); response.setTotal(rgs.size()); response.setData(rgs); } catch (Exception e) { e.printStackTrace(); returnStatus = HttpStatus.INTERNAL_SERVER_ERROR; response.setMessage(e.getMessage()); response.setSuccess(false); response.setTotal(0L); } } return new ResponseEntity<String>(new JSONSerializer() .exclude("*.class") .transform(new DateTransformer("MM/dd/yy"), Date.class) .serialize(response), returnStatus); } }
package com.fiona.test; import org.junit.Assert; import org.junit.Test; import java.util.List; public class TestKeyBoard { @Test public void test1() { int[] input = new int[]{2, 3}; KeyBoard keyBoard = new KeyBoard(); List<String> list = keyBoard.doConvert(input); KeyBoard secGenerationKeyBoard = new SecGenerationKeyBoard(); List<String> secGenerationList = secGenerationKeyBoard.doConvert(input); Assert.assertTrue(list.size() == keyBoard.getChars(2).length * keyBoard.getChars(3).length); Assert.assertTrue(list.size() == secGenerationList.size()); } @Test public void test2() { int[] input = new int[]{0, 3, 2, 1}; KeyBoard keyBoard = new KeyBoard(); List<String> list = keyBoard.doConvert(input); KeyBoard secGenerationKeyBoard = new SecGenerationKeyBoard(); List<String> secGenerationList = secGenerationKeyBoard.doConvert(input); Assert.assertTrue(list.size() == keyBoard.getChars(2).length * keyBoard.getChars(3).length); Assert.assertTrue(list.size() == secGenerationList.size()); } @Test public void test3() { int[] input = new int[]{0, 1}; KeyBoard keyBoard = new KeyBoard(); List<String> list = keyBoard.doConvert(input); KeyBoard secGenerationKeyBoard = new SecGenerationKeyBoard(); List<String> secGenerationList = secGenerationKeyBoard.doConvert(input); Assert.assertTrue(list.size() == 0); Assert.assertTrue(list.size() == secGenerationList.size()); } @Test(expected = IllegalArgumentException.class) public void test4() { int[] input = new int[]{5, 24}; KeyBoard keyBoard = new KeyBoard(); List<String> list = keyBoard.doConvert(input); } @Test public void test5() { int[] input = new int[]{5, 24}; KeyBoard secGenerationKeyBoard = new SecGenerationKeyBoard(); List<String> secGenerationList = secGenerationKeyBoard.doConvert(input); Assert.assertTrue(secGenerationList.size() == secGenerationKeyBoard.getChars(5).length * (secGenerationKeyBoard.getChars(2).length + secGenerationKeyBoard.getChars(4).length)); } }