text
stringlengths
10
2.72M
package test; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.util.List; import java.util.Map; public class AAAAAAA3{ public static String USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36"; public static String COOKIE = ""; public static String USER_ID = "13871109060"; public static String PASSWORD = "cgf1977121"; public static void main(String[] args) throws Exception { if (checkLogin(USER_ID,PASSWORD)) { System.out.println("Logged in"); getAccountPage(); getAssetPage(); getDetailPage(PRODUCT_ID); getAssetPage(); while (true){ try{ //loop if( post(TOTAL,PRODUCT_ID) ){ System.out.println("OK!!"); } break; }catch(Exception e){ e.printStackTrace(); continue; } // Thread.currentThread(); // Thread.sleep(20); } } } static String getPage1(){ String cookie = ""; try{ URL logonURL = new URL("http://lab.chinapnr.com/muser/publicRequests?UsrCustId=6000060183267352&TransAmt=50.00&BgRetUrl=http%3A%2F%2Fllcb.lalacaifu.com%2Fhuifu%2Fasyn&FreezeOrdId=853061459826827264&MerPriv=eyJzb3VyY2VUeXBlIjoiUEhPTkVYIiwicHJvQW1vdW50IjoiMzAwMDAwLjAwIn0%3D&RetUrl=https%3A%2F%2Fwww.lalacaifu.com%2Fhuifu%2Fsync&BorrowerDetails=%5B%7B%22BorrowerCustId%22%3A%226000060168631450%22%2C%22BorrowerAmt%22%3A%2250.00%22%2C%22BorrowerRate%22%3A%221.00%22%2C%22ProId%22%3A%22WVJ1704120939573%22%7D%5D&OrdDate=20170415&ChkValue=71D83FD2E90F87112213E40E0F38A6818D332BCE474B787C6C765F7E4C956F9D02BF988F95DBB79FE3A489FC729DBEE5E06077900A115BEF079229D969198DB607EA81C953C5D2378182FA7B67BD16E172653ECEF9D55ABCD4957F034FC7906B6EFFA7FE78E473AB527E548CF391A14E038699F92320ECBD40CB7B8BF2B94CCF&MerCustId=6000060016136889&OrdId=853061459826827264&Version=20&CmdId=InitiativeTender&IsFreeze=Y&MaxTenderRate=0.20"); URLConnection logonConn = logonURL.openConnection(); logonConn.setDoOutput(true);; logonConn.setRequestProperty("User-agent", USER_AGENT); logonConn.setRequestProperty("X-Requested-With", "XMLHttpRequest"); logonConn.setRequestProperty("Cookie", COOKIE); // 获得连接输出流 OutputStreamWriter logonOut = new OutputStreamWriter(logonConn .getOutputStream()); logonOut.flush(); logonOut.close(); BufferedReader logonReader = new BufferedReader( new InputStreamReader(logonConn.getInputStream(), "utf-8")); String line = null; int lineNum = 1; while ((line = logonReader.readLine()) != null) { ++lineNum; System.out.println(line); // if (line.contains("formhash=")) { // // formhash = "" // } } }catch(Exception e){ System.out.println(e); } return cookie; } static String getAccountPage(){ try{ //URL logonURL = new URL("https://m.lalacaifu.com/mobile-web/views/product/productDetail.html?proId=3725"); URL logonURL = new URL("https://m.lalacaifu.com/mobile-web/views/user/account.html"); URLConnection logonConn = logonURL.openConnection(); logonConn.setDoOutput(true);; logonConn.setRequestProperty("User-agent", USER_AGENT); logonConn.setRequestProperty("Referer", "https://m.lalacaifu.com/mobile-web/views/user/login.html"); logonConn.setRequestProperty("X-Requested-With", "XMLHttpRequest"); logonConn.setRequestProperty("Cookie", COOKIE); logonConn.setRequestProperty("Connection", "keep-alive"); logonConn.setRequestProperty("Cache-Control", "max-age=0"); BufferedReader logonReader = new BufferedReader( new InputStreamReader(logonConn.getInputStream(), "utf-8")); String line = null; int lineNum = 1; while ((line = logonReader.readLine()) != null) { ++lineNum; System.out.println(line); // if (line.contains("formhash=")) { // // formhash = "" // } } }catch(Exception e){ System.out.println(e); } return ""; } static String getAssetPage(){ try{ //URL logonURL = new URL("https://m.lalacaifu.com/mobile-web/views/product/productDetail.html?proId=3725"); URL logonURL = new URL("https://m.lalacaifu.com/fund/userasset"); URLConnection logonConn = logonURL.openConnection(); logonConn.setDoOutput(true);; logonConn.setRequestProperty("User-agent", USER_AGENT); logonConn.setRequestProperty("Referer", "https://m.lalacaifu.com/mobile-web/views/user/account.html"); logonConn.setRequestProperty("X-Requested-With", "XMLHttpRequest"); logonConn.setRequestProperty("Cookie", COOKIE); logonConn.setRequestProperty("Connection", "keep-alive"); logonConn.setRequestProperty("Cache-Control", "max-age=0"); BufferedReader logonReader = new BufferedReader( new InputStreamReader(logonConn.getInputStream(), "utf-8")); String line = null; int lineNum = 1; while ((line = logonReader.readLine()) != null) { ++lineNum; System.out.println(line); // if (line.contains("formhash=")) { // // formhash = "" // } } }catch(Exception e){ System.out.println(e); } return ""; } static String getDetailPage(int prodId){ try{ //URL logonURL = new URL("https://m.lalacaifu.com/mobile-web/views/product/productDetail.html?proId=3725"); URL logonURL = new URL("https://m.lalacaifu.com/mobile-web/views/product/productDetail.html?proId=" + prodId); URLConnection logonConn = logonURL.openConnection(); logonConn.setDoOutput(true);; logonConn.setRequestProperty("User-agent", USER_AGENT); logonConn.setRequestProperty("Referer", "https://m.lalacaifu.com/mobile-web/views/product/productList.html"); logonConn.setRequestProperty("X-Requested-With", "XMLHttpRequest"); logonConn.setRequestProperty("Cookie", COOKIE); logonConn.setRequestProperty("Connection", "keep-alive"); logonConn.setRequestProperty("Cache-Control", "max-age=0"); BufferedReader logonReader = new BufferedReader( new InputStreamReader(logonConn.getInputStream(), "utf-8")); String line = null; int lineNum = 1; while ((line = logonReader.readLine()) != null) { ++lineNum; System.out.println(line); // if (line.contains("formhash=")) { // // formhash = "" // } } }catch(Exception e){ System.out.println(e); } return ""; } static String getPage(String url){ try{ URL logonURL = new URL(url); //URL logonURL = new URL("https://m.lalacaifu.com/fund/userasset"); URLConnection logonConn = logonURL.openConnection(); logonConn.setDoOutput(true);; logonConn.setRequestProperty("User-agent", USER_AGENT); logonConn.setRequestProperty("X-Requested-With", "XMLHttpRequest"); logonConn.setRequestProperty("Cookie", COOKIE); logonConn.setRequestProperty("Referer", "https://m.lalacaifu.com/mobile-web/views/product/productList.html"); logonConn.setRequestProperty("Upgrade-Insecure-Requests", "1"); logonConn.setRequestProperty("Connection", "keep-alive"); logonConn.setRequestProperty("Cache-Control", "max-age=0"); // // 获得连接输出流 // OutputStreamWriter logonOut = new OutputStreamWriter(logonConn // .getOutputStream()); // logonOut.flush(); // logonOut.close(); BufferedReader logonReader = new BufferedReader( new InputStreamReader(logonConn.getInputStream(), "utf-8")); String line = null; int lineNum = 1; while ((line = logonReader.readLine()) != null) { ++lineNum; System.out.println(line); // if (line.contains("formhash=")) { // // formhash = "" // } } }catch(Exception e){ System.out.println(e); } return ""; } static String getCookie(){ String cookie = ""; try{ URL logonURL = new URL("http://m.lalacaifu.com/verifyCode.htm"); URLConnection logonConn = logonURL.openConnection(); logonConn.setDoOutput(true); logonConn.setRequestProperty("User-agent", USER_AGENT); logonConn.setRequestProperty("Connection", " Keep-Alive"); BufferedReader logonReader = new BufferedReader( new InputStreamReader(logonConn.getInputStream(), "utf-8")); String line = null; while ((line = logonReader.readLine()) != null) { //System.out.println(line); // if (line.contains("formhash=")) { // // formhash = "" // } } Map m = logonConn.getHeaderFields(); List li = (List) m.get("Set-Cookie"); String tmp1 = ""; for (int j = 0; j < li.size(); j++) { String temp = (String) li.get(j); if (temp.startsWith("_SID=")) { String[] te = temp.split(";"); tmp1 = te[0]; } } cookie = tmp1; }catch(Exception e){ System.out.println(e); } return cookie; } static String getLoginPage(){ String cookie = ""; try{ URL logonURL = new URL("https://m.lalacaifu.com/mobile-web/views/user/login.html"); URLConnection logonConn = logonURL.openConnection(); logonConn.setDoOutput(true); logonConn.setRequestProperty("User-agent", USER_AGENT); logonConn.setRequestProperty("Connection", " Keep-Alive"); BufferedReader logonReader = new BufferedReader( new InputStreamReader(logonConn.getInputStream(), "utf-8")); String line = null; while ((line = logonReader.readLine()) != null) { //System.out.println(line); // if (line.contains("formhash=")) { // // formhash = "" // } } }catch(Exception e){ System.out.println(e); } return cookie; } static boolean checkLogin(String userid, String password){ COOKIE = getCookie(); System.out.println(COOKIE); boolean isLogonSuccess = false; try{ URL logonURL = new URL("https://m.lalacaifu.com/user/login"); HttpURLConnection logonConn = (HttpURLConnection)logonURL.openConnection(); logonConn.setDoOutput(true); logonConn.setRequestProperty("Referer", "https://m.lalacaifu.com/mobile-web/views/user/login.html"); logonConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); logonConn.setRequestProperty("Accept-Language", "en-US,zh-CN;q=0.7,ja-JP;q=0.3"); logonConn.setRequestProperty("User-agent", USER_AGENT); logonConn.setRequestProperty("X-Requested-With", "XMLHttpRequest"); logonConn.setRequestProperty("Cookie", COOKIE); logonConn.setRequestProperty("Cache-Control", "no-cache"); logonConn.setRequestProperty("Connection", " Keep-Alive"); logonConn.setInstanceFollowRedirects(false); // 获得连接输出流 OutputStreamWriter logonOut = new OutputStreamWriter(logonConn .getOutputStream()); //logonOut.write("loginName="+userid+"&passWord="+password); logonOut.write("loginName="+userid+"&password="+password); logonOut.flush(); logonOut.close(); BufferedReader logonReader = new BufferedReader( new InputStreamReader(logonConn.getInputStream(), "utf-8")); String line = null; int lineNum = 1; while ((line = logonReader.readLine()) != null) { ++lineNum; System.out.println(line); if (line.contains("\"bool\":true")) { isLogonSuccess = true; } } }catch(Exception e){ } return isLogonSuccess; } static boolean post(int productId, int total){ boolean isLogonSuccess = false; try{ URL logonURL = new URL("https://m.lalacaifu.com/product/buy"); HttpURLConnection logonConn = (HttpURLConnection)logonURL.openConnection(); logonConn.setDoOutput(true); logonConn.setRequestProperty("Accept", "application/json"); logonConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); logonConn.setRequestProperty("Accept-Language", "en-US,zh-CN;q=0.7,ja-JP;q=0.3"); logonConn.setRequestProperty("Accept-Encoding", "gzip, deflate"); logonConn.setRequestProperty("Referer", "https://m.lalacaifu.com/mobile-web/views/product/productDetail.html?proId="+productId); logonConn.setRequestProperty("User-agent", USER_AGENT); logonConn.setRequestProperty("X-Requested-With", "XMLHttpRequest"); logonConn.setRequestProperty("Cache-Control", "no-cache"); logonConn.setRequestProperty("Connection", " Keep-Alive"); logonConn.setRequestProperty("Cookie", COOKIE); //logonConn.setRequestProperty("Upgrade-Insecure-Requests", "1"); logonConn.setInstanceFollowRedirects(false); // 获得连接输出流 OutputStreamWriter logonOut = new OutputStreamWriter(logonConn .getOutputStream()); logonOut.write("investMoney="+total+"&proId="+productId); logonOut.flush(); logonOut.close(); BufferedReader logonReader = new BufferedReader( new InputStreamReader(logonConn.getInputStream(), "utf-8")); String line = null; int lineNum = 1; while ((line = logonReader.readLine()) != null) { ++lineNum; System.out.println(line); // if (line.contains("\"bool\":true")) { // isLogonSuccess = true; // } } }catch(Exception e){ } return isLogonSuccess; } static boolean post1(int productId){ boolean isLogonSuccess = false; try{ URL logonURL = new URL("https://m.lalacaifu.com/product/detail"); HttpURLConnection logonConn = (HttpURLConnection)logonURL.openConnection(); logonConn.setDoOutput(true); logonConn.setRequestProperty("Accept", "application/json"); logonConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); logonConn.setRequestProperty("Accept-Language", "en-US,zh-CN;q=0.7,ja-JP;q=0.3"); logonConn.setRequestProperty("Accept-Encoding", "gzip, deflate"); logonConn.setRequestProperty("Referer", "https://m.lalacaifu.com/mobile-web/views/product/productDetail.html?proId=3725"); logonConn.setRequestProperty("User-agent", USER_AGENT); logonConn.setRequestProperty("X-Requested-With", "XMLHttpRequest"); logonConn.setRequestProperty("Cache-Control", "no-cache"); logonConn.setRequestProperty("Connection", " Keep-Alive"); logonConn.setRequestProperty("Upgrade-Insecure-Requests", "1"); logonConn.setRequestProperty("Cookie", COOKIE); // logonConn.setRequestProperty("Cookie", COOKIE); logonConn.setInstanceFollowRedirects(false); //logonConn.setRequestProperty("Connection", "close"); System.out.println(COOKIE); // 获得连接输出流 OutputStreamWriter logonOut = new OutputStreamWriter(logonConn .getOutputStream()); logonOut.write("proId="+productId); logonOut.flush(); logonOut.close(); BufferedReader logonReader = new BufferedReader( new InputStreamReader(logonConn.getInputStream(), "utf-8")); String line = null; int lineNum = 1; while ((line = logonReader.readLine()) != null) { ++lineNum; System.out.println(line); // if (line.contains("\"bool\":true")) { // isLogonSuccess = true; // } } }catch(Exception e){ } return isLogonSuccess; } }
package org.kuali.ole.service; import org.kuali.ole.ingest.pojo.ProfileAttributeBo; import org.kuali.ole.pojo.OleBibRecord; import org.kuali.ole.pojo.OleOrderRecord; import org.kuali.ole.pojo.bib.BibliographicRecord; import org.kuali.ole.pojo.edi.EDIOrder; import org.kuali.rice.krms.api.engine.EngineResults; import java.util.List; /** * Created with IntelliJ IDEA. * User: vivekb * Date: 2/28/13 * Time: 11:33 AM * To change this template use File | Settings | File Templates. */ public interface OleOrderRecordService { public OleOrderRecord fetchOleOrderRecord(EngineResults engineResult, OleBibRecord oleBibRecord, EDIOrder ediOrder, BibliographicRecord bibliographicRecord, List<ProfileAttributeBo> profileAttributeBos) throws Exception; }
package com.java.practice.array; /** * A binomial coefficient C(n, k) can be defined as the coefficient of X^k in the expansion of (1 + X)^n. * A binomial coefficient C(n, k) also gives the number of ways, disregarding order, * that k objects can be chosen from among n objects; more formally, the number of k-element subsets * (or k-combinations) of an n-element set. * Given two numbers n and r, find value of nCr * <p> * Examples : * <p> * Input : n = 5, r = 2 * Output : 10 * The value of 5C2 is 10 * <p> * Input : n = 3, r = 1 * Output : 3 */ public class Binomial1 { public static void main(String[] args) { long n = 8; long r = 3; long start = System.currentTimeMillis(); // System.out.println(nCr(n, r)); System.out.println("time using recursion :" + (System.currentTimeMillis() - start)); start = System.currentTimeMillis(); System.out.println(nCrEfficient(n, r)); System.out.println("time using efficient approach :" + (System.currentTimeMillis() - start)); } private static long nCr(long n, long r) { //return factorialRecursion(n) / (factorialRecursion(r) * factorialRecursion(n - r)); return factorialIteration(n) / (factorialIteration(r) * factorialIteration(n - r)); } private static long factorialRecursion(long n) { if (n == 0) { return 1; } return n * factorialRecursion(n - 1); } private static long factorialIteration(long n) { if (n == 0) { return 1; } long fact = 1; for (int i = 2; i <= n; i++) { fact *= i; } return fact; } private static long nCrEfficient(long n, long k) { if (k > n - k) { k = n - k; } long res = 1; for (int i = 0; i < k; i++) { res *= (n - i); res /= (i + 1); } return res; } }
package demo.oops; public class PolymorphismDemo { //SAME METHOD NAME WITH DIFFERENT ARGUMENT // public void car(int wheel1, int wheel2) { // System.out.println(wheel1+wheel2); // } // public void car(String Engine) { // System.out.println(Engine); // } // public void car() { // System.out.println("car"); // } // public static void main(String[] args) { // PolymorphismDemo poly = new PolymorphismDemo(); // poly.car(); // poly.car("Range Rover"); // poly.car(4,5); // } //OVERLOADING public int car(int wheel1, int wheel2) { return(wheel1+wheel2); } public String car(String engine) { return engine; } public void car() { System.out.println("car"); } public static void main(String[] args) { PolymorphismDemo poly1= new PolymorphismDemo(); System.out.println((poly1.car(5,6))); System.out.println((poly1.car("Range Rover"))); poly1.car(); } }
package ca.oneroof.oneroof; public class DollarUtils { public static String formatDollars(int cents) { return String.format("%d.%02d", cents / 100, cents % 100); } public static String formatDollarsSign(int cents) { return String.format("$%d.%02d", cents / 100, cents % 100); } }
package com.lmz; public class Print { public static void main(String[] args) { //输出不换行 char a='a'; int b=1; System.out.print(a+","); System.out.println(b); //换行 System.out.println("============================"); System.out.println("END"); //格式化输出 //如果要把数据显示成我们期望的格式,就需要使用格式化输出的功能。 // 格式化输出使用System.out.printf(),通过使用占位符%?,printf()可以把后面的参数格式化成指定格式: double d=12300000; System.out.println(d); double PI=3.141592653; //%f格式化输出浮点数, .2- System.out.printf("%.2f\n",PI); System.out.printf("%.4f",PI); } }
package Db; import java.io.IOException; import java.sql.*; import java.io.File; import java.util.ArrayList; import java.util.Calendar; import com.datacleaning.message.*; import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.Destination; import javax.jms.MessageConsumer; import javax.jms.Session; import javax.jms.TextMessage; import org.apache.activemq.ActiveMQConnection; import org.apache.activemq.ActiveMQConnectionFactory; import Readin.Readin; public class Db { //private static final Connection DbCon = null; private static Calendar c1; static String tcpnumber = "tcp://192.168.8.55:61616"; static String rootpath="E:\\output\\"; public static void main(String args[]) throws IOException { // ConnectionFactory :连接工厂,JMS 用它创建连接 ConnectionFactory connectionFactory; // Connection :JMS 客户端到JMS Provider 的连接 Connection connection = null; // Session: 一个发送或接收消息的线程 Session session; // Destination :消息的目的地;消息发送给谁. Destination destination; // 消费者,消息接收者 MessageConsumer consumer; connectionFactory = new ActiveMQConnectionFactory( ActiveMQConnection.DEFAULT_USER, ActiveMQConnection.DEFAULT_PASSWORD, tcpnumber); Readin reader = new Readin(); Sender fileSender = new Sender(); Calendar c = Calendar.getInstance(); int hour = c.get(Calendar.HOUR_OF_DAY); int minute = c.get(Calendar.MINUTE); int second = c.get(Calendar.SECOND); try { // 构造从工厂得到连接对象 connection = connectionFactory.createConnection(); // 启动 connection.start(); // 获取操作连接 session = connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE); // 获取session注意参数值xingbo.xu-queue是一个服务器的queue,须在在ActiveMq的console配置 destination = session.createQueue("Mdb"); consumer = session.createConsumer(destination); while (true) { //设置接收者接收消息的时间,为了便于测试,这里谁定为100s TextMessage message = (TextMessage) consumer.receive(3000); Thread.sleep(3000); if (null != message) { String s = message.getText(); System.out.println("1收到消息" + s); File file=new File(s); String filename=file.getName(); String name=filename.substring(0, filename.lastIndexOf(".")); readMdb(s,name); fileSender.connection("Txt"); fileSender.sendMessage("E:\\output\\"+name+".txt"); } } } catch (Exception e) { e.printStackTrace(); } finally { try { if (null != connection) connection.close(); } catch (Throwable ignore) { } } c1 = Calendar.getInstance(); int hour1 = c1.get(Calendar.HOUR_OF_DAY); int minute1 = c1.get(Calendar.MINUTE); int second1 = c1.get(Calendar.SECOND); System.out.print(hour+ " "+minute+" "+second); System.out.print(hour1+ " "+minute1+" "+second1); } public static void readMdb(String path,String name) throws IOException{ //存储从每个数据库单元读取的字符串数据 String s=null; //步骤1:加载驱动程序 String sDriver="sun.jdbc.odbc.JdbcOdbcDriver"; try{ Class.forName(sDriver); } catch(Exception e){ System.out.println("无法加载驱动程序"); return; } System.out.println("步骤1:加载驱动程序——成功!"); java.sql.Connection dbCon=null; Statement stmt=null; ResultSet rs = null; String tableName = null; String sCon="jdbc:odbc:cad;DBQ="+path; try{ dbCon=DriverManager.getConnection(sCon); if(dbCon!=null){ System.out.println("步骤2:连接数据库——成功!"); } //步骤3:建立JDBC的Statement对象 stmt=dbCon.createStatement(); if(stmt!=null){ System.out.println("步骤3:建立JDBC的Statement对象——成功!"); } } catch(SQLException e){ System.out.println("连接错误:"+sCon); System.out.println(e.getMessage()); if(dbCon!=null){ try{ dbCon.close(); } catch(SQLException e2){} } return; } try{//执行数据库查询,返回结果 Readin reader = new Readin(); java.sql.Connection conn = DriverManager.getConnection(sCon); ResultSet tables = conn.getMetaData().getTables( path, null, null, new String[] { "TABLE" }); // 获取第一个表名 if (tables.next()) { tableName = tables.getString(3);// getXXX can only be used once } else { return; } stmt = (Statement) conn.createStatement(); // 读取第一个表的内容 rs = stmt.executeQuery("select * from " + tableName); ResultSetMetaData data = rs.getMetaData(); while (rs.next()) { for (int i = 1; i <= data.getColumnCount(); i++) { s=rs.getString(i); //System.out.print(s + " "); if(s==null) reader.writeStrToFile("null"+"\\s",rootpath+name+".txt",0); else reader.writeStrToFile(s+"\\s",rootpath+name+".txt",0); } reader.writeStrToFile("\\s",rootpath+name+".txt",1); //System.out.println(); } /* dbCon=DriverManager.getConnection(sCon); DatabaseMetaData meta = dbCon.getMetaData(); String tt, tp; ResultSet rs = meta.getTables(null, null, null, null); while (rs.next()) { tt = rs.getString("TABLE_NAME"); tp = rs.getString("TABLE_TYPE"); System.out.println(" 表的名称 " + tt + " 表的类型 " + tp); } // 关闭连接 dbCon.close(); /*rs=stmt.executeQuery(sSQL); ResultSetMetaData rsm = rs.getMetaData(); int size = rsm.getColumnCount(); while (rs.next()) { for (int i = 1; i <= size; i++) { if (i > 1) System.out.print(", "); String columnValue = rs.getString(i); System.out.print(columnValue + " " + rsm.getColumnName(i)); } System.out.println(""); } /*dbCon=DriverManager.getConnection(sCon); DatabaseMetaData meta = dbCon.getMetaData(); ResultSet rs = meta.getTables(null, null, null, new String[] { "TABLE" }); while (rs.next()) { System.out.println("表名:" + rs.getString(3)); System.out.println("表所属用户名:" + rs.getString(2)); System.out.println("------------------------------"); } dbCon.close(); String sql4="SELECT * FROM acd WHERE Flags=0 AND Type=1"; rs=stmt.executeQuery(sql4); while(rs.next()){ System.out.println(rs.getString("name")); } */ } catch(SQLException e){ System.out.println(e.getMessage()); } finally{ try{ //关闭步骤3所开启的statement对象 stmt.close(); System.out.println("关闭statement对象"); } catch(SQLException e){} try{ //关闭数据库连接 dbCon.close(); System.out.println("关闭数据库连接对象"); } catch(SQLException e){} } } }
package cn.wangjy.study.trywithresources; import java.io.*; import java.util.zip.GZIPOutputStream; /** * TODO ADD DESCRIPTION * * @author wangjieyao * @Date 2017/5/24 11:30 */ public class TryWithResource { public static void main(String[] args) { //传统的try cache finally try{ test(); } catch (Exception e) { e.printStackTrace(); } //try-with-resources try(Connection conn =new Connection()) { conn.sendData(); } catch(Exception e) { e.printStackTrace(); } //try-with-resources 声明多个资源 try (FileInputStream fin = new FileInputStream(new File("input.txt")); FileOutputStream fout = new FileOutputStream(new File("out.txt")); GZIPOutputStream out = new GZIPOutputStream(fout)) { byte[] buffer = new byte[4096]; int read; while ((read = fin.read(buffer)) != -1) { out.write(buffer, 0, read); } } catch (IOException e) { e.printStackTrace(); } } private static void test() throws Exception { Connection conn = null; try { conn = new Connection(); conn.sendData(); } finally { if (conn != null) { conn.close(); } } } }
package model; import integration.Printer; import integration.SaleDTO; import util.Amount; public class Payment { private SaleDTO saleDTO; private Printer printer; private Amount amountPaid = new Amount(0); private Amount currentChange = new Amount(0); /** * Constructor, Save the passed Sales information and creates a printer. * @param saleDTO */ public Payment(SaleDTO saleDTO) { this.saleDTO = saleDTO; printer = new Printer(); } /** * Verify the payment by checking against running total and calculate the change. * If the payment is ok, we print a receipt. * @param amount * @return */ public void verify(Amount amount) { amountPaid = amountPaid.add(amount); currentChange = amountPaid.subtract(saleDTO.getRunningTotal()); if(amountPaid.getValue() >= saleDTO.getRunningTotal().getValue()) { printer.printReceipt(new Receipt(saleDTO, amountPaid, currentChange)); } else { System.out.println("Payed amount: " + amountPaid); System.out.println("missing amount: " + currentChange.negate()); } } /** * Retrieve the current amount payed. * @return */ public Amount getAmountPaid() { return amountPaid; } }
package com.typecasting_concept; public class ExplicitTypecasting { public static void main(String[] args) { /*double d = 10024.34345; float f = (float)d; System.out.println(f); int i = (int)f; System.out.println(i); short s = (short)i; System.out.println(s); byte b = (byte)s; System.out.println(b);*/ int a = 00000010; int c = a<<2; System.out.println(c); } }
/* * 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.aot.hint.support; import java.lang.reflect.Proxy; import java.util.function.Consumer; import org.springframework.aot.hint.MemberCategory; import org.springframework.aot.hint.RuntimeHints; import org.springframework.aot.hint.TypeHint; import org.springframework.util.ClassUtils; /** * Utilities for core hint inference on Spring-managed classes, * specifically for proxy types such as interface-based JDK proxies * and CGLIB-generated subclasses which need proxy/reflection hints. * * <p>Note that this class does not take specifics of Spring AOP or * any other framework arrangement into account. It just operates * on the JDK and CGLIB proxy facilities and their core conventions. * * @author Juergen Hoeller * @author Sebastien Deleuze * @since 6.0.3 * @see org.springframework.aot.hint.ProxyHints * @see org.springframework.aot.hint.ReflectionHints */ public abstract class ClassHintUtils { private static final Consumer<TypeHint.Builder> asClassBasedProxy = hint -> hint.withMembers(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.INVOKE_DECLARED_METHODS, MemberCategory.DECLARED_FIELDS); private static final Consumer<TypeHint.Builder> asProxiedUserClass = hint -> hint.withMembers(MemberCategory.INVOKE_PUBLIC_METHODS, MemberCategory.INVOKE_DECLARED_METHODS); /** * Register a proxy hint for a JDK proxy or corresponding reflection hints * for a CGLIB-generated subclass, if necessary. * @param candidateClass the class to introspect * @param runtimeHints the RuntimeHints instance to register the hints on * @see Proxy#isProxyClass(Class) * @see ClassUtils#getUserClass(Class) */ public static void registerProxyIfNecessary(Class<?> candidateClass, RuntimeHints runtimeHints) { if (Proxy.isProxyClass(candidateClass)) { // A JDK proxy class needs an explicit hint runtimeHints.proxies().registerJdkProxy(candidateClass.getInterfaces()); } else { // Potentially a CGLIB-generated subclass with reflection hints Class<?> userClass = ClassUtils.getUserClass(candidateClass); if (userClass != candidateClass) { runtimeHints.reflection() .registerType(candidateClass, asClassBasedProxy) .registerType(userClass, asProxiedUserClass); } } } }
package com.fsj.action; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.HashMap; import java.util.Map; import com.fsj.entity.Pricetrend; import com.fsj.entity.Pager; import com.fsj.service.PricetrendDAO; import com.fsj.service.impl.PricetrendDAOImpl; //价格走势Action动作类 public class PricetrendAction extends SuperAction { private static final long serialVersionUID = 1L; // 保存总页数 public Pager<Pricetrend> getPageCount(String hql, Map<String, Object> map) { // 定义业务逻辑类的对象 Pager<Pricetrend> pager = new Pager<Pricetrend>(); PricetrendDAO pricetrenddao = new PricetrendDAOImpl(); pager.setRowCount(pricetrenddao.queryAll(hql, map));// 总记录数 // 将传出的集合数据list放入session中,首先判断list数据 if (pager.getRowCount() > 0) { // 在session中保存 int t1 = pager.getRowCount() % pager.getPageSize(); int t2 = pager.getRowCount() / pager.getPageSize(); pager.setPageCount(t1 == 0 ? t2 : t2 + 1); } else { pager.setPageCount(0); } return pager; } // 获取当前页数 public int getPageNumber() { String number = request.getParameter("pageNumber"); if (number == null) { return 1; } else { int pageNumber = Integer.parseInt(number); // 获得传过来的pageNumber值 return pageNumber; } } // 实现查询所有价格走势的操作(可选查询条件:记录日期,记录级别,所属房屋) public String query() { StringBuffer hql = new StringBuffer(); hql.append("select count(ptid) from Pricetrend as pricetrend where 1=1 "); Map<String, Object> map = new HashMap<String, Object>(); if (request.getParameter("recorddate") != null && request.getParameter("recorddate").length() > 0) { try { map.put("recorddate", new SimpleDateFormat("yyyy-MM-dd") .parse(request.getParameter("recorddate"))); hql.append("and pricetrend.recorddate like :recorddate "); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (request.getParameter("grade") != null && request.getParameter("grade").length() > 0) { map.put("grade", request.getParameter("grade")); hql.append("and pricetrend.grade like :grade "); } if (request.getParameter("house") != null && request.getParameter("house").length() > 0) { map.put("house", Integer.parseInt(request.getParameter("house"))); hql.append("and pricetrend.house.hid like :house "); } String queryHql = hql.substring(19); // 定义业务逻辑类的对象 Pager<Pricetrend> pager = getPageCount(hql.toString(), map); PricetrendDAO pricetrenddao = new PricetrendDAOImpl(); pager.setPageNo(getPageNumber()); pager.setResult(pricetrenddao.querypage(pager.getPageNo(), pager.getPageSize(), queryHql, map)); // 将传出的集合数据list放入session中,首先判断list数据 if (pager.getResult() != null && pager.getResult().size() > 0) { // 在session中保存list信息到list中,将来可以调用 session.setAttribute("pager", pager); } return "query"; } // 添加价格走势操作 public String add() throws Exception { Pricetrend pricetrend = new Pricetrend(); PricetrendDAO pricetrenddao = new PricetrendDAOImpl(); pricetrenddao.addPricetrend(setAll(pricetrend)); return "operationsuccess"; } // 更新价格走势操作 public String save() throws Exception { Pricetrend pricetrend = new Pricetrend(); PricetrendDAO pricetrenddao = new PricetrendDAOImpl(); pricetrenddao.updatePricetrend(setAll(pricetrend)); return "operationsuccess"; } // 删除价格走势操作 public String delete() { // 定义价格走势业务逻辑类的对象 PricetrendDAO pricetrenddao = new PricetrendDAOImpl(); int ptid = Integer.parseInt(request.getParameter("ptid")); // 获得传过来的要删除价格走势的id值 pricetrenddao.deletePricetrend(ptid); return "operationsuccess"; } // 持久化类 public Pricetrend setAll(Pricetrend pricetrend) throws Exception { return pricetrend; } }
package wepa.news.controller.mvc; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import wepa.news.repository.CategoryRepository; @Controller public class PublicController { @Autowired CategoryRepository categoryRepository; @GetMapping("/") public String index(Model model) { model.addAttribute("categories", categoryRepository.findByDisplayInNavigation(true)); model.addAttribute("currentCategory", ""); // = all categories return "index"; } @GetMapping("{categoryName}") public String indexByCategory(@PathVariable String categoryName, Model model) { model.addAttribute("categories", categoryRepository.findByDisplayInNavigation(true)); model.addAttribute("currentCategory", categoryName); return "index"; } }
package com.webstore.shoppingcart.controller; import java.util.List; import javax.validation.Valid; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.webstore.shoppingcart.controller.base.ControllerBase; import com.webstore.shoppingcart.dto.request.ShoppingCartItemRequestDTO; import com.webstore.shoppingcart.dto.response.ResponseDTO; import com.webstore.shoppingcart.dto.response.ShoppingCartResponseDTO; import com.webstore.shoppingcart.service.ShoppingCartService; @RestController @RequestMapping(path = "/api/v1/shoppingCarts") public class ShoppingCartController extends ControllerBase { private static final Logger LOG = LoggerFactory.getLogger(ShoppingCartController.class); @Autowired private ShoppingCartService service; @PostMapping(path = "/user/{id}/addItems") public ResponseEntity<ResponseDTO<ShoppingCartResponseDTO>> addItems(@Valid @RequestBody ShoppingCartItemRequestDTO request, @PathVariable(value = "id") String id) { LOG.debug("Initializing POST in /api/v1/shoppingCarts/user/{id}/addItems with request {} and id {}", request, id); ShoppingCartResponseDTO response = service.addItems(request, id); LOG.debug("Finishing POST in /api/v1/shoppingCarts/user/{id}/addItems with response {}", response); return ResponseEntity. status(HttpStatus.OK). body(new ResponseDTO<>(response)); } @GetMapping(path = "/user/{id}/findPending") public ResponseEntity<ResponseDTO<ShoppingCartResponseDTO>> findPendingByUser(@PathVariable(value = "id") String id) { LOG.debug("Initializing GET in /api/v1/shoppingCarts/user/{id}/findPending with id {}", id); ShoppingCartResponseDTO response = service.findPendingByUser(id); LOG.debug("Finishing GET in /api/v1/shoppingCarts/user/{id}/findPending with response {}", response); return ResponseEntity. status(HttpStatus.OK). body(new ResponseDTO<>(response)); } @PostMapping(path = "/user/{id}/finish") public ResponseEntity<ResponseDTO<ShoppingCartResponseDTO>> finishByUser(@PathVariable(value = "id") String id) { LOG.debug("Initializing POST in /api/v1/shoppingCarts/user/{id}/finish with and id {}", id); ShoppingCartResponseDTO response = service.finishByUser(id); LOG.debug("Finishing POST in /api/v1/shoppingCarts/user/{id}/finish with response {}", response); return ResponseEntity. status(HttpStatus.OK). body(new ResponseDTO<>(response)); } @GetMapping(path = "/findAll") public ResponseEntity<ResponseDTO<List<ShoppingCartResponseDTO>>> findAll() { LOG.debug("Initializing GET in /api/v1/shoppingCarts/findAll"); List<ShoppingCartResponseDTO> response = service.findAll(); LOG.debug("Finishing GET in /api/v1/shoppingCarts/findAll with response {}", response); return ResponseEntity. status(HttpStatus.OK). body(new ResponseDTO<>(response)); } @GetMapping(path = "/findPending") public ResponseEntity<ResponseDTO<List<ShoppingCartResponseDTO>>> findPending() { LOG.debug("Initializing GET in /api/v1/shoppingCarts/findPending"); List<ShoppingCartResponseDTO> response = service.findPending(); LOG.debug("Finishing GET in /api/v1/shoppingCarts/findPending with response {}", response); return ResponseEntity. status(HttpStatus.OK). body(new ResponseDTO<>(response)); } }
/** * */ package de.fraunhofer.iese.ids.odrl.policy.library.model.tooling; import java.io.IOException; import java.util.Map; import com.fasterxml.jackson.core.JsonParseException; import com.github.jsonldjava.utils.JsonUtils; import de.fraunhofer.iese.ids.odrl.policy.library.model.OdrlPolicy; /** * @author Robin Brandstaedter <Robin.Brandstaedter@iese.fraunhofer.de> * */ public class IdsOdrlUtil { @SuppressWarnings("rawtypes") public static Map getMapOfJsonString(String odrlPolicyString) { Map odrlPolicyMap = null; try { Object o = JsonUtils.fromString(odrlPolicyString); if (o instanceof Map) { odrlPolicyMap = (Map) o; } } catch (JsonParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return odrlPolicyMap; } public static OdrlPolicy getOdrlPolicy(@SuppressWarnings("rawtypes") Map map) { return PatternUtil.getPolicy(map, true); } @SuppressWarnings("rawtypes") public static OdrlPolicy getOdrlPolicy(String odrlPolicyString) { Map map = getMapOfJsonString(odrlPolicyString); return PatternUtil.getPolicy(map, true); } }
package com.zhiyou.mapper; import java.util.List; import com.zhiyou.model.Course; import com.zhiyou.model.Coursec; public interface CourseMapper { public void add(Course course); public void update(Course course); public List<Coursec> selectAllLimit(int page, int number); public Course selectById(Integer id); public List<Course> selectAll(); public void delete(Integer[] ids); public int selectCount(); public List<Course> selectBySubject(Integer subject_id); }
package com.g74.rollersplat.viewer.game; import com.g74.rollersplat.model.elements.Position; import com.g74.rollersplat.viewer.gui.GUI; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import java.io.IOException; public class LoseViewerTest { private LoseViewer viewer; private GUI gui; @BeforeEach void setUp() throws IOException { gui = Mockito.mock(GUI.class); viewer = new LoseViewer(gui); } @Test void draw() throws IOException { String lose = "YOU LOSE"; String color = "#FF6347"; Position pos = new Position(19, 10); viewer.draw(); Mockito.verify(gui, Mockito.times(1)).clear(); Mockito.verify(gui, Mockito.times(1)).drawBackground(); Mockito.verify(gui, Mockito.times(1)).drawGivenChar(pos, color, lose); Mockito.verify(gui, Mockito.times(1)).refresh(); } }
import java.util.*; import java.io.*; /** * Priyanka Pathak * COMS 3134 - Fall 2010 * Homework Assignment Four - Maze Assignment * December 16, 2010 * */ public class Cell implements Serializable{ //Defines a cell by declaring four booleans indicated the existence of a wall, and their corresponding weights private static Random random = new Random(); public boolean left = true; public int wLeft; public boolean right = true; public int wRight; public boolean top = true; public int wTop; public boolean bottom = true; public int wBottom; public int distance = Integer.MAX_VALUE; public boolean visited = false; public void knockDownWall(int i){ switch(i){ case 0: left = false; break; case 1: right = false; break; case 2: top = false; break; case 3: bottom = false; break; } } }
package org.exoplatform.management.ecmadmin.operations.drive; import java.util.Iterator; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import org.exoplatform.container.PortalContainer; import org.exoplatform.container.xml.ComponentPlugin; import org.exoplatform.container.xml.Configuration; import org.exoplatform.container.xml.ExternalComponentPlugins; import org.exoplatform.container.xml.InitParams; import org.exoplatform.container.xml.ObjectParameter; import org.exoplatform.management.ecmadmin.operations.ECMAdminImportResource; import org.exoplatform.services.cms.drives.DriveData; import org.exoplatform.services.cms.drives.ManageDriveService; import org.exoplatform.services.cms.drives.impl.ManageDrivePlugin; import org.exoplatform.services.cms.drives.impl.ManageDriveServiceImpl; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.gatein.management.api.exceptions.OperationException; import org.gatein.management.api.operation.OperationContext; import org.gatein.management.api.operation.OperationNames; import org.gatein.management.api.operation.ResultHandler; import org.gatein.management.api.operation.model.NoResultModel; import org.jibx.runtime.BindingDirectory; import org.jibx.runtime.IBindingFactory; import org.jibx.runtime.IUnmarshallingContext; /** * @author <a href="mailto:bkhanfir@exoplatform.com">Boubaker Khanfir</a> * @version $Revision$ */ public class DriveImportResource extends ECMAdminImportResource { private static final Log log = ExoLogger.getLogger(DriveImportResource.class); private ManageDriveService driveService; public DriveImportResource() { super(null); } public DriveImportResource(String filePath) { super(filePath); } @Override public void execute(OperationContext operationContext, ResultHandler resultHandler) throws OperationException { // get attributes and attachement inputstream super.execute(operationContext, resultHandler); if (driveService == null) { driveService = operationContext.getRuntimeContext().getRuntimeComponent(ManageDriveService.class); } try { ZipInputStream zin = new ZipInputStream(attachmentInputStream); ZipEntry ze = null; while ((ze = zin.getNextEntry()) != null) { if (!ze.getName().startsWith("drive/")) { continue; } if (ze.getName().endsWith("drives-configuration.xml")) { IBindingFactory bfact = BindingDirectory.getFactory(Configuration.class); IUnmarshallingContext uctx = bfact.createUnmarshallingContext(); Configuration configuration = (Configuration) uctx.unmarshalDocument(zin, "UTF-8"); ExternalComponentPlugins externalComponentPlugins = configuration.getExternalComponentPlugins(ManageDriveService.class .getName()); List<ComponentPlugin> componentPlugins = externalComponentPlugins.getComponentPlugins(); for (ComponentPlugin componentPlugin : componentPlugins) { Class<?> pluginClass = Class.forName(componentPlugin.getType()); ManageDrivePlugin cplugin = (ManageDrivePlugin) PortalContainer.getInstance().createComponent(pluginClass, componentPlugin.getInitParams()); cplugin.setName(componentPlugin.getName()); cplugin.setDescription(componentPlugin.getDescription()); // TODO add setManageDrivePlugin in Interface // ManageDriveService ((ManageDriveServiceImpl) driveService).setManageDrivePlugin(cplugin); // Delete existing drives if replaceExisting=true if (replaceExisting) { deleteExistingDrives(componentPlugin); } } } zin.closeEntry(); } zin.close(); driveService.init(); } catch (Exception exception) { throw new OperationException(OperationNames.IMPORT_RESOURCE, "Error while importing ECMS drives.", exception); } resultHandler.completed(NoResultModel.INSTANCE); } private void deleteExistingDrives(ComponentPlugin componentPlugin) throws Exception { InitParams params_ = componentPlugin.getInitParams(); @SuppressWarnings("unchecked") Iterator<ObjectParameter> it = params_.getObjectParamIterator(); while (it.hasNext()) { DriveData data = (DriveData) it.next().getObject(); DriveData storedDriveData = driveService.getDriveByName(data.getName()); if (storedDriveData != null) { log.info("Overwrite existing drive '" + data.getName() + "'."); driveService.removeDrive(data.getName()); } } } }
/* * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.socket.handler; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.web.socket.CloseStatus; import org.springframework.web.socket.WebSocketHandler; import org.springframework.web.socket.WebSocketMessage; import org.springframework.web.socket.WebSocketSession; /** * An exception handling {@link WebSocketHandlerDecorator}. * Traps all {@link Throwable} instances that escape from the decorated * handler and closes the session with {@link CloseStatus#SERVER_ERROR}. * * @author Rossen Stoyanchev * @since 4.0 */ public class ExceptionWebSocketHandlerDecorator extends WebSocketHandlerDecorator { private static final Log logger = LogFactory.getLog(ExceptionWebSocketHandlerDecorator.class); public ExceptionWebSocketHandlerDecorator(WebSocketHandler delegate) { super(delegate); } @Override public void afterConnectionEstablished(WebSocketSession session) { try { getDelegate().afterConnectionEstablished(session); } catch (Exception ex) { tryCloseWithError(session, ex, logger); } } @Override public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) { try { getDelegate().handleMessage(session, message); } catch (Exception ex) { tryCloseWithError(session, ex, logger); } } @Override public void handleTransportError(WebSocketSession session, Throwable exception) { try { getDelegate().handleTransportError(session, exception); } catch (Exception ex) { tryCloseWithError(session, ex, logger); } } @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) { try { getDelegate().afterConnectionClosed(session, closeStatus); } catch (Exception ex) { if (logger.isWarnEnabled()) { logger.warn("Unhandled exception after connection closed for " + this, ex); } } } public static void tryCloseWithError(WebSocketSession session, Throwable exception, Log logger) { if (logger.isErrorEnabled()) { logger.error("Closing session due to exception for " + session, exception); } if (session.isOpen()) { try { session.close(CloseStatus.SERVER_ERROR); } catch (Throwable ex) { // ignore } } } }
package com.xianzaishi.wms.tmscore.vo; import com.xianzaishi.wms.tmscore.vo.DistributionBoxStatuVO; public class DistributionBoxStatuDO extends DistributionBoxStatuVO { }
import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.event.Event; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.chart.PieChart; import javafx.scene.control.*; import javafx.scene.input.MouseEvent; import javafx.scene.layout.*; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import javafx.scene.text.Text; import javafx.scene.text.TextFlow; import javafx.stage.Stage; import javafx.stage.Window; import java.sql.Date; import java.time.LocalDate; import java.time.ZoneId; import java.util.ArrayList; import java.util.concurrent.TimeUnit; public class SceneSetter { private Stage window; private User loggedInUser; private String customerOrEmployee; AccountManager am; TheaterManager tm; PaymentManager pm; //Used for screen where user inputs their seats private int numberSeatsSelected; public SceneSetter(Stage w){ window = w; numberSeatsSelected = 0; am = new AccountManager(); tm = new TheaterManager(); pm = new PaymentManager(); } public Scene firstScene(){ Scene customerScene = getLoginScene("customer"); Scene employeeScene = getLoginScene("employee"); //Info label Label info = new Label("Welcome to Movie Tickets!"); //Login Buttons Button cusLogin = new Button(); cusLogin.setText("Customer Login"); cusLogin.getStyleClass().add("button"); cusLogin.setId("cusLogin"); cusLogin.setOnAction(e -> window.setScene(customerScene)); //Lambda expression Button empLogin = new Button(); empLogin.setText("Employee Login"); empLogin.getStyleClass().add("button"); empLogin.setId("empLogin"); empLogin.setOnAction(e -> window.setScene(employeeScene)); VBox layout = new VBox(20); layout.setAlignment(Pos.CENTER); layout.getChildren().addAll(info, cusLogin, empLogin); Scene scene = new Scene(layout, 1280, 720); scene.getStylesheets().add("styles.css"); return scene; } public Scene getLoginScene(String cusOrEmp){ customerOrEmployee = cusOrEmp; VBox mainLayout = new VBox(); mainLayout.setAlignment(Pos.CENTER); mainLayout.setSpacing(-50.0); //Make everything tighter Label loginLabel = new Label("Login"); mainLayout.getChildren().add(loginLabel); GridPane grid = new GridPane(); grid.setPadding(new Insets(100, 100, 100 ,100)); //Border to window grid.setVgap(10); //Set vertical spacing grid.setHgap(10); //Set horizontal spacing grid.setAlignment(Pos.CENTER); //Login stuff //Email Label Label emailLogin = new Label("Email: "); GridPane.setConstraints(emailLogin, 0, 0); //Email Input TextField emailInputLogin = new TextField(); emailInputLogin.setPromptText("email"); GridPane.setConstraints(emailInputLogin, 1, 0); //Pass Label Label passLogin = new Label("Password: "); GridPane.setConstraints(passLogin, 0, 1); //Password Input PasswordField passInputLogin = new PasswordField(); passInputLogin.setPromptText("password"); GridPane.setConstraints(passInputLogin, 1, 1); //Login Button - Need to set onclick listener to verify from account manager and proceed to next screen Button loginButton = new Button("Login"); loginButton.getStyleClass().add("button"); GridPane.setConstraints(loginButton, 1, 2); //Add all to grid grid.getChildren().addAll(emailLogin, emailInputLogin, passLogin, passInputLogin, loginButton); //Add Login Grid to VBox mainLayout.getChildren().add(grid); //Sign up Stuff - ONLY IF USER IS A CUSTOMER if(customerOrEmployee.equals("customer")) { loginButton.setOnAction(e -> loginClickedCustomer(emailInputLogin, passInputLogin)); Label signupLabel = new Label("Sign up"); mainLayout.getChildren().add(signupLabel); //Signup Grid GridPane signup = new GridPane(); signup.setPadding(new Insets(100, 100, 100, 100)); //Border to window signup.setVgap(10); //Set vertical spacing signup.setHgap(10); //Set horizontal spacing signup.setAlignment(Pos.CENTER); //Signup name Label nameSignup = new Label("Name: "); GridPane.setConstraints(nameSignup, 0, 0); //Name input TextField nameInputSignup = new TextField(); nameInputSignup.setPromptText("name"); GridPane.setConstraints(nameInputSignup, 1, 0); //Signup email Label emailSignup = new Label("Email: "); GridPane.setConstraints(emailSignup, 0, 1); //Email input TextField emailInputSignup = new TextField(); emailInputSignup.setPromptText("email"); GridPane.setConstraints(emailInputSignup, 1, 1); //Signup Password Label passwordSignup = new Label("Password:"); GridPane.setConstraints(passwordSignup, 0, 2); //Signup password input PasswordField passwordSignupInput = new PasswordField(); passwordSignupInput.setPromptText("password"); GridPane.setConstraints(passwordSignupInput, 1, 2); //Signup confirmPassword Label confPassSignup = new Label("Confirm Password:"); GridPane.setConstraints(confPassSignup, 0, 3); //Signup confirmPassword input PasswordField confPassInput = new PasswordField(); confPassInput.setPromptText("confirm password"); GridPane.setConstraints(confPassInput, 1, 3); //Credit card num input Label creditCardNum = new Label("Credit Card Number: "); GridPane.setConstraints(creditCardNum, 0, 4); //Credit card num input TextField creditInput = new TextField(); creditInput.setPromptText("credit card number"); GridPane.setConstraints(creditInput, 1, 4); //Credit card exp date Label creditCardDate = new Label("Credit Card Exp Date: "); GridPane.setConstraints(creditCardDate, 0, 5); //Credit card exp date input DatePicker dp = new DatePicker(); GridPane.setConstraints(dp, 1, 5); //Credit card security code Label secCode = new Label("Security Code: "); GridPane.setConstraints(secCode, 0, 6); //Credit card security code input TextField secCodeInput = new TextField(); secCodeInput.setPromptText("security code"); GridPane.setConstraints(secCodeInput, 1, 6); //Credit card zip code Label zipCode = new Label("Zip Code: "); GridPane.setConstraints(zipCode, 0, 7); //Zip code input TextField zipCodeInput = new TextField(); zipCodeInput.setPromptText("zip code"); GridPane.setConstraints(zipCodeInput, 1, 7); //Add all to signup grid signup.getChildren().addAll(nameSignup, nameInputSignup, emailSignup, emailInputSignup, passwordSignup, passwordSignupInput, confPassSignup, confPassInput, creditCardNum, creditInput, creditCardDate, dp, secCode, secCodeInput, zipCode, zipCodeInput); //Signup button Button signupButton = new Button("Sign up"); signupButton.getStyleClass().add("button"); signupButton.setOnAction(e -> signupClicked(nameInputSignup, emailInputSignup, passwordSignupInput, confPassInput, creditInput, dp, secCodeInput, zipCodeInput)); GridPane.setConstraints(signupButton, 1, 8); signup.getChildren().add(signupButton); //Add Signup grid to VBox mainLayout.getChildren().add(signup); } else { loginButton.setOnAction(e -> loginClickedEmployee(emailInputLogin, passInputLogin)); } //Add back button Button backButton = new Button("Back"); backButton.getStyleClass().add("button"); backButton.setOnAction(e -> window.setScene(firstScene())); mainLayout.getChildren().add(backButton); Scene scene = new Scene(mainLayout, 1280, 720); scene.getStylesheets().add("styles.css"); return scene; } private void loginClickedCustomer(TextField email, TextField password){ if(am.customerSignin(email.getText(), password.getText())){ //Correct username and password //Go to movie selection screen loggedInUser = am.getPaymentInfo(email.getText()); window.setScene(getTheaterScene()); } } private void loginClickedEmployee(TextField email, TextField password){ if(am.employeeSignin(email.getText(), password.getText())){ //Correct username and password //Go to movie selection screen loggedInUser = am.getEmployee(email.getText()); window.setScene(getTheaterScene()); } } private void signupClicked(TextField name, TextField email, PasswordField pass, PasswordField confPass, TextField creditNum, DatePicker dp, TextField secCode, TextField zipCode) { //Convert LocalDate object from dp to Date object because createCustomerAccount inside of AccountManager needs a Date object LocalDate ld = dp.getValue(); java.sql.Date sqlDate = java.sql.Date.valueOf(ld.toString()); if(am.createCustomerAccount(name.getText(), email.getText(), pass.getText(), confPass.getText(), creditNum.getText(), sqlDate, secCode.getText(), zipCode.getText())){ //Signup successful, go to movie selection screen window.setScene(getTheaterScene()); } else { System.out.println("Error creating account"); } } public Scene getTheaterScene(){ VBox mainLayout = new VBox(); mainLayout.setAlignment(Pos.CENTER); Label loginLabel = new Label("All Movies For Today"); mainLayout.getChildren().add(loginLabel); GridPane grid = new GridPane(); grid.setPadding(new Insets(100, 100, 100 ,100)); //Border to window grid.setVgap(10); //Set vertical spacing grid.setHgap(10); //Set horizontal spacing grid.setAlignment(Pos.CENTER); ArrayList<String> movies = tm.getMovieNames(); for(int i = 0; i < movies.size(); i++){ Label movieNameLabel = new Label(movies.get(i)); GridPane.setConstraints(movieNameLabel, 0, i); grid.getChildren().add(movieNameLabel); ArrayList<Showing> showings = tm.getShowings(movies.get(i)); for(int j = 0; j < showings.size(); j++){ final int movieID = j; UtilityMethods um = new UtilityMethods(); Hyperlink theaterLink = new Hyperlink(um.formatTime(showings.get(movieID).showtime)); theaterLink.setOnAction(e -> window.setScene(getSeatSelectionScreen(showings.get(movieID).id))); GridPane.setConstraints(theaterLink, j+1, i); grid.getChildren().add(theaterLink); } } mainLayout.getChildren().add(grid); //Bottom nav bar for buttons. Only has 1 for customer but has multiple for manager or employee HBox bottomNavBar = new HBox(); bottomNavBar.setAlignment(Pos.CENTER); bottomNavBar.setSpacing(10.0); Button backButton = new Button("Logout"); backButton.setOnAction(e -> window.setScene(firstScene())); bottomNavBar.getChildren().add(backButton); mainLayout.getChildren().add(bottomNavBar); //Additional Stuff if user is employee if(loggedInUser instanceof Employee){ Employee emp = (Employee) loggedInUser; Button snackPurchaseButton = new Button("Snack Purchases"); snackPurchaseButton.setOnAction(e -> window.setScene(snackPurchaseScene())); bottomNavBar.getChildren().add(snackPurchaseButton); //Additional Stuff if user is manager if(emp.isManager()){ Button addEmployeeButton = new Button("Add Employee"); addEmployeeButton.setOnAction(e -> window.setScene(addEmployeeScene())); Button revenueButton = new Button("View Revenue Data"); revenueButton.setOnAction(e -> window.setScene(revenueScene())); Button movieManagerButton = new Button("Movie Manager"); movieManagerButton.setOnAction(e -> window.setScene(movieManager())); bottomNavBar.getChildren().addAll(addEmployeeButton, revenueButton, movieManagerButton); } } Scene scene = new Scene(mainLayout, 1280, 720); return scene; } public Scene movieManager(){ VBox mainLayout = new VBox(); mainLayout.setAlignment(Pos.CENTER); mainLayout.setSpacing(10.0); HBox moviesVsAddMovieTitles = new HBox(); moviesVsAddMovieTitles.setSpacing(300.0); moviesVsAddMovieTitles.setAlignment(Pos.CENTER); Label addMovie = new Label("Add Movie"); moviesVsAddMovieTitles.getChildren().add(addMovie); Label removeMovies = new Label("Remove Movies"); moviesVsAddMovieTitles.getChildren().add(removeMovies); mainLayout.getChildren().add(moviesVsAddMovieTitles); HBox actualForms = new HBox(); actualForms.setSpacing(100.0); actualForms.setAlignment(Pos.CENTER); GridPane addMovieGrid = new GridPane(); addMovieGrid.setAlignment(Pos.CENTER); addMovieGrid.setHgap(10.0); addMovieGrid.setVgap(10.0); //Movie name Label movieNameLabel = new Label("Movie Name: "); GridPane.setConstraints(movieNameLabel, 0, 0); TextField movieName = new TextField(); movieName.setPromptText("movie name"); GridPane.setConstraints(movieName, 1, 0); //Theater Number Label theaterNumber = new Label("Theater Number"); GridPane.setConstraints(theaterNumber, 0, 1); ObservableList<Integer> theaterNumbers = FXCollections.observableArrayList( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ); final ComboBox theaterNumberDropDown = new ComboBox(theaterNumbers); theaterNumberDropDown.getSelectionModel().selectFirst(); theaterNumberDropDown.setPrefWidth(175.0); GridPane.setConstraints(theaterNumberDropDown, 1, 1); //Time Label timeLabel = new Label("Time: "); GridPane.setConstraints(timeLabel, 0, 2); TextField time = new TextField(); time.setPromptText("24hr time (1230)"); GridPane.setConstraints(time, 1, 2); //Button to add movie Button addMovieBtn = new Button("Add Movie"); GridPane.setConstraints(addMovieBtn, 0, 3); addMovieBtn.setOnAction(e -> addMovieBtnClicked(movieName.getText(), (int)theaterNumberDropDown.getValue(), time.getText())); addMovieGrid.getChildren().addAll(movieNameLabel, movieName, theaterNumber, theaterNumberDropDown, timeLabel, time, addMovieBtn); //Remove showing grid GridPane removeShowingGrid = new GridPane(); removeMovies.setAlignment(Pos.CENTER); removeShowingGrid.setVgap(10.0); removeShowingGrid.setHgap(10.0); ArrayList<String> movies = tm.getMovieNames(); for(int i = 0; i < movies.size(); i++){ Label movieNameLabelRemove = new Label(movies.get(i)); GridPane.setConstraints(movieNameLabelRemove, 0, i); removeShowingGrid.getChildren().add(movieNameLabelRemove); ArrayList<Showing> showings = tm.getShowings(movies.get(i)); for(int j = 0; j < showings.size(); j++){ final int movieID = j; UtilityMethods um = new UtilityMethods(); Hyperlink theaterLink = new Hyperlink(um.formatTime(showings.get(movieID).showtime)); theaterLink.setOnAction(e -> movieRemovedClicked(showings.get(movieID).id)); GridPane.setConstraints(theaterLink, j+1, i); removeShowingGrid.getChildren().add(theaterLink); } } actualForms.getChildren().addAll(addMovieGrid, removeShowingGrid); mainLayout.getChildren().add(actualForms); Button back = new Button("Back"); back.setOnAction(e -> window.setScene(getTheaterScene())); mainLayout.getChildren().add(back); Scene scene = new Scene(mainLayout, 1280, 720); return scene; } private void movieRemovedClicked(int id){ tm.removeMovie(id); window.setScene(movieManager()); } private void addMovieBtnClicked(String movieName, int theaterNumber, String time){ if(tm.insertIntoMovies(movieName, theaterNumber, time)){ window.setScene(movieManager()); } } public Scene snackPurchaseScene(){ VBox mainLayout = new VBox(); mainLayout.setAlignment(Pos.CENTER); mainLayout.setSpacing(0.0); Label mainLabel = new Label("Purchase Snacks"); mainLayout.getChildren().add(mainLabel); GridPane grid = new GridPane(); grid.setPadding(new Insets(100, 100, 100, 100)); //Border to window grid.setVgap(10); //Set vertical spacing grid.setHgap(10); //Set horizontal spacing grid.setAlignment(Pos.CENTER); //Popcorn Label popcornLabel = new Label("Popcorn: "); GridPane.setConstraints(popcornLabel, 0, 0); grid.getChildren().add(popcornLabel); //Popcorn - drop down ObservableList<Integer> options = FXCollections.observableArrayList( 0, 1, 2, 3, 4, 5, 6, 7, 8 ); final ComboBox popcornDropDown = new ComboBox(options); popcornDropDown.getSelectionModel().selectFirst(); popcornDropDown.setPrefWidth(175.0); GridPane.setConstraints(popcornDropDown, 1, 0); grid.getChildren().add(popcornDropDown); //Drinks Label drinkLabel = new Label("Drink(s): "); GridPane.setConstraints(drinkLabel, 0, 1); grid.getChildren().add(drinkLabel); final ComboBox drinkDropDown = new ComboBox(options); drinkDropDown.getSelectionModel().selectFirst(); drinkDropDown.setPrefWidth(175.0); GridPane.setConstraints(drinkDropDown, 1, 1); grid.getChildren().add(drinkDropDown); //Candy Label candyLabel = new Label("Candy: "); GridPane.setConstraints(candyLabel, 0, 2); grid.getChildren().add(candyLabel); final ComboBox candyDropDown = new ComboBox(options); candyDropDown.getSelectionModel().selectFirst(); candyDropDown.setPrefWidth(175.0); GridPane.setConstraints(candyDropDown, 1, 2); grid.getChildren().add(candyDropDown); //Name on Credit Card - label Label nameOnCardLabel = new Label("Name on Credit Card: "); GridPane.setConstraints(nameOnCardLabel, 0, 3); grid.getChildren().add(nameOnCardLabel); //Name on Credit Card - input TextField nameInput = new TextField(); nameInput.setPromptText("name on credit card"); nameInput.setText(loggedInUser.name()); GridPane.setConstraints(nameInput, 1, 3); grid.getChildren().add(nameInput); //Credit Card Number - label Label creditNumLabel = new Label("Credit Card Number: "); GridPane.setConstraints(creditNumLabel, 0, 4); grid.getChildren().add(creditNumLabel); //Credit Card Number - input TextField cardNumberInput = new TextField(); cardNumberInput.setPromptText("credit card number"); cardNumberInput.setText(loggedInUser.creditNum()); GridPane.setConstraints(cardNumberInput, 1, 4); grid.getChildren().add(cardNumberInput); //Credit Card Expiration Date - Label Label expDateLabel = new Label("Credit Card Expiration Date"); GridPane.setConstraints(expDateLabel, 0, 5); grid.getChildren().add(expDateLabel); //Credit Card Expiration Date - input DatePicker dp = new DatePicker(loggedInUser.creditExpDate()); GridPane.setConstraints(dp, 1 , 5); grid.getChildren().add(dp); //Credit Card Security Code Label securityCodeLabel = new Label("Credit Card Security Code"); GridPane.setConstraints(securityCodeLabel, 0, 6); grid.getChildren().add(securityCodeLabel); //Credit Card Security Code - input TextField secCodeInput = new TextField(); secCodeInput.setPromptText("security code"); secCodeInput.setText(loggedInUser.secCode()); GridPane.setConstraints(secCodeInput, 1, 6); grid.getChildren().add(secCodeInput); //Zip Code - label Label zipCodeLabel = new Label("Zip Code: "); GridPane.setConstraints(zipCodeLabel, 0, 7); grid.getChildren().add(zipCodeLabel); //Zip Code - input TextField zipCodeInput = new TextField(); zipCodeInput.setPromptText("zip code"); zipCodeInput.setText(loggedInUser.zipCode()); GridPane.setConstraints(zipCodeInput, 1, 7); grid.getChildren().add(zipCodeInput); mainLayout.getChildren().add(grid); //Bottom navigation buttons HBox bottomButtons = new HBox(); Button pay = new Button("Complete Purchase"); Button back = new Button("Previous Screen"); back.setOnAction(e -> window.setScene(getTheaterScene())); pay.setOnAction(e -> snackPaymentClicked(nameInput, cardNumberInput, dp, secCodeInput, zipCodeInput, popcornDropDown.getValue().toString(), drinkDropDown.getValue().toString(), candyDropDown.getValue().toString())); //If user is employee they can pay in cash if(loggedInUser instanceof Employee){ Button cashButton = new Button("Payed in Cash"); cashButton.setOnAction(e -> snackPaymentClickedCash(popcornDropDown.getValue().toString(), drinkDropDown.getValue().toString(), candyDropDown.getValue().toString())); bottomButtons.getChildren().add(cashButton); } bottomButtons.getChildren().addAll(pay, back); bottomButtons.setAlignment(Pos.CENTER); bottomButtons.setSpacing(10.0); mainLayout.getChildren().add(bottomButtons); Scene scene = new Scene(mainLayout, 1280, 720); return scene; } public Scene revenueScene(){ VBox mainLayout = new VBox(); mainLayout.setSpacing(10.0); mainLayout.setAlignment(Pos.CENTER); Scene scene = new Scene(mainLayout, 1280, 720); Label titleOfPage = new Label("Revenue"); mainLayout.getChildren().addAll(titleOfPage); mainLayout.getChildren().add(pm.getPaymentData()); Button back = new Button("Back"); back.setOnAction(e -> window.setScene(getTheaterScene())); mainLayout.getChildren().addAll(back); return scene; } public Scene addEmployeeScene(){ VBox mainLayout = new VBox(); mainLayout.setAlignment(Pos.CENTER); mainLayout.setSpacing(0.0); Label mainLabel = new Label("Create Employee Account"); mainLayout.getChildren().add(mainLabel); GridPane grid = new GridPane(); grid.setPadding(new Insets(100, 100, 100, 100)); //Border to window grid.setVgap(10); //Set vertical spacing grid.setHgap(10); //Set horizontal spacing grid.setAlignment(Pos.CENTER); //Employee email Label emailLabel = new Label("Email: "); GridPane.setConstraints(emailLabel, 0, 0); TextField emailInput = new TextField(); emailInput.setPromptText("employee email"); GridPane.setConstraints(emailInput, 1, 0); grid.getChildren().addAll(emailLabel, emailInput); //Employee password Label passwordLabel = new Label("Password: "); GridPane.setConstraints(passwordLabel, 0, 1); PasswordField passwordInput = new PasswordField(); passwordInput.setPromptText("employee password"); GridPane.setConstraints(passwordInput, 1, 1); grid.getChildren().addAll(passwordLabel, passwordInput); //Employee confirm password Label confirmPassLabel = new Label("Confirm Password: "); GridPane.setConstraints(confirmPassLabel, 0, 2); PasswordField confirmPasswordInput = new PasswordField(); confirmPasswordInput.setPromptText("confirm password"); GridPane.setConstraints(confirmPasswordInput, 1, 2); grid.getChildren().addAll(confirmPassLabel, confirmPasswordInput); //Employee is manager toggle Label isManagerLabel = new Label("Manager: "); GridPane.setConstraints(isManagerLabel, 0, 3); CheckBox isManagerCheck = new CheckBox(); isManagerCheck.setSelected(false); GridPane.setConstraints(isManagerCheck, 1, 3); grid.getChildren().addAll(isManagerLabel, isManagerCheck); mainLayout.getChildren().add(grid); //Back and add buttons HBox bottomNavBar = new HBox(); bottomNavBar.setAlignment(Pos.CENTER); bottomNavBar.setSpacing(10.0); Button addEmployee = new Button("Add Employee"); addEmployee.setOnAction(e -> addEmpButtonClicked(emailInput, passwordInput, confirmPasswordInput, isManagerCheck)); Button back = new Button("Back"); back.setOnAction(e -> window.setScene(getTheaterScene())); bottomNavBar.getChildren().addAll(addEmployee, back); mainLayout.getChildren().add(bottomNavBar); Scene scene = new Scene(mainLayout, 1280, 720); return scene; } public void addEmpButtonClicked(TextField email, TextField pass, TextField confPass, CheckBox manager){ if(email.getText() != null && !email.getText().trim().isEmpty() && pass.getText() != null && !pass.getText().trim().isEmpty() && confPass.getText() != null && !confPass.getText().trim().isEmpty()) { if (am.createEmployeeAccount(email.getText(), pass.getText(), confPass.getText(), manager.isSelected())) { window.setScene(getTheaterScene()); } } } public Scene getSeatSelectionScreen(int movieId){ VBox mainLayout = new VBox(); UtilityMethods um = new UtilityMethods(); mainLayout.setAlignment(Pos.CENTER); Showing thisMovie = new Showing(movieId, tm); //Header Label movieName = new Label(thisMovie.movieName); Label startTime = new Label("Start Time: " + um.formatTime(thisMovie.showtime)); Label theaterNumber = new Label("Theater: " + thisMovie.theaterNumber); HBox header = new HBox(); header.setAlignment(Pos.CENTER); header.setSpacing(500.00); header.getChildren().addAll(movieName, startTime, theaterNumber); mainLayout.getChildren().addAll(header); //This HBox is used for separating the user info and seat selection HBox splitScreen = new HBox(); splitScreen.setSpacing(150.0); //Left side of screen - the credit card info and email and stuff GridPane userVals = new GridPane(); userVals.setPadding(new Insets(100, 100, 100, 100)); userVals.setVgap(10.0); userVals.setHgap(10.0); userVals.setAlignment(Pos.CENTER); //Number of seats - label Label numSeatSelectLabel = new Label("Select Number of Seats: "); GridPane.setConstraints(numSeatSelectLabel, 0, 0); userVals.getChildren().add(numSeatSelectLabel); //Number of seats - drop down ObservableList<Integer> options = FXCollections.observableArrayList( 1, 2, 3, 4, 5, 6, 7, 8 ); final ComboBox numSeatsDropDown = new ComboBox(options); numSeatsDropDown.getSelectionModel().selectFirst(); numSeatsDropDown.setPrefWidth(175.0); GridPane.setConstraints(numSeatsDropDown, 1, 0); userVals.getChildren().add(numSeatsDropDown); //Name on Credit Card - label Label nameOnCardLabel = new Label("Name on Credit Card: "); GridPane.setConstraints(nameOnCardLabel, 0, 1); userVals.getChildren().add(nameOnCardLabel); //Name on Credit Card - input TextField nameInput = new TextField(); nameInput.setPromptText("name on credit card"); nameInput.setText(loggedInUser.name()); GridPane.setConstraints(nameInput, 1, 1); userVals.getChildren().add(nameInput); //Credit Card Number - label Label creditNumLabel = new Label("Credit Card Number: "); GridPane.setConstraints(creditNumLabel, 0, 2); userVals.getChildren().add(creditNumLabel); //Credit Card Number - input TextField cardNumberInput = new TextField(); cardNumberInput.setPromptText("credit card number"); cardNumberInput.setText(loggedInUser.creditNum()); GridPane.setConstraints(cardNumberInput, 1, 2); userVals.getChildren().add(cardNumberInput); //Credit Card Expiration Date - Label Label expDateLabel = new Label("Credit Card Expiration Date"); GridPane.setConstraints(expDateLabel, 0, 3); userVals.getChildren().add(expDateLabel); //Credit Card Expiration Date - input DatePicker dp = new DatePicker(loggedInUser.creditExpDate()); GridPane.setConstraints(dp, 1 , 3); userVals.getChildren().add(dp); //Credit Card Security Code Label securityCodeLabel = new Label("Credit Card Security Code"); GridPane.setConstraints(securityCodeLabel, 0, 4); userVals.getChildren().add(securityCodeLabel); //Credit Card Security Code - input TextField secCodeInput = new TextField(); secCodeInput.setPromptText("security code"); secCodeInput.setText(loggedInUser.secCode()); GridPane.setConstraints(secCodeInput, 1, 4); userVals.getChildren().add(secCodeInput); //Zip Code - label Label zipCodeLabel = new Label("Zip Code: "); GridPane.setConstraints(zipCodeLabel, 0, 5); userVals.getChildren().add(zipCodeLabel); //Zip Code - input TextField zipCodeInput = new TextField(); zipCodeInput.setPromptText("zip code"); zipCodeInput.setText(loggedInUser.zipCode()); GridPane.setConstraints(zipCodeInput, 1, 5); userVals.getChildren().add(zipCodeInput); //Email Label Label emailLabel = new Label("Email: "); GridPane.setConstraints(emailLabel, 0, 6); userVals.getChildren().add(emailLabel); //Email Input TextField emailInput = new TextField(); emailInput.setPromptText("email"); emailInput.setText(loggedInUser.email()); GridPane.setConstraints(emailInput, 1, 6); userVals.getChildren().add(emailInput); //Add user input values to HBox splitScreen.getChildren().add(userVals); //Right side of screen - actual seat selection GridPane seatSelector = new GridPane(); seatSelector.setPadding(new Insets(100, 100, 100, 100)); seatSelector.setHgap(10); seatSelector.setVgap(10); Rectangle seatRectanges[] = new Rectangle[100]; //Seat selection rectangles for(int i = 0; i < 10; i++){ for(int j = 0; j < 10; j++){ int charLoc = i*10+j; seatRectanges[charLoc] = new Rectangle(); seatRectanges[charLoc].setWidth(20); seatRectanges[charLoc].setHeight(20); if(thisMovie.seats.charAt(charLoc) == 'e'){ seatRectanges[charLoc].setFill(Color.GRAY); seatRectanges[charLoc].setOnMouseClicked(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent mouseEvent) { //Check if turning this seat green would go over selected seats # if(numberSeatsSelected < (int)numSeatsDropDown.getValue() && !seatRectanges[charLoc].getFill().equals(Color.GREEN)){ seatRectanges[charLoc].setFill(Color.GREEN); numberSeatsSelected++; }else if(seatRectanges[charLoc].getFill().equals(Color.GREEN)){ seatRectanges[charLoc].setFill(Color.GRAY); numberSeatsSelected--; } //If its red we do nothing, don't need a check } }); }else if(thisMovie.seats.charAt(charLoc) == 'o'){ //Occupied seatRectanges[charLoc].setFill(Color.RED); } GridPane.setConstraints(seatRectanges[charLoc], i, j); seatSelector.getChildren().add(seatRectanges[charLoc]); } } //Grid labels for(int i = 0; i < 10; i++){ Label numLabel = new Label("" + (i + 1)); GridPane.setConstraints(numLabel, 10, i); seatSelector.getChildren().add(numLabel); Label letterLabel = new Label("" + (char)(i + 65)); GridPane.setConstraints(letterLabel, i, 10); seatSelector.getChildren().add(letterLabel); } numSeatsDropDown.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent actionEvent) { numberSeatsSelected = 0; for(int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { int charLoc = i * 10 + j; if(thisMovie.seats.charAt(charLoc) == 'e'){ seatRectanges[charLoc].setFill(Color.GRAY); } else { seatRectanges[charLoc].setFill(Color.RED); } } } } }); //Add seat selector to HBox splitScreen.getChildren().add(seatSelector); mainLayout.getChildren().addAll(splitScreen); //Bottom navigation buttons HBox bottomButtons = new HBox(); Button pay = new Button("Complete Purchase"); Button back = new Button("Previous Screen"); back.setOnAction(e -> window.setScene(getTheaterScene())); pay.setOnAction(e -> paymentClicked(nameInput, cardNumberInput, dp, secCodeInput, zipCodeInput, emailInput, thisMovie, seatRectanges)); bottomButtons.getChildren().addAll(pay); //If user is employee they can pay in cash if(loggedInUser instanceof Employee){ Button cashButton = new Button("Payed in Cash"); cashButton.setOnAction(e -> paymentClickedCash(seatRectanges, thisMovie)); bottomButtons.getChildren().add(cashButton); } bottomButtons.getChildren().add(back); bottomButtons.setAlignment(Pos.CENTER); bottomButtons.setSpacing(10.0); mainLayout.getChildren().add(bottomButtons); Scene scene = new Scene(mainLayout, 1280, 720); return scene; } private void paymentClickedCash(Rectangle seats[], Showing showing){ for(int i = 0; i < seats.length; i++){ pm.updateRevenue(true, false, false, false); showing.reserveSeat(i); } window.setScene(paymentSuccessful()); } public void paymentClicked(TextField name, TextField num, DatePicker date, TextField secCode, TextField zip, TextField email, Showing showing, Rectangle seats[]){ //Make sure all fields are filed boolean successful = true; Border errorBorder = new Border(new BorderStroke(Color.RED, BorderStrokeStyle.SOLID, CornerRadii.EMPTY, BorderWidths.DEFAULT)); if(name.getText() == null || name.getText().trim().isEmpty()){ successful = false; name.setBorder(errorBorder); } if(num.getText() == null || num.getText().trim().isEmpty() || !pm.validateCard(num.getText())){ successful = false; num.setBorder(errorBorder); } if(date.getValue() == null || date.getValue().isBefore(LocalDate.now())){ successful = false; date.setBorder(errorBorder); } if(secCode.getText() == null || secCode.getText().trim().isEmpty()){ successful = false; secCode.setBorder(errorBorder); } if(zip.getText() == null || zip.getText().trim().isEmpty()){ successful = false; zip.setBorder(errorBorder); } if(email.getText() == null || email.getText().trim().isEmpty()){ successful = false; email.setBorder(errorBorder); } if(successful){ for(int i = 0; i < seats.length; i++){ if(seats[i].getFill().equals(Color.GREEN)){ showing.reserveSeat(i); pm.updateRevenue(true,false,false,false); //every time a seat is changed to green, payment manager is also notified } } window.setScene(paymentSuccessful()); } } public Scene paymentSuccessful(){ VBox mainLayout = new VBox(); mainLayout.setAlignment(Pos.CENTER); Label successful = new Label("Payment Successful!"); mainLayout.getChildren().add(successful); Button movieTheaterScreen = new Button("Go back to viewing Showtimes"); movieTheaterScreen.setOnAction(e -> window.setScene(getTheaterScene())); mainLayout.getChildren().add(movieTheaterScreen); Scene scene = new Scene(mainLayout, 1280, 720); return scene; } //used in snack purchase screen public void snackPaymentClicked(TextField name, TextField num, DatePicker date, TextField secCode, TextField zip, String pop, String dr, String can){ //Make sure all fields are filed boolean successful = true; Border errorBorder = new Border(new BorderStroke(Color.RED, BorderStrokeStyle.SOLID, CornerRadii.EMPTY, BorderWidths.DEFAULT)); if(name.getText() == null || name.getText().trim().isEmpty()){ successful = false; name.setBorder(errorBorder); } if(num.getText() == null || num.getText().trim().isEmpty() || !pm.validateCard(num.getText())){ successful = false; num.setBorder(errorBorder); } if(date.getValue() == null || date.getValue().isBefore(LocalDate.now())){ successful = false; date.setBorder(errorBorder); } if(secCode.getText() == null || secCode.getText().trim().isEmpty()){ successful = false; secCode.setBorder(errorBorder); } if(zip.getText() == null || zip.getText().trim().isEmpty()){ successful = false; zip.setBorder(errorBorder); } if(successful){ int p = Integer.parseInt(pop); int d = Integer.parseInt(dr); int c = Integer.parseInt(can); for (int i = 0; i < p; i++){ pm.updateRevenue(false, true, false, false); } for (int i = 0; i < d; i++){ pm.updateRevenue(false, false, true, false); } for (int i = 0; i < c; i++){ pm.updateRevenue(false, false, false, true); } window.setScene(snackPaymentSuccessful()); } } private void snackPaymentClickedCash(String pop, String dr, String can){ int p = Integer.parseInt(pop); int d = Integer.parseInt(dr); int c = Integer.parseInt(can); for (int i = 0; i < p; i++){ pm.updateRevenue(false, true, false, false); } for (int i = 0; i < d; i++){ pm.updateRevenue(false, false, true, false); } for (int i = 0; i < c; i++){ pm.updateRevenue(false, false, false, true); } window.setScene(paymentSuccessful()); } public Scene snackPaymentSuccessful(){ VBox mainLayout = new VBox(); mainLayout.setAlignment(Pos.CENTER); Label successful = new Label("Payment Successful!"); mainLayout.getChildren().add(successful); Button snackScreen = new Button("Go back to snack purchase"); snackScreen.setOnAction(e -> window.setScene(snackPurchaseScene())); mainLayout.getChildren().add(snackScreen); Scene scene = new Scene(mainLayout, 1280, 720); return scene; } public Color swapColor(Color current){ if(current.equals(Color.GRAY)){ return Color.GREEN; } else { return Color.GRAY; } } }
package stormedpanda.simplyjetpacks.sound; import net.minecraft.client.audio.TickableSound; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.util.SoundCategory; import net.minecraft.util.math.BlockPos; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import stormedpanda.simplyjetpacks.client.ClientJetpackHandler; import java.util.Collections; import java.util.HashMap; import java.util.Map; @OnlyIn(Dist.CLIENT) public class JetpackSound extends TickableSound { private static final Map<Integer, JetpackSound> PLAYING_FOR = Collections.synchronizedMap(new HashMap<>()); private final PlayerEntity player; private int fadeOut = -1; public JetpackSound(PlayerEntity player) { super(ModSounds.JETPACK, SoundCategory.PLAYERS); this.player = player; this.repeat = true; PLAYING_FOR.put(player.getEntityId(), this); } public static boolean playing(int entityId) { return PLAYING_FOR.containsKey(entityId) && PLAYING_FOR.get(entityId) != null && !PLAYING_FOR.get(entityId).isDonePlaying(); } @Override public void tick() { BlockPos pos = this.player.getPosition(); this.x = (float) pos.getX(); this.y = (float) pos.getY();// - 10; this.z = (float) pos.getZ(); if (this.fadeOut < 0 && !ClientJetpackHandler.isFlying(this.player)) { this.fadeOut = 0; synchronized (PLAYING_FOR) { PLAYING_FOR.remove(this.player.getEntityId()); } } else if (this.fadeOut >= 5) { this.func_239509_o_(); } else if(this.fadeOut >= 0) { this.volume = 1.0F - this.fadeOut / 5F; this.fadeOut++; } } }
package io.github.ihongs.action.anno; import io.github.ihongs.Cnst; import io.github.ihongs.Core; import io.github.ihongs.HongsException; import io.github.ihongs.action.ActionHelper; import io.github.ihongs.action.ActionRunner; import io.github.ihongs.action.PresetHelper; import io.github.ihongs.util.Synt; import java.lang.annotation.Annotation; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; /** * 预置补充处理器 * <pre> * ab 参数含义: * _obj_ 将启用对象模式 * _str_ 将启用字串模式 * </pre> * <p> * 可使用 ab 参数将指定好的条件注入到请求数据中. * 这样可减少终端一些常规参数, * 并能在未来更方便地做出调整; * 如 ab=v1 附加版本 1 的参数. * </p> * @author Hong */ public class PresetInvoker implements FilterInvoker { @Override public void invoke(ActionHelper helper, ActionRunner chains, Annotation anno) throws HongsException { Preset ann = (Preset) anno; String conf = ann.conf(); String form = ann.form(); String[] deft = ann.deft(); String[] defs = ann.defs(); // 默认参数可完全由外部指定 if (deft == null || deft.length == 0) { Map req = helper.getRequestData(); Set<String> uzed = Synt.toTerms(req.get(Cnst.AB_KEY)); Set<String> used = new LinkedHashSet (); if (null != uzed && ! uzed.isEmpty ( )) { for(String item : uzed) { if (item.equals("_obj_")) { Core.getInstance().put(Cnst.OBJECT_MODE, true); } else if (item.equals("_str_")) { Core.getInstance().put(Cnst.OBJECT_MODE,false); } else if (item.startsWith("_") == false && !item.startsWith(".") && !item.startsWith(":") && !item.startsWith("!")) { used.add("." + item); } } deft = used.toArray(new String[0]); } } // 识别路径 if (form.length() == 0) { form = chains.getEntity(); } if (conf.length() == 0) { conf = chains.getModule(); // 照顾 Module Action 的配置规则. 2018/7/7 改为完全由外部预判 // if (FormSet.hasConfFile(conf+"/"+form)) { // conf = conf+"/"+form ; // } } // 补充参数 try { Map req; PresetHelper pre; req = helper.getRequestData(); pre = new PresetHelper(); pre.addItemsByForm(conf, form, deft, defs); pre.preset(req, helper ); } catch (HongsException ex) { int ec = ex.getErrno(); if (ec != 910 && ec != 911 && ec != 913 ) { // 非枚举缺失 throw ex ; } } chains.doAction(); } }
package hwarang.artg.funding.controller; import java.util.List; import javax.websocket.server.PathParam; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import hwarang.artg.common.model.CriteriaDTO; import hwarang.artg.funding.model.FundingReplyVO; import hwarang.artg.funding.service.FundingReplyService; import lombok.AllArgsConstructor; @RequestMapping("/replies/") @RestController @AllArgsConstructor public class FundingReplyController { private FundingReplyService service; @PostMapping(value = "/new", consumes = "application/json", produces = {MediaType.TEXT_PLAIN_VALUE}) public ResponseEntity<String>create(@RequestBody FundingReplyVO vo){ int insertCount = service.register(vo); return insertCount ==1 ? new ResponseEntity<>("success", HttpStatus.OK) :new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } @GetMapping(value = "/pages/{funding_num}/{page}", produces = { MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_UTF8_VALUE}) public ResponseEntity<List<FundingReplyVO>>getList(@PathVariable("page")int page, @PathVariable("funding_num")Long funding_num){ CriteriaDTO cri = new CriteriaDTO(page,10); return new ResponseEntity<>(service.getList(cri, funding_num), HttpStatus.OK); } @GetMapping(value = "/{rno}", produces = { MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_UTF8_VALUE}) public ResponseEntity<FundingReplyVO> get(@PathVariable("rno")Long rno){ return new ResponseEntity<>(service.get(rno), HttpStatus.OK); } @DeleteMapping(value = "/{rno}",produces = {MediaType.TEXT_PLAIN_VALUE}) public ResponseEntity<String> remove(@PathVariable("rno")Long rno){ return service.remove(rno)==1 ? new ResponseEntity<>("success", HttpStatus.OK) : new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } @RequestMapping(method = {RequestMethod.PUT,RequestMethod.PATCH}, value = "/{rno}", consumes = "application/json", produces = {MediaType.TEXT_PLAIN_VALUE}) public ResponseEntity<String> modify(@RequestBody FundingReplyVO vo, @PathVariable("rno")Long rno){ vo.setRno(rno); return service.modify(vo)==1 ?new ResponseEntity<>("success", HttpStatus.OK) :new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } }
package service; public interface IRoomService { public RoomService createNewRoom(int roomNumber, int howManyPersonInRoom); public Integer peopleInRoom(); public Integer maxPeopleInRoom(); public String personGetIn(); public String personGetOut(); }
package com.huadin.entity; import java.io.Serializable; public class Person implements Serializable { private String loginName;//登录名 private String userName;// private String phone; private String address; private boolean permission; private String registerDate; public String getRegisterDate() { return registerDate; } public void setRegisterDate(String registerDate) { this.registerDate = registerDate; } public String getLoginName() { return loginName; } public void setLoginName(String loginName) { this.loginName = loginName; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public boolean isPermission() { return permission; } public void setPermission(boolean permission) { this.permission = permission; } }
package persistencia; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class Conexion { private Connection cn ; public Conexion(){ try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); cn=DriverManager.getConnection("jdbc:odbc:Conecta_db"); } catch (Exception e){ e.printStackTrace(); System.out.println("Problemas con la conexion"); }//mostrar error. } public Connection getConexion () { return cn; } }
package Test; public class DITest { public class A { public void read() { System.out.println("read A"); } } public class B extends A { public void read() { System.out.println("read B"); } } public class C extends A { public void read() { System.out.println("read C"); } } public void addObj(String className) { if(className.equals("B")) { new B().read(); } if(className.equals("C")) { new C().read(); } } public static void main(String[] args) { String className = "C"; DITest dit = new DITest(); dit.addObj(className); } }
package com.mibo.modules.data.base; import com.jfinal.plugin.activerecord.Model; import com.jfinal.plugin.activerecord.IBean; /** * Generated by JFinal, do not modify this file. */ @SuppressWarnings({"serial", "unchecked"}) public abstract class BaseUser<M extends BaseUser<M>> extends Model<M> implements IBean { public M setId(java.lang.Integer id) { set("id", id); return (M)this; } public java.lang.Integer getId() { return getInt("id"); } public M setPhone(java.lang.String phone) { set("phone", phone); return (M)this; } public java.lang.String getPhone() { return getStr("phone"); } public M setPassword(java.lang.String password) { set("password", password); return (M)this; } public java.lang.String getPassword() { return getStr("password"); } public M setLoginToken(java.lang.String loginToken) { set("login_token", loginToken); return (M)this; } public java.lang.String getLoginToken() { return getStr("login_token"); } public M setLoginTime(java.util.Date loginTime) { set("login_time", loginTime); return (M)this; } public java.util.Date getLoginTime() { return get("login_time"); } public M setRegisterTime(java.util.Date registerTime) { set("register_time", registerTime); return (M)this; } public java.util.Date getRegisterTime() { return get("register_time"); } public M setAccountStatus(java.lang.String accountStatus) { set("account_status", accountStatus); return (M)this; } public java.lang.String getAccountStatus() { return getStr("account_status"); } }
public class InvincibilityPackage extends PresentBonusPackage { private int effectPeriod; public InvincibilityPackage (int period, int positionX, int positionY, int appearTime){ super( positionX, positionY, appearTime); this.effectPeriod = period; } public int getEffectPeriod() { return effectPeriod; } }
package app.com.example.android.spotifystreamer; import android.os.Parcel; import android.os.Parcelable; /** * Created by rmendoza on 6/24/2015. */ public class RowItemFiveStrings implements Parcelable { private String textColumn0; private String textColumn1; private String textColumn2; private String textColumn3; private String textColumn4; public RowItemFiveStrings() { } public RowItemFiveStrings(String textColumn0, String textColumn1, String textColumn2, String textColumn3, String textColumn4) { this.textColumn0 = textColumn0; this.textColumn1 = textColumn1; this.textColumn2 = textColumn2; this.textColumn3 = textColumn3; this.textColumn4 = textColumn4; } public String gettextColumn0() {return textColumn0; } public void settextColumn0(String title) {this.textColumn0 = title; } public String gettextColumn1() { return textColumn1; } public void settextColumn1(String title) { this.textColumn1 = title; } public String gettextColumn2() {return textColumn2; } public void settextColumn2(String title) {this.textColumn2 = title; } public String gettextColumn3() {return textColumn3; } public void settextColumn3(String title) {this.textColumn3 = title; } public String gettextColumn4() {return textColumn4; } public void settextColumn4(String title) {this.textColumn4 = title; } @Override public int describeContents() { return 0; } public RowItemFiveStrings(Parcel parcel) { this.textColumn0 = parcel.readString(); this.textColumn1 = parcel.readString(); this.textColumn2 = parcel.readString(); this.textColumn3 = parcel.readString(); this.textColumn4 = parcel.readString(); } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(textColumn0); dest.writeString(textColumn1); dest.writeString(textColumn2); dest.writeString(textColumn3); dest.writeString(textColumn4); } public static Creator<RowItemFiveStrings> CREATOR = new Creator<RowItemFiveStrings>() { @Override public RowItemFiveStrings createFromParcel(Parcel source) { return new RowItemFiveStrings(source); } @Override public RowItemFiveStrings[] newArray(int size) { return new RowItemFiveStrings[size]; } }; }
package com.jinglangtech.teamchat.model; /** * Created by think on 2018/3/24. */ public class SendResponse { public String id; public String time; }
package edu.inheritance.hollingsworth.james; import edu.jenks.dist.inheritance.Weighable; public class WeighedItem extends Item implements Weighable { private double pricePerPound; public WeighedItem(boolean bulk, double pricePerPound) { super(bulk); this.pricePerPound = pricePerPound; } @Override public double getPricePerPound() { return pricePerPound; } @Override public void setPricePerPound(double pricePerPound) { this.pricePerPound = pricePerPound; } }
package test.integration.org.testinfected.petstore.jdbc; import org.testinfected.petstore.order.OrderNumber; import org.testinfected.petstore.order.OrderNumberSequence; import org.hamcrest.FeatureMatcher; import org.hamcrest.Matcher; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.testinfected.petstore.Transactor; import org.testinfected.petstore.UnitOfWork; import org.testinfected.petstore.jdbc.JDBCTransactor; import org.testinfected.petstore.jdbc.OrderNumberDatabaseSequence; import test.support.org.testinfected.petstore.jdbc.Database; import test.support.org.testinfected.petstore.jdbc.TestDatabaseEnvironment; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; public class OrderNumberDatabaseSequenceTest { Database database = Database.in(TestDatabaseEnvironment.load()); Connection connection = database.connect(); Transactor transactor = new JDBCTransactor(connection); OrderNumberSequence orderNumberSequence = new OrderNumberDatabaseSequence(connection); @Before public void resetDatabase() throws Exception { database.reset(); } @After public void closeConnection() throws SQLException { connection.close(); } @Test public void incrementsSequenceNumber() throws Exception { seedSequenceNumberWith(100); assertThat("next order number", nextOrderNumber(), orderNumber("00000101")); assertThat("next order number", nextOrderNumber(), orderNumber("00000102")); } private void seedSequenceNumberWith(final long seed) throws Exception { transactor.perform(new UnitOfWork() { public void execute() throws Exception { PreparedStatement statement = connection.prepareStatement("insert into order_numbers values (?)"); statement.setLong(1, seed); assertThat("update count", statement.executeUpdate(), is(1)); } }); } private OrderNumber nextOrderNumber() { return orderNumberSequence.nextOrderNumber(); } private Matcher<OrderNumber> orderNumber(final String number) { return new FeatureMatcher<OrderNumber, String>(equalTo(number), "an order number", "order number") { @Override protected String featureValueOf(OrderNumber actual) { return actual.getNumber(); } }; } }
/** * Created by Chroon on 2016-11-08. */ package Controller; import Interface.OptionChoisi; import Interface.TCI; import Model.Sol; import Model.Vaisseau; import View.Gagner; import View.Perdre; import View.SceneJeu; import javafx.animation.Animation; import javafx.animation.KeyFrame; import javafx.animation.Timeline; import javafx.stage.Stage; import javafx.util.Duration; public class ControllerJeu implements TCI{ private Timeline mouvementCollision; private Vaisseau vaisseau; private Sol sol; private SceneJeu jeu; private Gagner gagne; private Perdre perdre; private Stage stage; private int diff; private Points points; private OptionChoisi optChoisi; private Turret turret; private TempeteSolaire tempete; public ControllerJeu(Vaisseau vaisseau, Sol sol, SceneJeu jeu,Stage leStage, Perdre perdu, Gagner gagne, Points points,Turret turret,TempeteSolaire tempete){ this.jeu=jeu; this.vaisseau=vaisseau; this.sol=sol; stage=leStage; perdre=perdu; this.gagne=gagne; this.points=points; this.turret=turret; this.tempete=tempete; turret.setInterfacePerdre(this); initialisationMouvementCollision(); } public void setInterfaceChoix(OptionChoisi choix){ optChoisi=choix; } public void setJeu(int planete, int diff, String nom){ this.diff = diff; sol.genererPath(diff,planete); vaisseau.setNom(nom); vaisseau.setRotate(0); vaisseau.setVitesseIni(0); vaisseau.setEssence(1000); vaisseau.setRotationIni(); jeu.addElementJeu(vaisseau,sol.getPath()); stage.setScene(jeu.getSceneJeu()); points.resetPoints(); points.startPoint(); startMouvementCollision(); chargementOption(); } private void finJeu(){ jeu.cleanup(); sol.cleanup(); } private void initialisationMouvementCollision(){ mouvementCollision=new Timeline(new KeyFrame( Duration.millis(15), t->{ vaisseau.accelerer(jeu.appuyerGaz()); jeu.deplacement(vaisseau.getTranslateX()+vaisseau.getVitesseX(), vaisseau.getTranslateY()-vaisseau.getVitesseY()); if (jeu.appuyerGaz()) jeu.setGaz(vaisseau.getEssence()); collision(); } )); mouvementCollision.setCycleCount(Animation.INDEFINITE); } private void startMouvementCollision(){ mouvementCollision.play(); } private void stopMouvmentCollision(){ mouvementCollision.stop(); } private void gagner(){ stopMouvmentCollision(); turret.finAttaqueOrbital(); tempete.stopTempete(); points.stopPoint(); finJeu(); stage.setScene(gagne.getScene()); } public void perdre(){ stopMouvmentCollision(); turret.finAttaqueOrbital(); tempete.stopTempete(); points.stopPoint(); finJeu(); stage.setScene(perdre.getScene()); } private void conditionVictoire(){ if(vaisseau.getX() >= sol.getPlat1()*10 - 3 && (vaisseau.getX()+20) <= sol.getPlat1() * 10 + (60/diff) + 3) { if (vaisseau.getVitesseY() <= 2 && vaisseau.getRotation() > 80 && vaisseau.getRotation() < 100) gagner(); else perdre(); } else if (vaisseau.getX() >= sol.getPlat2() * 10 - 3 && (vaisseau.getX()+20) <= sol.getPlat2() * 10 + 3 + (60/diff)){ if (vaisseau.getVitesseY() <= 2 && vaisseau.getRotation() > 80 && vaisseau.getRotation() < 100) gagner(); else perdre(); } else perdre(); } private void collision() { double valeurPrecise1; if(Math.round(vaisseau.getX()/10) >= 140||Math.round(vaisseau.getX()/10)<0){ valeurPrecise1 = sol.getSolValeurs().get(140); } else valeurPrecise1 = (sol.getSolValeurs().get((int) Math.round(vaisseau.getX()/10)) + (((sol.getSolValeurs().get((int) (Math.round(vaisseau.getX()/10) + 1)) - sol.getSolValeurs().get((int) (Math.round(vaisseau.getX()/10) + 1))) / 10))); double valeurPrecise2; if(((Math.round(vaisseau.getX()/10) + 2)) > 140||Math.round(vaisseau.getX()/10)<0) valeurPrecise2 = valeurPrecise1; else valeurPrecise2 = (sol.getSolValeurs().get((int) (Math.round(vaisseau.getX()/10) + 2)) + (((sol.getSolValeurs().get((int) (Math.round(vaisseau.getX()/10) + 1)) - sol.getSolValeurs().get((int) (Math.round(vaisseau.getX()/10) + 2))) / 10))); if (vaisseau.getY() >= valeurPrecise1 || vaisseau.getY() >= valeurPrecise2){ System.out.println("<----------------------->"); System.out.println("X : " + vaisseau.getX()); System.out.println("X2 : " + (vaisseau.getX() + 20)); System.out.println("Y : " + vaisseau.getY()); System.out.println("rotation : " + vaisseau.getRotation()); System.out.println("Vitesse : " + vaisseau.getVitesseY()); System.out.println("Sol 1 : " + valeurPrecise1); System.out.println("sol 2 : " + valeurPrecise2); System.out.println("plat 1 : " + sol.getPlat1()); System.out.println("plat 2 : " + sol.getPlat2()); System.out.println("<----------------------->"); System.out.println(); conditionVictoire(); } } private void chargementOption(){ if(optChoisi.asaultOrbital()){ turret.setTir(diff); turret.commencerAttaqueObirtal(diff); } if (optChoisi.tempete()){ tempete.startTempete(); } if (optChoisi.cheatEssence()){ vaisseau.essenceInfini(); } } }
package com.timbremer.vertretungsplanggnauen; import android.app.Activity; import android.app.AlertDialog; import android.net.Uri; import android.os.Bundle; import android.view.MenuItem; import android.content.Context; import android.content.Intent; import android.support.v4.app.NavUtils; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.view.WindowManager; import android.view.inputmethod.InputMethodManager; import android.webkit.CookieManager; import android.webkit.CookieSyncManager; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends Activity { private View buttonLogin; private EditText etusername; private EditText etpassword; private WebView wv; private boolean send; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); setTitle("Vertretungsplan"); InputMethodManager imm = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE); getWindow().setSoftInputMode( WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); //SHAREDPREFS:FIRSTRUN boolean firstrun = getSharedPreferences("PREFERENCE", MODE_PRIVATE).getBoolean("firstrun", true); if (firstrun){ buttonLogin = findViewById(R.id.btlogin); send = false; wv = (WebView) findViewById(R.id.wv); wv.setVisibility(View.INVISIBLE); etusername = (EditText) findViewById(R.id.etusername); etpassword = (EditText) findViewById(R.id.etpassword); buttonLogin.setOnClickListener(new OnClickListener() { private String username; private String password; @Override public void onClick(View v) { CookieSyncManager.createInstance(MainActivity.this); CookieSyncManager.getInstance().startSync(); InputMethodManager imm = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE); getWindow().setSoftInputMode( WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); wv.setVisibility(View.VISIBLE); username = etusername.getText().toString(); password = etpassword.getText().toString(); // setContentView(wv); wv = (WebView) findViewById(R.id.wv); wv.getSettings().setBuiltInZoomControls(true); CookieManager.getInstance().setAcceptCookie(true); CookieSyncManager.getInstance().sync(); wv.getSettings().setJavaScriptEnabled(true); wv.getSettings().setLoadWithOverviewMode(true); wv.getSettings().setUseWideViewPort(true); wv.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } String text = "yes"; @Override public void onPageFinished(WebView view, String url) { if(!send) { view.loadUrl("javascript:{" + "document.getElementById('mod_login_username').value='" + username + "';" + "document.getElementById('mod_login_password').value = '" + password + "';" + "document.getElementById('mod_login_remember').checked='true';" + "var form = document.getElementsByName('login');" + "form[0].submit();};" ); send = true; } } }); wv.loadUrl("http://www.ggnauen.de/index.php?option=com_frontpage&Itemid=1"); } }); } // Save the state getSharedPreferences("PREFERENCE", MODE_PRIVATE) .edit() .putBoolean("firstrun", false) .commit(); CookieSyncManager.createInstance(MainActivity.this); CookieSyncManager.getInstance().startSync(); wv = (WebView) findViewById(R.id.wv); wv.getSettings().setBuiltInZoomControls(true); CookieManager.getInstance().setAcceptCookie(true); wv.getSettings().setJavaScriptEnabled(true); wv.getSettings().setLoadWithOverviewMode(true); wv.getSettings().setUseWideViewPort(true); wv.loadUrl("http://www.ggnauen.de/index.php?option=com_content&task=category&sectionid=2&id=19&Itemid=100"); wv.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.raumplan, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle item selection switch (item.getItemId()) { case R.id.mclose: finish(); return true; case R.id.msettings: startActivity(new Intent(this, SettingsActivity.class)); return true; case R.id.mhome: startActivity(new Intent(this, MainActivity.class)); return true; case R.id.mraumplan: startActivity(new Intent(this, RaumplanActivity.class)); return true; case android.R.id.home: NavUtils.navigateUpFromSameTask(this); return true; case R.id.mbewerten: Intent i = new Intent(Intent.ACTION_SEND); i.setType("message/rfc822"); i.putExtra(Intent.EXTRA_EMAIL, new String[]{"tbremer19@gmail.com"}); i.putExtra(Intent.EXTRA_SUBJECT, "Feedback: GGN Vertretungsplan App"); try { startActivity(Intent.createChooser(i, "Email senden...")); } catch (android.content.ActivityNotFoundException ex) { Toast.makeText(MainActivity.this, "Keine App zum Verschicken einer Email gefunden!", Toast.LENGTH_SHORT).show(); } return true; default: return super.onOptionsItemSelected(item); } } }
package com.dqm.utils; import java.nio.ByteBuffer; import java.util.Arrays; /** * Created by dqm on 2018/8/24. */ public class UInt32 { public static byte[] fromUnsignedInt(long value) { byte[] bytes = new byte[8]; ByteBuffer.wrap(bytes).putLong(value); return Arrays.copyOfRange(bytes, 4, 8); } public static long toUnsignedInt(byte[] bytes) { ByteBuffer buffer = ByteBuffer.allocate(8).put(new byte[]{0, 0, 0, 0}).put(bytes); buffer.position(0); return buffer.getLong(); } public static long toUnsignedInt(final ByteBuffer byteBuffer, boolean inverted) { byte[] indexBytes = new byte[4]; byteBuffer.get(indexBytes); if(inverted) indexBytes = ByteUtil.invertedByteArrayV2(indexBytes); return toUnsignedInt(indexBytes); } }
package io.devchaos.player.service.repository; import io.devchaos.player.service.domain.Player; import org.springframework.data.repository.reactive.ReactiveCrudRepository; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; /** * @author Paulo Jesus */ public interface PlayerRepository extends ReactiveCrudRepository<Player, String> { Flux<Player> findAllByActive(boolean active); Mono<Player> findByIdAndActiveIsTrue(String id); }
/** * Copyright 2014 MoonYard * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ import java.net.InetAddress; import java.util.ArrayList; import org.eclipse.jface.dialogs.InputDialog; import org.eclipse.jface.window.Window; public class Ariva { /** socket */ SocketUDP socket; /** devices */ ArrayList<Devices> devices; /** devices */ ArrayList<Devices> devices_static; /** port */ final int port = 32773; /** scan for devices */ final String key_scan = "MOBILE_SCAN"; /** respond of device start with */ final String key_present = "STB_RESPOND:"; /** set active */ int active = 0; // constructor public Ariva() { // set socket this.socket = new SocketUDP(port); // set devices this.devices = new ArrayList<Devices>(); // set devices this.devices_static = new ArrayList<Devices>(); } // add start parameter ariva public void addParameterAriva(String ip) { try { // create device Devices d = new Devices(); // set data d.name = ip; // set address d.address = InetAddress.getByName(ip); // add to devices_static.add(d); } catch (Exception e) { System.out.println(e.getMessage()); } } // active device in combo public void setActive(int i) { // set this.active = i; } // active device public int getActive() { // set return this.active; } // get name public String getActiveName() { // return return devices.get(active).name; } // get active ip public String getActiveIp() { // return return devices.get(active).address.getHostAddress(); } // get device count public int getDeviceCount() { // return return devices.size(); } // get device name public String getDeviceName(int id) { // return return devices.get(id).name; } // scan network for arivas public Boolean scanNetworkForDevices() { // string ip active String ipactive = ""; // count int count = 0; // check ip of active if (devices.size() > 0) { // set active ipactive = getActiveIp(); } // clear devices devices.clear(); // add static devices if (devices_static.size() > 0) { // for for (Devices d : devices_static) { // add to all devices.add(d); // is device active if (d.address.getHostAddress().equals(ipactive)) { // set active setActive(count); } // count count++; } } // clear active setActive(0); // set timeout socket.setTimeout(1200); // set names from arivas ArrayList<Response> aResponse = this.socket.requestBroadcast(key_scan); // for for (int i = 0; i < aResponse.size(); i++) { // get response String response = aResponse.get(i).getResponse(); if (response.startsWith(key_present)) { // create device Devices d = new Devices(); // set name ariva102e :61?? d.name = response.replace(key_present, "").replace(":61", ""); // set address d.address = aResponse.get(i).getAddress(); System.out.println((count) + " " + d.name); // add device devices.add(d); // is device active if (d.address.getHostAddress().equals(ipactive)) { // set active setActive(count); } // count count++; } } // set timeout socket.setTimeout(270); // return return (devices.size() > 0); } // send public void send(Codes value) { // send ArrayList<Response> response = socket.request(devices.get(active).address, value.getValue()); // for for (int i = 0; i < response.size(); i++) { // send if (response.get(i).getResponse().startsWith("input:")) { // show input showInput(); } } } // send input private void sendInput(String value) { // send ArrayList<Response> response = socket.request(devices.get(active).address, "input:" + value); // for for (int i = 0; i < response.size(); i++) { // debug // System.out.println("RES:" + response.get(i).getResponse()); } } // show dialog private void showInput() { // create dialog InputDialog dialog = new InputDialog(ListAriva.shell, "Search", "type string here", "", null); // if ok if (dialog.open() == Window.OK) { // get value String value = dialog.getValue(); // if value not null if (value != null) { // debug // System.out.println(value); // send input sendInput(value); } } } // codes to send public static enum Codes { tvradio("tvradio"), information("info"), videomode("vmode"), sat("sat"), exit( "exit"), back("back"), down("down"), up("up"), right("right"), left( "left"), ok("enter"), red("red"), blue("blue"), green("green"), yellow( "yellow"), white("white"), channel_up("ch+"), channel_down( "ch-"), volume_up("vol+"), volume_down("vol-"), key1("key1"), key2( "key2"), key3("key3"), key4("key4"), key5("key5"), key6("key6"), key7( "key7"), key8("key8"), key9("key9"), key0("key0"), epg("epg"), mute( "mute"), menu("menu"), slow("slow"), fast("fast"), pause( "pause"), play("play"), rec("rec"), page_up("page+"), page_down( "page-"), fav("fav"), pvr("pvr"), stop("stop"), ratio("ratio"), power( "power"), vmode("vmode"); // value private final String value; // constructor Codes(String value) { // set value this.value = value; } // get value public String getValue() { // return return value; } } // save devices class Devices { // ip private InetAddress address; // name private String name; } }
/* * 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 shape; /** * * @author Go Eun Sung */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here Shape s1 = new Circle(10); Shape s2 = new Rectangle(10, 15); Shape s3 = new Square(10); System.out.println(s1); System.out.println(s2); System.out.println(s3); } }
package com.opensap.mobile.canteen; public abstract class TestSettings { private static final boolean INTERNAL_TEST_MODE = false; private static final boolean EXTERNAL_TEST_MODE = Boolean.getBoolean("test.mode") // Check Java system property. || com.sap.cloud.server.odata.core.SystemEnvironment.getBoolean("XS_TEST_MODE"); // Check system environment variable. public static final boolean TEST_MODE = INTERNAL_TEST_MODE | EXTERNAL_TEST_MODE; }
/** * La classe libro contiene tutte le caratteristiche del libro da vendere: * titolo, autore, numero delle pagine e il costo * @see Autore * L'istanza di questa classe verra' utilizzata nella classe Test2 * @see Test2 * @author Genovese Tommaso, Bruno Luca, Cuniberti Andrea, Bagnis Gabriele * @version 1.0 */ public class Libro { private String titolo; private Autore autore; private int numeroPagine; private static double costoPagina = 0.05; private static final double COSTO_FISSO = 5.5; /** * Il metodo libro e' il metodo costruttore della classe * @param titolo variabile che contiene il titolo del libro * @param autore oggetto che contiene il nome e il cognome dell'autore del libro * @param numeroPagine varibile che contiene il numero totale delle pagine del libro */ public Libro(String titolo, Autore autore, int numeroPagine) { this.titolo = titolo; this.autore = autore; this.numeroPagine = numeroPagine; } /** * Il metodo setCostoPagina stabilisce il costo della pogina * @param costo */ public static void setCostoPagina(double costo) { costoPagina = costo; } /** * Il metodo getCostoPagina restituisce il costo per ogni pagina * @return costoPagina */ public static double getCostoPagina() { return costoPagina; } /** * Il metodo getCostoFisso restituisce il costo di default impostato a 5.5 * @return COSTO_FISSO */ public static double getCostoFisso() { return COSTO_FISSO; } /** * Il metodo getTitolo restituisce il titolo del libro * @return titolo */ public String getTitolo() { return titolo; } /** * Il metodo getAutore restituisce nome e cognome dell'autore del libro * @return autore * @see Autore */ public Autore getAutore() { return autore; } /** * Il metodo getNumeroPagine restituisce il numero delle pagine * @return numeroPagine */ public int getNumeroPagine() { return numeroPagine; } /** * Il metodo getPrezzo restituisce il calcolo del prezzo totale del libro * @return COSTO_FISSO + numeroPagine * costoPagina */ public double getPrezzo() { return COSTO_FISSO + numeroPagine * costoPagina; } /** * Il metodo toString stampa una stringa contente tutte le informazioni del libro * @return s */ @Override public String toString() { String s = ""; s = "'" + titolo + "' di " + autore + ", numeroPagine=" + numeroPagine + ", prezzo=" + getPrezzo() + "\n"; return s; } }
package Sorters; public abstract class Sorter { int[] array; private long startTime; private int comparisons; Sorter(int[] array){ startTime = System.nanoTime(); this.array = array; comparisons = 0; sort(0, array.length - 1); end(); } public String toString(){ String string = "[ "; for(int i : array){ string += i + " "; } string += "]"; return string; } /** * compares 2 index * * @return true if a1 is bigger, false if a2 is bigger */ protected final boolean compare(int a1, int a2){ comparisons++; return array[a1] > array[a2]; } /** * switches a[a1] to a[a2] * * @param a1 location of place to switch * @param a2 another location of place to switch */ protected final void change(int a1, int a2){ int temp = array[a1]; array[a1] = array[a2]; array[a2] = temp; // System.out.println(this); } /** * checks if the array is sorted * * @return if it is sorted or not */ protected final boolean isSorted(){ for(int i = 1; i < array.length; i++){ if(array[i - 1] > array[i]){ return false; } } return true; } private void end(){ if(isSorted()) { System.out.println("\nIt took " + ((System.nanoTime() - startTime) / 1000000) + " milliseconds for completion"); System.out.println("It took " + comparisons + " comparisons"); }else{ System.out.println("\nSort incomplete"); } // System.out.println(this); } protected abstract void sort(int start, int finish); }
import java.awt.*; import java.awt.event.MouseEvent; import java.awt.geom.Ellipse2D; import javax.swing.JButton; /** * This is the class of my circle button(green one). * @author Yaolong Li * @version 1.0 */ public class MyButton1 extends JButton { // to store in the info about the shape private Shape shape = null; public MyButton1() { this.addMouseListener(new java.awt.event.MouseAdapter(){ public void mouseEntered(MouseEvent e) { ((JButton)e.getSource()).setCursor(new Cursor(Cursor.HAND_CURSOR)); } public void mouseExited(MouseEvent e) { ((JButton)e.getSource()).setCursor(new Cursor(Cursor.MOVE_CURSOR)); } }); Dimension size = getPreferredSize(); // Changes the size of the button. size.width = size.height =20; setPreferredSize(size); setContentAreaFilled(false); } /* (non-Javadoc) * Paints the button. */ protected void paintComponent(Graphics g) { if (getModel().isArmed()) { g.setColor(Color.YELLOW); } else { g.setColor(Color.green); } g.fillOval(0, 0, getSize().width - 1, getSize().height - 1); super.paintComponents(g); } protected void paintBorder(Graphics g) { g.setColor(getForeground()); g.drawOval(0, 0, getSize().width - 1, getSize().height - 1); } /** * Checks if the mouse is on the top. */ public boolean contains(int x, int y) { if ((shape == null) || (!shape.getBounds().equals(getBounds()))) { shape = new Ellipse2D.Float(0, 0, getWidth(), getHeight()); } return shape.contains(x, y); } }
package com.phantoms.armodapi.android; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.util.Log; import android.view.LayoutInflater; import android.widget.FrameLayout; import com.unity3d.player.UnityPlayer; import com.unity3d.player.UnityPlayerActivity; /** * AR SDK Activity,To access AR-SDK, you need to inherit this Activity. */ public abstract class AbstractARMODActivity extends UnityPlayerActivity { private final String InitSDK = "InitSDK"; private final String FetchByUid = "LaunchARQuery"; private final String LaunchARScanner = "LaunchARScanner"; private final String Dispose = "Dispose"; private final String EntryPoint = "EntryPoint"; private final String DoQuit = "doQuit"; private final String CleanCache = "CleanCache"; private final String SetUIInterfaceOrientation = "SetUIInterfaceOrientation"; public static AbstractARMODActivity instance = null; private Class<?> originalActivity; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); instance = this; onCreateUI(); } @Override protected void onDestroy() { super.onDestroy(); originalActivity = null; instance = null; } //-------------------------------------------------------------------------------------------------------------- /** * Build the UI on the AR window */ public abstract void onCreateUI(); /** * When the device does not support AR-SDK, execute this method * */ abstract public void deviceNotSupport(); /** * This method is executed when the resource is loaded. */ abstract public void removeLoadingOverlay(); /** * Download resource progress */ abstract public void updateLoadingProgress(float _progressValue); /** * Start loading resources will execute the method */ abstract public void addLoadingOverlay(); /** * The method will be executed if an exception occurs * * @param _error SDK error string * @param _errorCode Error code */ abstract public void throwException(String _error,int _errorCode); /** * The device supports AR SDK, but AR Service needs to be installed */ abstract public void needInstallARCoreService(); /** * Use the APP built-in browser to open the specified link * @param _url url string */ abstract public void openBuiltInBrowser(String _url); /** * The algorithm of AR is initialized */ abstract public void sdkInitialized(); /** * Recognized successfully */ abstract public void recognitionComplete(); /** * Start to recognize */ abstract public void recognitionStart(); /** * Get device information * @param _opTag The type of operation request sent by the sdk */ abstract public String tryAcquireInformation(String _opTag); /** * Initialize SDK * * @param _appConfigure SDK configuration information, passed in in JSON format * @param _activity Act class of the current window */ public void initARMOD(String _appConfigure, Class<?> _activity) { originalActivity = _activity; callSDKMethod(InitSDK, _appConfigure); } /** * Query project details by project Id * * @param _id Project unique Id */ public void fetchProject(String _id) { new Handler(Looper.getMainLooper()) .postDelayed(() -> callSDKMethod(FetchByUid, _id), 1000); } /** * Start image recognition, the recognition is successful at the beginning of the recognition, please refer to'onRecognized' and'startRecognized' */ public void fetchProjectByImage(){ new Handler(Looper.getMainLooper()) .postDelayed(() -> callSDKMethod(LaunchARScanner, ""), 1000); } /** *Uninstall close the current SDK window */ public void unloadAndHideARMOD() { if (isInitialized()) { Intent intent = new Intent(getApplicationContext(), this.getClass()); intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); intent.putExtra(DoQuit, true); startActivity(intent); } } /** * Get the Frame layout on the AR window * * @return Frame Layout */ public FrameLayout getARMODFrameLayout() { if (isInitialized()) return mUnityPlayer; else return null; } /** * Get the Layout Inflater of the current window. You can set the following Id * * @return Layout Inflater */ public LayoutInflater getLayoutInflater() { return (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } /** * Set the orientation of the current window * * @param _orientationId Portrait=1; PortraitUpsideDown=2;LandscapeLeft=3;LandscapeRight=4; */ public void setUIInterfaceOrientation(String _orientationId) { callSDKMethod(SetUIInterfaceOrientation, _orientationId); } /** * Clear AR cache */ public void cleanCache(){ callSDKMethod(CleanCache,""); } //-------------------------------------------------------------------------------------------------------------- /** * Listen for Intent events * * @param intent intent */ private void handleIntent(Intent intent) { if (intent == null || intent.getExtras() == null) return; Log.i("handleIntent","handleIntent!!!!"); if (intent.getExtras().containsKey(DoQuit)) if (mUnityPlayer != null) { callSDKMethod(Dispose, ""); finish(); } } /** * Call SDK internal method * * @param _methodName Call method name * @param _data transfer data */ private void callSDKMethod(String _methodName, String _data) { if (isInitialized()) { UnityPlayer.UnitySendMessage(EntryPoint, _methodName, _data); } else { System.out.println("You can not send anything message to AR,Because SDK is not initialize"); } } /** *Uninstall AR window */ private void unloadARMODView() { Intent intent = new Intent(getApplicationContext(), originalActivity); intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_SINGLE_TOP); startActivity(intent); } /** * Determine whether the SDK is initialized * * @return False False means that it has not been initialized, and True means that the initialization is successful */ protected boolean isInitialized() { return mUnityPlayer != null; } /** * Get a new Intent * * @param intent intent */ @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); handleIntent(intent); setIntent(intent); } /** * Callback function, run when the AR window is closed */ @Override public void onUnityPlayerUnloaded() { unloadARMODView(); } //-------------------------------------------------------------------------------------------------------------- }
package sop.util; import java.io.File; import java.text.SimpleDateFormat; import java.util.Calendar; import org.apache.commons.lang.StringUtils; /** * @Author: LCF * @Date: 2020/1/9 11:21 * @Package: sop.util */ public class BaseSys { private static volatile long DELTA_TO_DB_TIMESTAMP = 0L; public static void setDbTimestampDelta(long delta) { DELTA_TO_DB_TIMESTAMP = delta; } public static boolean isUnix() { return System.getProperty("file.separator", "").equals("/"); } /** * On UNIX systems, this character is <code>':'</code>; on Microsoft Windows systems it * is <code>';'</code>. */ public static String getPathSeparator() { return File.pathSeparator; } public static String getFolderSeparator() { return File.separator; } public static java.util.Calendar getServerCalendar() { Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(System.currentTimeMillis() + DELTA_TO_DB_TIMESTAMP); return cal; } public static java.util.Date getServerDate() { return getServerCalendar().getTime(); } public static java.util.Date getDate() { return getServerDate(); } public static java.sql.Timestamp getTimestamp() { return new java.sql.Timestamp(getDate().getTime()); } public static String getYYYY() { return String.valueOf(getYear()); } public static String getMM() { return StringUtils.leftPad(String.valueOf(getMonth() + 1), 2, "0"); } public static String getDD() { return StringUtils.leftPad(String.valueOf(getDay()), 2, "0"); } public static int getYear() { return getCalendarWithoutTime().get(Calendar.YEAR); } public static int getMonth() { return getCalendarWithoutTime().get(Calendar.MONTH); } public static int getDay() { return getCalendarWithoutTime().get(Calendar.DAY_OF_MONTH); } public static java.util.Date getDateWithoutTime() { return DateUtils.trimDate(getServerDate(), Calendar.DAY_OF_MONTH); } public static java.util.Calendar getCalendarWithoutTime() { return DateUtils.trimDate(getServerCalendar(), Calendar.DAY_OF_MONTH); } public static String getCurrentTime() { SimpleDateFormat format = new SimpleDateFormat("HH:mm"); return format.format(getServerDate()); } public static java.sql.Timestamp getTimestampWithoutMillisecond() { long sysTime = getTimestamp().getTime(); return new java.sql.Timestamp((sysTime / 1000) * 1000); } public static void main(String[] args) { System.out.println(getYear()); System.out.println(getMonth()); System.out.println(getDay()); System.out.println(getYYYY()); System.out.println(getMM()); System.out.println(getDD()); } }
/* *@包名:com.b505.tools *@文档名:SSHA.java *@功能:密码加密 *@作者:李振强 *@创建时间:2014.5.10 *@版权:河北北方学院信息技术研究所 */ package com.hwj.tools; import java.security.MessageDigest; import org.springframework.stereotype.Component; @Component public class SSHA { /* * @方法名:digest(String str) * * @功能:密码加密 * * @功能说明:利用SHA算法进行SSHA加密 * * @作者:李振强 * * @创建时间:2014.5.10 * * @修改时间:2014.5.10 */ public String digest(String str) throws Exception { final String salt = "doWhile(1){LeavesFly();YangtzeRiverFlows();}"; String password = str + salt; MessageDigest md = MessageDigest.getInstance("SHA"); byte[] srcByte = password.getBytes(); md.update(srcByte); byte[] resByte = md.digest(); String returnStr = new String(resByte); return returnStr; } }
package TestRunner; import org.junit.runner.RunWith; import cucumber.api.CucumberOptions; import cucumber.api.junit.Cucumber; @RunWith(Cucumber.class) @CucumberOptions(features = "src/test/resources/Feature/SubPay.feature" ,glue= {"stepDefinition"} ,plugin= {"pretty","html:JunitReports/htmlreport", "json:JunitReports/jsonreport.json", "junit:JunitReports/xmlreport.xml", "com.cucumber.listener.ExtentCucumberFormatter:JunitReports/cucumber-reports/report.html"} ,monochrome=true) public class JunitRunner { }
package com.cags.EC; import java.util.List; /** * Interface for the objective function to be optimized. */ public interface ObjectiveFunction<P> { int length(); double f(List<P> args); }
package com.example.ecommerceapp.buyers; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.example.ecommerceapp.R; import com.example.ecommerceapp.model.Prevalent; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.HashMap; public class ConfirmFinalActivity extends AppCompatActivity { EditText et_name,et_phone,et_address,et_cityName; Button btn_confirm; String totalPrice ; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_confirm_final); totalPrice = getIntent().getStringExtra("total price"); Toast.makeText(ConfirmFinalActivity.this,totalPrice, Toast.LENGTH_LONG).show(); et_name =findViewById(R.id.confirm_et_name); et_phone =findViewById(R.id.confirm_et_phone); et_address =findViewById(R.id.confirm_et_address); et_cityName =findViewById(R.id.confirm_et_cityName); btn_confirm =findViewById(R.id.confirm_btn_confirm); btn_confirm.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { validationFields(); } }); } private void validationFields() { if(TextUtils.isEmpty(et_name.getText())){ Toast.makeText(ConfirmFinalActivity.this, " the name is empty",Toast.LENGTH_LONG).show(); }else if(TextUtils.isEmpty(et_phone.getText().toString())&&!TextUtils.isDigitsOnly(et_phone.getText())){ Toast.makeText(ConfirmFinalActivity.this, " check your phone number",Toast.LENGTH_LONG).show(); }else if (TextUtils.isEmpty(et_address.getText())){ Toast.makeText(ConfirmFinalActivity.this, " check your address",Toast.LENGTH_LONG).show(); }else if ((TextUtils.isEmpty(et_cityName.getText().toString()))){ Toast.makeText(ConfirmFinalActivity.this, " check your city name",Toast.LENGTH_LONG).show(); }else { confirmMethod(); } } private void confirmMethod() { Calendar calendar = Calendar.getInstance(); SimpleDateFormat simpleFormatDate = new SimpleDateFormat("MM :dd,yyyy"); String saveCurrentDate = simpleFormatDate.format(calendar.getTime()); SimpleDateFormat simpleFormatTime = new SimpleDateFormat("HH :mm:ss a"); String saveCurrentTime = simpleFormatTime.format(calendar.getTime()); DatabaseReference conRef = FirebaseDatabase.getInstance().getReference().child("orders") .child(Prevalent.onlineUser.getPhone()); HashMap<String , Object> map = new HashMap<>(); map.put("totalPrice", totalPrice); map.put("name", et_name.getText().toString()); map.put("phone", et_phone.getText().toString()); map.put("address", et_address.getText().toString()); map.put("cityName", et_cityName.getText().toString()); map.put("date", saveCurrentDate); map.put("time", saveCurrentTime); map.put("state", "not shipped"); conRef.updateChildren(map).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if(task.isSuccessful()){ FirebaseDatabase.getInstance().getReference().child("cart list").child("user view") .child(Prevalent.onlineUser.getPhone()).child("products") .removeValue().addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if(task.isSuccessful()){ Toast.makeText(ConfirmFinalActivity.this, " confirmed successful ",Toast.LENGTH_LONG).show(); Intent intent = new Intent(ConfirmFinalActivity.this, HomeActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent); } } }); } } }); } }
// File : Park.java // PIC : Letivany Aldina - 13514067 /** * * @author Letivany Aldina - 13514067 */ public class Park extends Cell implements Facility { private final String tipeCell = "park"; private final char simbol = '*'; /** * constructor kelas * @param x posisi x Cell * @param y posisi y Cell */ public Park(int x, int y){ super(x,y); } /** * mengembalikan tipe Cell dari park * @return string tipe Cell */ @Override public String getTipeCell(){ return tipeCell; } /** * mengembalikan simbol tipe Cell * @return char simbol Cell */ @Override public char render(){ return simbol; } }
package com.alex.eat; public interface Weigh { int getWeight(); }
package com.apperun.clubchooser; /** * Created by Slang on 7/1/2017. */ public class Choice { private String choiceName; private int sports; private int arts; private int community; private int academics; public Choice(String choiceName, int academics, int sports, int arts, int community){ this.choiceName = choiceName; this.sports = sports; this.arts = arts; this.community = community; this.academics = academics; } public Choice(String choiceName){ this(choiceName, 0, 0, 0, 0); } public String getChoiceName() { return choiceName; } public void setChoiceName(String choiceName) { this.choiceName = choiceName; } public int getSports() { return sports; } public void setSports(int sports) { this.sports = sports; } public int getArts() { return arts; } public void setArts(int arts) { this.arts = arts; } public int getCommunity() { return community; } public void setCommunity(int community) { this.community = community; } public int getAcademics() { return academics; } public void setAcademics(int academics) { this.academics = academics; } }
//package registration; // //import static org.junit.Assert.*; // //import java.awt.AWTException; //import java.awt.Component; //import java.awt.Container; //import java.io.File; // //import javax.swing.JButton; //import javax.swing.JPanel; //import javax.swing.JTextArea; //import javax.swing.JTextField; // //import org.junit.After; //import org.junit.Before; //import org.junit.Test; // //public class GuiTest { // // private Gui gui; // private JButton button; // private JTextArea textOutput; // private JTextField textEntry; // private JPanel faultyRegistrationPanel; // private final String file = "/test/output.txt"; // private Component[] listItems; // // @Before // public void before() throws AWTException { // gui = new Gui(file, new ClientConnection()); // button = (JButton) getComponent(gui, "button"); // textOutput = (JTextArea) getComponent(gui, "textOutput"); // textEntry = (JTextField) getComponent(gui, "textEntry"); // faultyRegistrationPanel = (JPanel) getComponent(gui, "faultyRegistrationPanel"); // listItems = faultyRegistrationPanel.getComponents(); // } // // @After // public void after() { // File f = new File(file); // if (!f.delete()) { // System.out.println("Failed to remove " + file); // } // } // // @Test // public void testOneRegistration() { // textEntry.setText("1"); // button.doClick(); // assertEquals("1",textOutput.getText().substring(0, 1)); // assertEquals(11, textOutput.getText().trim().length()); // assertEquals(0, textEntry.getText().length()); // } // // @Test // public void testMultipleRegistrations() { // textEntry.setText("1-8"); // button.doClick(); // String[] lines = textOutput.getText().split("\n"); // assertEquals(8, lines.length); // } // // @Test // public void testClassRegistration() { // textEntry.setText("@seniorer"); // button.doClick(); // assertEquals("seniorer", textOutput.getText().substring(0, 8)); // } // // @Test // public void testRemoveFaultyRegistration() { // button.doClick(); // ListItem li = (ListItem) getComponent(gui, "listItem0"); // assertEquals(8, li.getText().length()); // JButton removeButton = (JButton) getComponent(gui, "removeButton"); // removeButton.doClick(); // try { // ListItem li0 = (ListItem) getComponent(gui, "listItem0"); // li0.getText(); // assertFalse(true); // } catch (Exception e) { } // } // // @Test // public void testEmptyField() { // button.doClick(); // ListItem li = (ListItem) getComponent(gui, "listItem0"); // assertEquals(8, li.getText().length()); // try { // ListItem li1 = (ListItem) getComponent(gui, "listItem1"); // li1.getText(); // assertFalse(true); // } catch (Exception e) { } // } // // public static Component getComponent(Component parent, String name) { // if (name.equals(parent.getName())) { // return parent; // } // // if (parent instanceof Container) { // Component[] children = ((Container) parent).getComponents(); // // for (Component c : children) { // Component child = getComponent(c, name); // if (child != null) return child; // } // } // return null; // } //}
package class1; import java.util.Scanner; public class toantu { public static void main(String[] args) { int a; int b; int tong; Scanner scanner = new Scanner(System.in); System.out.println("Nhap so a"); a = scanner.nextInt(); System.out.println("Nhap so b"); b = scanner.nextInt(); tong=a + b; System.out.println("Tong 2 so la: " + tong); System.out.println("Binh phuong tong la: " + Math.pow(tong,2)); System.out.println("can bac 2 tong la: " + Math.sqrt(tong)); } }
package com.esum.comp.tcprelay; import com.esum.common.exception.XTrusException; public class TcpRelayException extends XTrusException { public TcpRelayException(String code, String location, String message, Throwable cause) { super(code, location, message, cause); } public TcpRelayException(String location, String message, Throwable cause) { super(location, message, cause); } public TcpRelayException(String code, String location, String message) { super(code, location, message); } }
/******************************************************************************* ** ** Advanced Distributed Learning Co-Laboratory (ADL Co-Lab) grants you ** ("Licensee") a non-exclusive, royalty free, license to use, modify and ** redistribute this software in source and binary code form, provided that ** i) this copyright notice and license appear on all copies of the software; ** and ii) Licensee does not utilize the software in a manner which is ** disparaging to ADL Co-Lab. ** ** This software is provided "AS IS," without a warranty of any kind. ALL ** EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ** ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE ** OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. ADL Co-Lab AND ITS LICENSORS ** SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF ** USING, MODIFYING OR DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN NO ** EVENT WILL ADL Co-Lab OR ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, ** PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, ** INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE ** THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE ** SOFTWARE, EVEN IF ADL Co-Lab HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH ** DAMAGES. ** *******************************************************************************/ package com.ziaan.scorm2004.validator.contentpackage; // native java imports import java.util.ArrayList; import java.util.logging.Logger; // xerces imports // adl imports /** * * <strong>Filename: </strong><br>LaunchData.java<br><br> * * <strong>Description: </strong><br> A <CODE>LaunchData</CODE> is a Data * Structure used to store information for the Launch Data of SCOs.<br><br> * * <strong>Design Issues: </strong><br>None<br> * <br> * * <strong>Implementation Issues: </strong><br>None<br><br> * * <strong>Known Problems: </strong><br>None<br><br> * * <strong>Side Effects: </strong><br>None<br><br> * * <strong>References: </strong><br>None<br><br> * * @author ADL Technical Team */ public class LaunchData { /** * Logger object used for debug logging.<br> */ private Logger mLogger; /** * The identifier attribute of the <organization> element.<br> */ private String mOrganizationIdentifier; /** * The identifier attribute of the <item> element.<br> */ private String mItemIdentifier; /** * The identifier attribute of the <resource> element.<br> */ private String mResourceIdentifier; /** * The xml:base attribute of the <manifest> element.<br> */ private String mManifestXMLBase; /** * The xml:base attribute of the <resources> element.<br> */ private String mResourcesXMLBase; /** * The xml:base attribute of the <resource> element.<br> */ private String mResourceXMLBase; /** * The parameter value of the item.<br> */ private String mParameters; private boolean mIsVisible; private String mResType; private ArrayList mResFileUrl; private ArrayList mRefResId; private String mItemMetaLocation; private String mResourceMetaLocation; /** * The persistState attribute of an item. */ private String mPersistState; /** * The location of the item.<br> */ private String mLocation; /** * The SCORM type of the item (i.e. sco, sca, asset).<br> */ private String mSCORMType; /** * The title value of the item.<br> */ private String mItemTitle; /** * The variable representing the datafromlms element of the item.<br> */ private String mDataFromLMS; /** * The variable representing the timelimitaction element of the item.<br> */ private String mTimeLimitAction; /** * The variable representing the minNormalizedMeasure element.<br> */ private String mMinNormalizedMeasure; /** * The variable representing the attemptAbsoluteDurationLimit element.<br> */ private String mAttemptAbsoluteDurationLimit; /** * The variable representing the completionThreshold element.<br> */ private String mCompletionThreshold; /** * The variable representing the objectives found in the sequencing.<br> */ private String mObjectivesList; /** * The variable representing the hideRTSUI value of "previous".<br> */ public boolean mPrevious; /** * The variable representing the hideRTSUI value of "continue".<br> */ public boolean mContinue; /** * The variable representing the hideRTSUI value of "exit".<br> */ public boolean mExit; /** * The variable representing the hideRTSUI value of "abandon".<br> */ public boolean mAbandon; private String mParentIdentifier; private String mObjID; private int mTreeOrder; /** * The default constructor.<br> */ public LaunchData() { mLogger = Logger.getLogger("com.ziaan.scorm2004.validator"); mOrganizationIdentifier = new String(); mItemIdentifier = new String(); mResourceIdentifier = new String(); mManifestXMLBase = new String(); mResourcesXMLBase = new String(); mResourceXMLBase = new String(); // Item mIsVisible = true; mParameters = new String(); mItemTitle = new String(); mTimeLimitAction = new String(); mAttemptAbsoluteDurationLimit = new String(); mDataFromLMS = new String(); mCompletionThreshold = new String(); mLocation = new String(); mParentIdentifier = new String(); mObjID = new String(); // Resource mSCORMType = new String(); mPersistState = new String(); mResType = new String();; mResFileUrl = new ArrayList(); mRefResId = new ArrayList(); // Sequencing mMinNormalizedMeasure = new String(); mObjectivesList = new String(); mPrevious = false; mContinue = false; mExit = false; mAbandon = false; } /** * * Assigns the given value to the mOrganizationIdentifier attribute. <br> * * @param iOrganizationIdentifier - The organization identitifier value to * be assigned. <br> */ public void setOrganizationIdentifier( String iOrganizationIdentifier ) { mOrganizationIdentifier = iOrganizationIdentifier; } /** * * Assigns the given value to the mItemIdentifier attribute.<br> * * @param iItemIdentifier - The item identifier value to be assigned.<br> */ public void setItemIdentifier( String iItemIdentifier ) { mItemIdentifier = iItemIdentifier; } /** * * Assigns the given value to the mResourceIdentifier attribute.<br> * * @param iResourceIdentifier - The resource identifier value to be assigned. * <br> */ public void setResourceIdentifier( String iResourceIdentifier ) { mResourceIdentifier = iResourceIdentifier; } /** * * Assigns the given value to the mManifestXMLBase attribute.<br> * * @param iManifestXMLBase - The manifest xml:base value to be assigned.<br> */ public void setManifestXMLBase( String iManifestXMLBase ) { mManifestXMLBase = iManifestXMLBase; } /** * * Assigns the given value to the mResourcesXMLBase attribute.<br> * * @param iResourcesXMLBase - The resources xml:base value to be assigned.<br> */ public void setResourcesXMLBase( String iResourcesXMLBase ) { mResourcesXMLBase = iResourcesXMLBase; } /** * * Assigns the given value to the mResourceXMLBase attribute.<br> * * @param iResourceXMLBase - The resource xml:base value to be assigned.<br> */ public void setResourceXMLBase( String iResourceXMLBase ) { mResourceXMLBase = iResourceXMLBase; } /** * * Assigns the given value to the mParameters attribute.<br> * * @param iParameters - The parameters value to be assigned.<br> */ public void setParameters( String iParameters ) { mParameters = iParameters; } /** * * Assigns the given value to the mPersistState attribute of an item.<br> * * @param iPersistState - The persistState value to be assigned.<br> */ public void setPersistState( String iPersistState ) { mPersistState = iPersistState; } /** * * Assigns the given value to the mLocation attribute.<br> * * @param iLocation - The location value to be assigned.<br> */ public void setLocation( String iLocation ) { mLocation = iLocation; } /** * * Assigns the given value to the mSCORMType attribute.<br> * * @param iSCORMType - The scormtype value to be assigned.<br> */ public void setSCORMType( String iSCORMType ) { mSCORMType = iSCORMType; } /** * * Assigns the given value to the mItemTitle attribute.<br> * * @param iSCORMType - The item value to be assigned.<br> */ public void setItemTitle( String iItemTitle ) { mItemTitle = iItemTitle; } /** * Assigns the given value to the mDataFromLMS attribute.<br> * * @param iDataFromLMS - The datafromlms value to be assigned.<br> */ public void setDataFromLMS( String iDataFromLMS ) { mDataFromLMS = iDataFromLMS; } /** * Assigns the given value to the mTimeLimitAction attribute.<br> * * @param iTimeLimitAction - The timelimitaction value to be assigned.<br> */ public void setTimeLimitAction( String iTimeLimitAction ) { mTimeLimitAction = iTimeLimitAction; } /** * Assigns the given value to the minNormalizedMeasure attribute.<br> * * @param iMinNormalizedMeasure - The minnormalizedmeasure value to be * assigned.<br> */ public void setMinNormalizedMeasure( String iMinNormalizedMeasure ) { mMinNormalizedMeasure = iMinNormalizedMeasure; } /** * Assigns the given value to the attemptAbsoluteDurationLimit attribute.<br> * * @param iAttemptAbsoluteDurationLimit - The attemptabsolutedurationlimit * value to be assigned.<br> */ public void setAttemptAbsoluteDurationLimit( String iAttemptAbsoluteDurationLimit ) { mAttemptAbsoluteDurationLimit = iAttemptAbsoluteDurationLimit; } /** * Assigns the given value to the mCompletionThreshold attribute.<br> * * @param iCompletionThreshold - The completionThreshold value to be * assigned.<br> */ public void setCompletionThreshold( String iCompletionThreshold ) { mCompletionThreshold = iCompletionThreshold; } /** * Assigns the given value to the mObjectivesList attribute.<br> * * @param iObjectivesList - The objectives to be * assigned.<br> */ public void setObjectivesList( String iObjectivesList ) { mObjectivesList = iObjectivesList; } /** * Assigns the given value to the mPrevious attribute.<br> * * @param iPrevious - The previous value to be assigned.<br> */ public void setPrevious( boolean iPrevious ) { mPrevious = iPrevious; } /** * Assigns the given value to the mContinue attribute.<br> * * @param iContinue - The continue value to be assigned.<br> */ public void setContinue( boolean iContinue ) { mContinue = iContinue; } /** * Assigns the given value to the mExit attribute.<br> * * @param iExit - The exit value to be assigned.<br> */ public void setExit( boolean iExit ) { mExit = iExit; } /** * Assigns the given value to the mAbandon attribute.<br> * * @param iAbandon - The abandon value to be assigned.<br> */ public void setAbandon( boolean iAbandon ) { mAbandon = iAbandon; } /** * Gives access to the indentifier value of the <organization> element.<br> * * @return - The identifier value of the <organization> element.<br> */ public String getOrganizationIdentifier() { return mOrganizationIdentifier; } /** * * Gives access to the identifier value of the <item> element.<br> * * @return - The identifier value of the <item> element.<br> */ public String getItemIdentifier() { return mItemIdentifier; } /** * * Gives access to the identifier value of the <resource> element.<br> * * @return - The identifier value of the <resource> element.<br> */ public String getResourceIdentifier() { return mResourceIdentifier; } /** * * Gives access to the xml:base value of the <manifest> element.<br> * * @return - The xml:base value of the <manifest> element.<br> */ public String getManifestXMLBase() { return mManifestXMLBase; } /** * * Gives access to the xml:base value of the <resources> element.<br> * * @return - The xml:base value of the <resources> element.<br> */ public String getResourcesXMLBase() { return mResourcesXMLBase; } /** * * Gives access to the xml:base value of the <resource> element.<br> * * @return - The xml:base value of the <resource> element.<br> */ public String getResourceXMLBase() { return mResourceXMLBase; } /** * * Gives access to the full xml:base value.<br> * * @return - The full xml:base value as determined in the manifest.<br> */ public String getXMLBase() { String result = mManifestXMLBase; // add a file separator only if there is a directory before and after it. if ( (! result.equals("")) && (! mResourcesXMLBase.equals("")) && (! result.endsWith("/")) ) { result += "/"; } result += mResourcesXMLBase; // add a file separator only if there is a directory before and after it. if ( (! result.equals("")) && (! mResourceXMLBase.equals("")) && (! result.endsWith("/")) ) { result += "/"; } result += mResourceXMLBase; return result; } /** * * Gives access to the parameters of the item.<br> * * @return - The parameter value of the item.<br> */ public String getParameters() { return mParameters; } /** * Gives access to the persistState attribute of the item.<br> * * @return = The value of the persistState attribute of the item.<br> */ public String getPersistState() { return mPersistState; } /** * * Gives access to the location of the item.<br> * * @return - The location value of the item.<br> */ public String getLocation() { return mLocation; } /** * * Gives access to the SCORM type value of the item.<br> * * @return - The SCORM type value of the item.<br> */ public String getSCORMType() { return mSCORMType; } /** * * Gives access to the title value of the item.<br> * * @return - The title value of the item.<br> */ public String getItemTitle() { return mItemTitle; } /** * * Gives access to the datafromlms element value of the item.<br> * * @return - The value of the datafromlms element.<br> */ public String getDataFromLMS() { return mDataFromLMS; } /** * * Gives access to the timelimitaction element value of the item.<br> * * @return - The value of the timelimitaction element.<br> */ public String getTimeLimitAction() { return mTimeLimitAction; } /** * * Gives access to the minNormalizedMeasure element value.<br> * * @return - The value of the minNormalizedMeasure element.<br> */ public String getMinNormalizedMeasure() { return mMinNormalizedMeasure; } /** * * Gives access to the attemptAbsoluteDurationLimit element value.<br> * * @return - The value of the attemptAbsoluteDurationLimit element.<br> */ public String getAttemptAbsoluteDurationLimit() { return mAttemptAbsoluteDurationLimit; } /** * Gives access to the completionThreshold element value.<br> * * @return - The value of the completionThreshold element.<br> */ public String getCompletionThreshold() { return mCompletionThreshold; } /** * Gives access to the objectiveslist element value.<br> * * @return - The value of the objectiveslist element.<br> */ public String getObjectivesList() { return mObjectivesList; } /** * * Gives access to the value of mPrevious, which is a boolean * representing whether a hideRTSUI element for the item had the value of * "previous".<br> * * @return - The value of the mPrevious.<br> */ public boolean getPrevious() { return mPrevious; } /** * * Gives access to the value of mContinue, which is a boolean * representing whether a hideRTSUI element for the item had the value of * "continue".<br> * * @return - The value of the mContinue.<br> */ public boolean getContinue() { return mContinue; } /** * * Gives access to the value of mExit, which is a boolean * representing whether a hideRTSUI element for the item had the value of * "exit".<br> * * @return - The value of the mExit.<br> */ public boolean getExit() { return mExit; } /** * * Gives access to the value of mAbandon, which is a boolean * representing whether a hideRTSUI element for the item had the value of * "abandon".<br> * * @return - The value of the mAbandon.<br> */ public boolean getAbandon() { return mAbandon; } /** * * Gives access to the full launch line of the item including the full * xml:base of the item.<br> * * @return - The full launch location of the item.<br> */ public String getLaunchLine() { String xmlBase = getXMLBase(); if ( (! xmlBase.equals("")) && (! xmlBase.endsWith("/")) ) { xmlBase += "/"; } return xmlBase + mLocation + mParameters; } /** * * Displays a string representation of the data structure for the SCO * Integration to the Java logger. <br> * */ public void print() { mLogger.fine( "##################################################"); mLogger.fine( "#### resourceIdentifier = '" + mResourceIdentifier + "'"); mLogger.fine( "#### itemIdentifier = '" + mItemIdentifier + "'"); mLogger.fine( "#### itemTitle = '" + mItemTitle + "'"); mLogger.fine( "#### manifestXMLBase = '" + mManifestXMLBase + "'"); mLogger.fine( "#### resourcesXMLBase = '" + mResourcesXMLBase + "'"); mLogger.fine( "#### resourceXMLBase = '" + mResourceXMLBase + "'"); mLogger.fine( "#### scormType = '" + mSCORMType + "'"); mLogger.fine( "#### parameters = '" + mParameters + "'"); mLogger.fine( "#### isvisible = '" + mIsVisible + "'"); mLogger.fine( "#### location = '" + mLocation + "'"); mLogger.fine( "#### LaunchLine = '" + getLaunchLine() + "'"); mLogger.fine( "##################################################"); } /** * Displays a string representation of the data structure for Integration to * the Java Console.<br> * */ public void printToConsole() { System.out.println( "###############################################"); System.out.println( "### resourceIdentifier = '" + mResourceIdentifier + "'"); System.out.println( "### itemIdentifier = '" + mItemIdentifier + "'"); System.out.println( "### itemTitle = '" + mItemTitle + "'"); System.out.println( "### manifestXMLBase = '" + mManifestXMLBase + "'"); System.out.println( "### resourcesXMLBase = '" + mResourcesXMLBase + "'"); System.out.println( "### resourceXMLBase = '" + mResourceXMLBase + "'"); System.out.println( "### scormType = '" + mSCORMType + "'"); System.out.println( "### parameters = '" + mParameters + "'"); System.out.println( "### isvisible = '" + mIsVisible + "'"); System.out.println( "### location = '" + mLocation + "'"); System.out.println( "### LaunchLine = '" + getLaunchLine() + "'"); System.out.println( "###############################################"); } // Added code by Jin-pil Chung, 2006.04.28 public void setIsVisible( boolean iIsVisible ) { mIsVisible = iIsVisible; } public boolean getIsVisible() { return mIsVisible; } public void setResType( String iResType ) { mResType = iResType; } public String getResType() { return mResType; } public void setResFileUrl(ArrayList iResFileUrl) { mResFileUrl = iResFileUrl; } public ArrayList getResFileUrl() { return mResFileUrl; } public void setRefResId(ArrayList iRefResId) { mRefResId = iRefResId; } public ArrayList getRefResId() { return mRefResId; } public void setItemMetaLocation(String iItemMetaLocation) { mItemMetaLocation = iItemMetaLocation; } public String getItemMetaLocation() { return mItemMetaLocation; } public void setResourceMetaLocation(String iResourceMetaLocation) { mResourceMetaLocation = iResourceMetaLocation; } public String getResourceMetaLocation() { return mResourceMetaLocation; } public void setObjID(String iObjID) { mObjID = iObjID; } public String getObjID() { return mObjID; } public void setItemPIdentifier(String iParentIdentifier) { mParentIdentifier = iParentIdentifier; } public String getItemPIdentifier() { return mParentIdentifier; } public void setTreeOrder(int iTreeOrder) { mTreeOrder = iTreeOrder; } public int getTreeOrder() { return mTreeOrder; } }
package com.beike.common.exception; /** * @Title:LotteryRegException.java * @Package com.beike.common.exception * @Description: 抽奖活动 * @date May 17, 2011 2:50:42 PM * @author jianjun.huo * @version v1.0 */ public class LotteryRegException extends BaseException { private static final long serialVersionUID = 3702637877386451709L; public LotteryRegException() { super(); } public LotteryRegException(int code) { super(code); } public LotteryRegException(String errorMsg) { super(errorMsg); } }
package MethodsEncapsulation; /** * Created by RXC8414 on 5/19/2017. */ public class ArgumentMain { public static void main(String[] args) { Arguments arg = new Arguments(); // You can send as many arguments as needed and they don't // have to be of the same data type // NOTE: this method MUST receive one String, one String, one int and one char // in that same order arg.personInfo("Rolando","Colon",43,'M'); } }
package designpatterns.factory.simple; /** * https://design-patterns.readthedocs.io/zh_CN/latest/creational_patterns/simple_factory.html * 设计模式的组成; 遵循的设计原则; 优点; 缺点; 适用的场景 */ public class SimpleFactory { public static Product createProduct(String productName) { if (productName == "A") { return new ConcreteProductA(); } else if (productName == "B") { return new ConcreteProductB(); } return null; } public static void main(String[] args) { SimpleFactory.createProduct("A"); } }
/* * ################################################################ * * ProActive Parallel Suite(TM): The Java(TM) library for * Parallel, Distributed, Multi-Core Computing for * Enterprise Grids & Clouds * * Copyright (C) 1997-2011 INRIA/University of * Nice-Sophia Antipolis/ActiveEon * Contact: proactive@ow2.org or contact@activeeon.com * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; version 3 of * the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * * If needed, contact us to obtain a release under GPL Version 2 or 3 * or a different license than the AGPL. * * Initial developer(s): The ProActive Team * http://proactive.inria.fr/team_members.htm * Contributor(s): * * ################################################################ * $$PROACTIVE_INITIAL_DEV$$ */ package org.ow2.proactive.scheduler.ext.matsci.client; import java.io.Serializable; /** * ResultsAndLogs an object encapsulating PAsolve Matlab or Scilab results plus logs and exceptions * * @author The ProActive Team */ public class ResultsAndLogs<R> implements Serializable { /** */ private static final long serialVersionUID = 31L; protected R result; protected String logs; protected Throwable exception; public ResultsAndLogs() { } public void setResult(R result) { this.result = result; } public void setLogs(String logs) { this.logs = logs; compressLogs(); } public void setException(Throwable exception) { this.exception = exception; } protected MatSciTaskStatus status; public boolean isGlobalError() { return status == MatSciTaskStatus.GLOBAL_ERROR; } public boolean isRuntimeError() { return status == MatSciTaskStatus.RUNTIME_ERROR; } public boolean isOK() { return status == MatSciTaskStatus.OK; } public MatSciTaskStatus getStatus() { return status; } public void setStatus(MatSciTaskStatus status) { this.status = status; } public ResultsAndLogs(R result, String logs, Throwable exception, MatSciTaskStatus status) { this.result = result; this.logs = logs; compressLogs(); this.exception = exception; this.status = status; } public R getResult() { return result; } public String getLogs() { return logs; } public boolean isMatSciError() { return status == MatSciTaskStatus.MATSCI_ERROR; } @Override public String toString() { if (result != null) return result.toString(); else if (exception != null) { return exception.getMessage(); } else { return "Error in remote script code"; } } public Throwable getException() { return exception; } private void compressLogs() { if (logs.length() > 0) { StringBuilder sb = new StringBuilder(logs); char last = sb.charAt(0); for (int i = 1; i < sb.length(); i++) { if (last == '\r' && sb.charAt(i) == '\n') { sb.deleteCharAt(i - 1); } else { last = sb.charAt(i); } } logs = sb.toString(); } } }
package org.dbdoclet.tidbit.perspective.docbook.html; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JColorChooser; import org.dbdoclet.Identifier; import org.dbdoclet.service.ResourceServices; import org.dbdoclet.tidbit.common.Constants; import org.dbdoclet.tidbit.perspective.panel.docbook.EbnfPanel; import org.dbdoclet.tidbit.project.Project; import org.dbdoclet.tidbit.project.driver.AbstractDriver; public class HtmlEbnfPanel extends EbnfPanel implements ActionListener { private static final long serialVersionUID = 1L; private JCheckBox ebnfTableBorder; private JButton ebnfTableBgcolorButton; private Color ebnfTableBgColor; public HtmlEbnfPanel() { createGui(); } @Override protected void createGui() { super.createGui(); ebnfTableBorder = jf.createCheckBox(new Identifier("ebnf.table.border"), "ebnf.table.border"); defaultsPanel.addComponent(ebnfTableBorder); ebnfTableBgcolorButton = jf.createButton(Constants.COLOR_CHAR + " ebnf.table.bgcolor..."); ebnfTableBgcolorButton.addActionListener(this); defaultsPanel.addComponent(ebnfTableBgcolorButton); addVerticalGlue(); } @Override public void syncView(Project project, AbstractDriver driver) { super.syncView(project, driver); ebnfTableBorder.setSelected(driver.isParameterEnabled("ebnf.table.border", true)); ebnfTableBgColor = driver.getColorParameter("ebnf.table.bgcolor"); ebnfTableBgcolorButton.setForeground(ebnfTableBgColor); } @Override public void syncModel(Project project, AbstractDriver driver) { super.syncModel(project, driver); driver.setParameter("ebnf.table.border", ebnfTableBorder.isSelected()); driver.setColorParameter("ebnf.table.bgcolor", ebnfTableBgColor); } public void actionPerformed(ActionEvent event) { Object source = event.getSource(); if (source != null && source == ebnfTableBgcolorButton) { Color color = JColorChooser.showDialog(this, ResourceServices.getString(res,"C_COLOR"), ebnfTableBgColor); if (color != null) { ebnfTableBgColor = color; ebnfTableBgcolorButton.setForeground(color); } } } }
package util; /** * Created by Tejal Shah. */ public class ProcessEvent { }
package com.xixiwan.platform.module.common.util; import org.apache.commons.lang3.exception.ExceptionUtils; import org.apache.commons.mail.DefaultAuthenticator; import org.apache.commons.mail.Email; import org.apache.commons.mail.SimpleEmail; /** * @ClassName: EmailUtil * @Description: 邮件工具类 * @Author: Sente * @Date: 2018年10月2日 下午1:51:40 * @Copyright: 2018 www.sto.cn Inc. All rights reserved. */ public class EmailUtils { private EmailUtils() { throw new IllegalStateException("EmailUtil class"); } public static void simpleEmail(String subject, String msg, String... emails) { try { Email email = new SimpleEmail(); email.setHostName("smtp.163.com"); email.setAuthenticator(new DefaultAuthenticator("liaoxiting2011@163.com", "wy13875470948")); email.setSSLOnConnect(true); email.setSSLCheckServerIdentity(true); email.setFrom("liaoxiting2011@163.com"); email.setSubject(subject); email.setMsg(msg); email.addTo(emails); email.send(); } catch (Exception e) { ExceptionUtils.rethrow(e); } } }
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; /** * @describle: * @author: pangxiaofeng * @create: 2020/12/21 **/ @SpringBootApplication @ComponentScan("com.fengxiong.*") public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
package com.zxt.compplatform.formengine.dao; import java.sql.Blob; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import com.zxt.compplatform.formengine.entity.view.Page; /** * 数据查询实现 * @author 007 */ public class QueryDataDao extends BaseDao implements IQueryDataDao { /* (non-Javadoc) * @see com.zxt.compplatform.formengine.dao.IQueryDataDao#queryPages(com.zxt.compplatform.formengine.entity.view.Page) */ public String queryPages(Page page) { String formId = page.getFormId(); Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; List list = new ArrayList(); String res = ""; StringBuffer query = new StringBuffer(); try { conn = getConn(); query.append(" SELECT "); query.append(" TY.STY_CONTENT"); query.append(" FROM BP_T_FORM_FORMSDEFINITION TY "); query.append(" WHERE FORMS_ID = '" + formId + "'"); // System.out.println(query.toString()); pstmt = conn.prepareStatement(query.toString()); rs = pstmt.executeQuery(); while (rs.next()) { Blob b = rs.getBlob("STY_CONTENT"); res = new String(b.getBytes(1L, (int) b.length())); } } catch (SQLException e) { e.printStackTrace(); } finally { try { if (rs != null) rs.close(); if (pstmt != null) pstmt.close(); if (conn != null) conn.close(); } catch (Exception e) { e.printStackTrace(); } } return res; } /* (non-Javadoc) * @see com.zxt.compplatform.formengine.dao.IQueryDataDao#queryTabs(java.lang.String) */ public String queryTabs(String tabId) { return null; } }
package com.example.aizat.homework3.custom_view; import android.content.Context; import android.media.Image; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.Gravity; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import com.example.aizat.homework3.R; /** * Created by Aizat on 06.10.2017. */ public class PagerIndicator extends LinearLayout { private int currentPosition; public PagerIndicator(Context context) { super(context); init(); } public PagerIndicator(Context context, @Nullable AttributeSet attrs) { super(context, attrs); init(); } public PagerIndicator(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void init() { setOrientation(HORIZONTAL); setGravity(Gravity.CENTER); } public void setItemCount(int count, int currentPosition){ removeAllViews(); for (int i = 0; i < count; i++){ ImageView imageView = new ImageView(getContext()); imageView.setImageResource(R.drawable.indicator_unactive); addView(imageView); } setCurrentPosition(currentPosition); } public void setCurrentPosition(int position) { if (position >= 0 && position < getChildCount()){ ((ImageView)getChildAt(currentPosition)).setImageResource(R.drawable.indicator_unactive); currentPosition = position; ((ImageView)getChildAt(currentPosition)).setImageResource(R.drawable.indicator_active); } } }
package com.github.gaoyangthu.esanalysis.ebusi.service.impl; import com.github.gaoyangthu.core.mysql.EbusiUtil; import com.github.gaoyangthu.esanalysis.ebusi.bean.AccountMeta; import com.github.gaoyangthu.esanalysis.ebusi.dao.AccountMetaMapper; import com.github.gaoyangthu.esanalysis.ebusi.service.AccountService; import org.apache.ibatis.session.SqlSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; /** * account_meta表实现 * * Author: gaoyangthu * Date: 14-3-12 * Time: 下午3:12 */ public class AccountServiceImpl implements AccountService { private static final Logger LOGGER = LoggerFactory.getLogger(AccountServiceImpl.class); /** * 根据accountId查询用户信息 * * @param accountId 用户ID * @return 用户信息 */ @Override public AccountMeta getAccount(String accountId) { AccountMeta accountMeta = null; SqlSession sqlSession = EbusiUtil.getSessionFactory().openSession(); try { AccountMetaMapper accountMetaMapper = sqlSession.getMapper(AccountMetaMapper.class); accountMeta = accountMetaMapper.selectByPrimaryKey(accountId); } finally { sqlSession.close(); } return accountMeta; } /** * 根据日期查询注册用户 * * @param beginDate 开始时间 * @param endDate 结束时间 * @return 用户列表 */ @Override public List<AccountMeta> findByDate(Date beginDate, Date endDate) { List<AccountMeta> accounts = null; Map<String, Object> params = new HashMap<String, Object>(); params.put("beginDate", beginDate); params.put("endDate", endDate); SqlSession sqlSession = EbusiUtil.getSessionFactory().openSession(); try { AccountMetaMapper accountMetaMapper = sqlSession.getMapper(AccountMetaMapper.class); accounts = accountMetaMapper.findByDate(params); } finally { sqlSession.close(); } return accounts; } }
package co.edu.una.UNalmanaqueback.backend.model; import com.fasterxml.jackson.annotation.JsonIgnore; import javax.persistence.*; import java.sql.Date; import java.util.List; @Entity @Table(name = "User", schema = "unalmanaquedb") public class User { @Id @GeneratedValue(strategy=GenerationType.AUTO) private Integer userId; @Column private String userName; @Column private String userEmail; @Column private String userPassword; @Column private Date userBorn; public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getUserEmail() { return userEmail; } public void setUserEmail(String userEmail) { this.userEmail = userEmail; } public String getUserPassword() { return userPassword; } public void setUserPassword(String userPassword) { this.userPassword = userPassword; } public Date getUserBorn() { return userBorn; } public void setUserBorn(Date userBorn) { this.userBorn = userBorn; } //Foreign Keys @JsonIgnore @OneToMany (mappedBy = "user") private List<Event> events; }
import java.util.*; class Vertex{ HashMap<Integer, Integer> sosedi; Vertex(){ sosedi = new HashMap<>(); } } public class Main { private static int findmin(int S, int T, HashMap<Integer, Integer> parentMap, Vertex[] ver){ int min = Integer.MAX_VALUE; int current = T; while(current != S){ int parent = parentMap.get(current); int val = ver[parent].sosedi.get(current); if(val < min) min = val; current = parent; } return min; } private static void reducePaths(int S, int T, HashMap<Integer, Integer> parentMap, Vertex[] ver, int val){ int current = T; while(current != S){ int parent = parentMap.get(current); ver[parent].sosedi.put(current, ver[parent].sosedi.get(current) - val); ver[current].sosedi.put(parent, ver[current].sosedi.get(parent) + val); current = parent; } } public static void main(String[] args){ Scanner sc = new Scanner(System.in); int V = sc.nextInt(); int E = sc.nextInt(); //inicijalizacija na teminjata Vertex[] ver = new Vertex[V]; for(int i = 0; i<V; i++) ver[i] = new Vertex(); //input na rebrata for(int i = 0; i<E; i++){ int a = sc.nextInt(); int b = sc.nextInt(); int c = sc.nextInt(); ver[a].sosedi.put(b, c); if(!ver[b].sosedi.containsKey(a)) ver[b].sosedi.put(a, 0); } //input na start i finish int S = sc.nextInt(); int T = sc.nextInt(); //BFS int total = 0; boolean end; do{ HashMap<Integer, Integer> parentMap = new HashMap<>(); HashSet<Integer> visited = new HashSet<>(); Queue<Integer> q = new LinkedList<>(); q.add(S); visited.add(S); end = true; while(!q.isEmpty()){ int current = q.remove(); if(current == T){ int minimum = findmin(S, T, parentMap, ver); reducePaths(S, T, parentMap, ver, minimum); total += minimum; end = false; break; } for(Map.Entry<Integer, Integer> ss : ver[current].sosedi.entrySet()) { if(ss.getValue() <= 0) continue; int sosed = ss.getKey(); if(!visited.contains(sosed)){ visited.add(sosed); q.add(sosed); parentMap.put(sosed, current); } } } }while(!end); System.out.println(total); } }
/* * Copyright 2002-2021 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.core.codec; import java.util.Collections; import java.util.List; import java.util.Map; import org.reactivestreams.Publisher; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import org.springframework.core.ResolvableType; import org.springframework.core.io.buffer.DataBuffer; import org.springframework.core.io.buffer.DataBufferFactory; import org.springframework.lang.Nullable; import org.springframework.util.MimeType; /** * Strategy to encode a stream of Objects of type {@code <T>} into an output * stream of bytes. * * @author Sebastien Deleuze * @author Rossen Stoyanchev * @since 5.0 * @param <T> the type of elements in the input stream */ public interface Encoder<T> { /** * Whether the encoder supports the given source element type and the MIME * type for the output stream. * @param elementType the type of elements in the source stream * @param mimeType the MIME type for the output stream * (can be {@code null} if not specified) * @return {@code true} if supported, {@code false} otherwise */ boolean canEncode(ResolvableType elementType, @Nullable MimeType mimeType); /** * Encode a stream of Objects of type {@code T} into a {@link DataBuffer} * output stream. * @param inputStream the input stream of Objects to encode. If the input should be * encoded as a single value rather than as a stream of elements, an instance of * {@link Mono} should be used. * @param bufferFactory for creating output stream {@code DataBuffer}'s * @param elementType the expected type of elements in the input stream; * this type must have been previously passed to the {@link #canEncode} * method and it must have returned {@code true}. * @param mimeType the MIME type for the output content (optional) * @param hints additional information about how to encode * @return the output stream */ Flux<DataBuffer> encode(Publisher<? extends T> inputStream, DataBufferFactory bufferFactory, ResolvableType elementType, @Nullable MimeType mimeType, @Nullable Map<String, Object> hints); /** * Encode an Object of type T to a data buffer. This is useful for scenarios, * that distinct messages (or events) are encoded and handled individually, * in fully aggregated form. * <p>By default this method raises {@link UnsupportedOperationException} * and it is expected that some encoders cannot produce a single buffer or * cannot do so synchronously (e.g. encoding a {@code Resource}). * @param value the value to be encoded * @param bufferFactory for creating the output {@code DataBuffer} * @param valueType the type for the value being encoded * @param mimeType the MIME type for the output content (optional) * @param hints additional information about how to encode * @return the encoded content * @since 5.2 */ default DataBuffer encodeValue(T value, DataBufferFactory bufferFactory, ResolvableType valueType, @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) { // It may not be possible to produce a single DataBuffer synchronously throw new UnsupportedOperationException(); } /** * Return the list of MIME types supported by this Encoder. The list may not * apply to every possible target element type and calls to this method should * typically be guarded via {@link #canEncode(ResolvableType, MimeType) * canEncode(elementType, null)}. The list may also exclude MIME types * supported only for a specific element type. Alternatively, use * {@link #getEncodableMimeTypes(ResolvableType)} for a more precise list. * @return the list of supported MIME types */ List<MimeType> getEncodableMimeTypes(); /** * Return the list of MIME types supported by this Encoder for the given type * of element. This list may differ from the {@link #getEncodableMimeTypes()} * if the Encoder doesn't support the element type or if it supports it only * for a subset of MIME types. * @param elementType the type of element to check for encoding * @return the list of MIME types supported for the given element type * @since 5.3.4 */ default List<MimeType> getEncodableMimeTypes(ResolvableType elementType) { return (canEncode(elementType, null) ? getEncodableMimeTypes() : Collections.emptyList()); } }
package jianzhioffer; /** * @ClassName : Solution21 * @Description : 调整数组顺序使奇数位于偶数的前面 * @Date : 2019/9/16 13:09 */ public class Solution21 { //方法1:双指针法:这个无法保证相对顺序正确 public void reOrderArray(int [] array) { if (array==null || array.length==0) return; int left=0; int right=array.length-1; while (left<right){ while ((array[left]&1)==1 && left<right) left++; while ((array[right]&1)==0 && right>left) right--; if (left<right){ int tmp=array[left]; array[left]=array[right]; array[right]=tmp; } } } //方法2:冒泡法:这个能保证相对顺序,这个能通过牛客网测试 //从i=1开始遍历,如果是奇数,则向前找到偶数,找到一个换一个位置 public void reOrderArray2(int [] array) { if (array==null || array.length==0) return; for (int i=1;i<array.length;i++){ int tmp=array[i]; int j=i-1; if ((tmp&1)==1){ while (j>=0){ if ((array[j]&1)==1) { break; }else{ int t=array[j+1]; array[j+1]=array[j]; array[j]=t; j--; } } } array[j+1]=tmp; } } }
package com.greenenergycorp.dojo.tdd.hashtable; public class HashTable { private HashTableEntry[] table; public static void main(String[] args) {} public HashTableEntry[] getTable() { return table; } public void setTable(HashTableEntry[] table) { this.table = table; } public static void printTable(HashTable hashTable) { if (hashTable == null) { System.out.println("hashTable is null"); return; } HashTableEntry[] table = hashTable.getTable(); if (table.length == 0) { System.out.println("hashTable is empty"); return; } System.out.println("-------------------------"); for (int i = 0; i < table.length; i++) { System.out.println("i=" + i + ", " + table[i]); } return; } }
package com.zhicai.byteera.activity.traincamp.presenter; import android.text.TextUtils; import com.google.protobuf.InvalidProtocolBufferException; import com.zhicai.byteera.MyApp; import com.zhicai.byteera.activity.bean.DayTask; import com.zhicai.byteera.activity.traincamp.DailyTaskActivity; import com.zhicai.byteera.commonutil.LogUtil; import com.zhicai.byteera.service.serversdk.BaseHandlerClass; import com.zhicai.byteera.service.serversdk.TiangongClient; import com.zhicai.byteera.service.train_camp.AchieveReward; import java.util.ArrayList; import java.util.List; public class DayTaskPresenter { DailyTaskActivity activity; public DayTaskPresenter(DailyTaskActivity activity) { this.activity = activity; } public void getDailyTaskList() { AchieveReward.GetDailyTaskListReq req = null; if (!TextUtils.isEmpty(MyApp.getInstance().getUserId())) req = AchieveReward.GetDailyTaskListReq.newBuilder().setUserId(MyApp.getInstance().getUserId()).build(); else req = AchieveReward.GetDailyTaskListReq.newBuilder().build(); TiangongClient.instance().send("chronos", "get_daily_task_list", req.toByteArray(), new BaseHandlerClass() { @Override public void onSuccess(byte[] buffer) { try { final AchieveReward.GetDailyTaskListResponse res = AchieveReward.GetDailyTaskListResponse.parseFrom(buffer); LogUtil.d("dailyList : %s", res.toString()); MyApp.getMainThreadHandler().postAtFrontOfQueue(new Runnable() { @Override public void run() { List<DayTask> dayTasks = new ArrayList(); if (res.getErrorno() == 0) { for (AchieveReward.DailyTask tasks : res.getTasksList()) dayTasks.add(new DayTask(tasks.getId(),tasks.getAbbr(),tasks.getName(),tasks.getCoin(),tasks.getStatus().getNumber())); activity.setDialyList(dayTasks); activity.getDailyTask(new DayTask(res.getUserCoin(), res.getUserRank(), res.getConLogin())); } } }); } catch (InvalidProtocolBufferException e) { e.printStackTrace(); } } }); } public void taskRewardDoing(final String taskId){ AchieveReward.SetDailyTaskRewardReq req = AchieveReward.SetDailyTaskRewardReq.newBuilder().setUserId(MyApp.getInstance().getUserId()).setTaskId(taskId).build(); TiangongClient.instance().send("chronos", "set_daily_task_reward", req.toByteArray(), new BaseHandlerClass() { @Override public void onSuccess(byte[] buffer) { try { final AchieveReward.SetDailyTaskRewardResponse res = AchieveReward.SetDailyTaskRewardResponse.parseFrom(buffer); LogUtil.d("reward : %s", res.toString()); MyApp.getMainThreadHandler().postAtFrontOfQueue(new Runnable() { @Override public void run() { if (res.getErrorno() == 0) { activity.getDailyTask(new DayTask(res.getUserCoin(), res.getUserRank(), res.getConLogin())); getDailyTaskList(); } } }); } catch (InvalidProtocolBufferException e) { e.printStackTrace(); } } }); } }
package com.rd.monitoring.charts; import com.vaadin.annotations.JavaScript; @JavaScript({"jquery-min.js", "highcharts.js", "highcharts-connector.js"}) public class HighCharts extends AbstractHighCharts { private static final long serialVersionUID = -7326315426217377753L; }
package com.jstf.selenium; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.openqa.selenium.By; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.SearchContext; import org.openqa.selenium.WebElement; import org.openqa.selenium.internal.FindsByCssSelector; public abstract class JBy extends By{ /** * @param linkText The exact text to match against * @return a By which locates A elements by the exact text it displays */ public static By classContains(final String className) { if (className == null) throw new IllegalArgumentException( "Cannot find elements when className is null."); return new ByClassContains(className); } public static By ByTextEqualsIgnoreCase(By by, final String text) { if (text == null) throw new IllegalArgumentException( "Cannot find elements when text is null."); return new ByTextEqualsIgnoreCase(by, text); } public static class ByTextEqualsIgnoreCase extends By implements Serializable{ private static final long serialVersionUID = 1234567887654322L; private final String text; private final By by; public ByTextEqualsIgnoreCase(By by, String text) { this.by = by; this.text = text; } @Override public List<WebElement> findElements(SearchContext context) { List<WebElement> elements = new ArrayList<WebElement>(); for (WebElement webElement : context.findElements(by)) { if(webElement.getText().equalsIgnoreCase(text)) { elements.add(webElement); } } return elements; } @Override public WebElement findElement(SearchContext context) { List<WebElement> allElements = findElements(context); if (allElements == null || allElements.isEmpty()) throw new NoSuchElementException("Cannot locate an element using " + toString()); return allElements.get(0); } } public static By ByTextContainsIgnoreCase(By by, final String text) { if (text == null) throw new IllegalArgumentException( "Cannot find elements when text is null."); return new ByTextContainsIgnoreCase(by, text); } public static By ByTextContainsIgnoreCase(String cssSelector, final String text) { if (text == null) throw new IllegalArgumentException( "Cannot find elements when text is null."); return new ByTextContainsIgnoreCase(cssSelector, text); } public static class ByTextContainsIgnoreCase extends By implements Serializable{ private static final long serialVersionUID = 1234567887654312L; private final String text; private final By by; public ByTextContainsIgnoreCase(By by, String text) { this.by = by; this.text = text; } public ByTextContainsIgnoreCase(String cssSelector, String text) { this.by = By.cssSelector(cssSelector); this.text = text; } @Override public List<WebElement> findElements(SearchContext context) { List<WebElement> elements = new ArrayList<WebElement>(); for (WebElement webElement : context.findElements(by)) { if(StringUtils.containsIgnoreCase(webElement.getText(), text)) { elements.add(webElement); } } return elements; } @Override public WebElement findElement(SearchContext context) { List<WebElement> allElements = findElements(context); if (allElements == null || allElements.isEmpty()) throw new NoSuchElementException("Cannot locate an element using " + toString()); return allElements.get(0); } } public static class ByClassContains extends By implements Serializable{ private static final long serialVersionUID = 1234567887654321L; private final String className; public ByClassContains(String className) { this.className = className; } @Override public List<WebElement> findElements(SearchContext context) { return ((FindsByCssSelector) context).findElementsByCssSelector("*[class*='"+className+"']"); } @Override public WebElement findElement(SearchContext context) { return ((FindsByCssSelector) context).findElementByCssSelector("*[class*='"+className+"']"); } @Override public String toString() { return "By.classContains: " + className; } } }
package org.example; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; public class App { public static void main( String[] args ) throws ScriptException { //ExerciseGenerator exerciseGenerator = new ExerciseGenerator(); Operators operators = new Operators(); Numbers numbers = new Numbers(); ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("JavaScript"); String generatedExercise = (numbers.getGeneratedNumber()+" "+operators.getRandomOperator()+" "+numbers.getGeneratedNumber()); System.out.println(generatedExercise + " = " + engine.eval(generatedExercise)); //System.out.println(numbers.getGeneratedNumber() + " " + operators.getRandomOperator() + " " + numbers.getGeneratedNumber() + " = "); } }
package com.atguigu.lgl; import java.util.Date; import org.junit.Test; public class DateTest { @Test public void test2(){ java.sql.Date date = new java.sql.Date(1565968642295L); System.out.println(date.toString()); System.out.println(date.getTime()); //获取当前日期 java.sql.Date date2 = new java.sql.Date(new java.util.Date().getTime()); System.out.println(date2); } @Test public void test(){ //获取当前时间 java.util.Date date = new java.util.Date(); System.out.println(date.getTime());//秒差 1565968642295 System.out.println(date.toString());//Fri Aug 16 23:17:22 IRKT 2019 //获取毫秒数所对应的的时间 Date date2 = new java.util.Date( 1565968642295L); System.out.println(date2.toString()); } }
package com.davivienda.utilidades.archivoxls; import com.davivienda.utilidades.archivo.Archivo; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Collection; import org.apache.commons.io.IOUtils; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFClientAnchor; import org.apache.poi.hssf.usermodel.HSSFDataFormat; import org.apache.poi.hssf.usermodel.HSSFFont; import org.apache.poi.hssf.usermodel.HSSFPatriarch; import org.apache.poi.hssf.usermodel.HSSFPicture; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.util.HSSFColor; import org.apache.poi.hssf.util.Region; import org.apache.poi.ss.util.CellRangeAddress; /** * * @author p-cchapa 13/06/2011 */ public class ArchivoXLSDali40 extends Archivo { protected HSSFWorkbook libro; protected HSSFSheet hoja; protected String nombreHoja; protected Integer lineasTitulos = 0; protected Integer lineaTitulosFilas = 0; protected Integer lineaDatos = 0; protected Integer saltoColumna = 10; //protected Integer saltoColumna = 2; //protected Integer saltoColumna = 5; protected Integer saltoFila = 15; protected Integer saltoFila1 = this.saltoFila - 2; private HSSFRow lineaTituloColumna; private HSSFRow lineaTituloFila; protected HSSFCellStyle estiloTituloGrandeHoja; protected HSSFCellStyle estiloTituloHoja; protected HSSFCellStyle estiloTituloColumna; protected HSSFCellStyle estiloLineaNormal; protected HSSFCellStyle estiloCeldaDatoFecha; protected HSSFCellStyle estiloCeldaDatoNumerico; protected HSSFCellStyle estiloCeldaDatoMoneda; protected HSSFCellStyle estiloTituloHojaNormal; protected HSSFCellStyle estiloTituloHojaNormalCentrado; protected HSSFCellStyle estiloSubTituloNormal; protected HSSFCellStyle estiloSubTituloFirma; protected HSSFCellStyle estiloTituloSeccion; protected Collection<HSSFRow> lineas; //nuevo protected HSSFCellStyle estiloSubtituloTituloHoja; protected boolean encuentraGrafica; HSSFCellStyle estiloDatosSeccion; HSSFCellStyle estiloTituloFila; private HSSFCellStyle estiloDatoVacio; /** * Crea una nueva instancia de <code>ArchivoXLS</code>. */ public ArchivoXLSDali40() throws FileNotFoundException, IOException { this(null, null, "Hoja1"); } /** * Crea un objeto ArchivoXLS con el nombre del archivo asociado * * @param nombreArchivo */ public ArchivoXLSDali40(String nombreArchivo) throws FileNotFoundException, IOException { this(null, nombreArchivo, "Hoja1"); } /** * Crea un objeto ArchivoXLS con el nombre y directorio del archivo * asociados * * @param directorio * @param nombreArchivo * @param nombreHoja */ public ArchivoXLSDali40(String directorio, String nombreArchivo, String nombreHoja) throws FileNotFoundException, IOException { super(nombreArchivo, directorio); this.nombreHoja = nombreHoja; this.libro = new HSSFWorkbook(); this.hoja = libro.createSheet(this.nombreHoja); this.crearEstilos(); } public ArchivoXLSDali40(String directorio, String nombreArchivo, String nombreHoja, boolean blngraph, String dirLogo) throws FileNotFoundException, IOException { super(nombreArchivo, directorio); this.nombreHoja = nombreHoja; this.libro = new HSSFWorkbook(); this.hoja = libro.createSheet(this.nombreHoja); if (blngraph) { creargrafico(dirLogo); } this.crearEstilos(); } public void creargrafico(String dirLogo) throws IOException { InputStream is = null; try { encuentraGrafica = true; is = new FileInputStream(dirLogo); byte[] bytes = IOUtils.toByteArray(is); int pictureIdx = libro.addPicture(bytes, HSSFWorkbook.PICTURE_TYPE_JPEG); HSSFPatriarch drawing = hoja.createDrawingPatriarch(); HSSFClientAnchor anchor; anchor = new HSSFClientAnchor(0, 0, 1023, 255, (short) 0, 0, (short) 0, 0); HSSFPicture pict = drawing.createPicture(anchor, pictureIdx); pict.resize(); } catch (Exception ex) { encuentraGrafica = false; } finally { if (is != null) { is.close(); } } } @Override public void obtenerArchivo() throws IllegalArgumentException { super.obtenerArchivo(); try { super.getFileOutputStream(); } catch (FileNotFoundException ex) { throw new IllegalArgumentException(ex); } } public HSSFWorkbook getLibro() { return libro; } public void crearTitulosHoja(String titulosHoja, Integer lineaTitulo) { this.lineasTitulos = lineaTitulo; LineaXLSDali40 linea = new LineaXLSDali40(this, this.lineasTitulos, EstiloLineaXLS.TITULO_HOJA); Celda celda = new Celda((short) 0, (Object) titulosHoja, TipoDatoCelda.TITULO_HOJA); linea.asignarCelda(celda); this.lineasTitulos++; } public void crearTitulosHojaDali40(String[] titulosHoja) { this.lineasTitulos = 0; LineaXLSDali40 linea1 = new LineaXLSDali40(this, this.lineasTitulos, EstiloLineaXLS.TITULO_HOJA_NORMAL); Celda celda1 = new Celda((short) 0, (Object) titulosHoja[1], TipoDatoCelda.TITULO_COLUMNA); linea1.asignarCelda(celda1); // } public void crearTitulosFilasDali40(String[] titulosFila, Integer p) { crearEstilosBorde(); Integer lineasAdicionadas = this.lineaTitulosFilas; LineaXLSDali40 linea = null; Celda celda = null; this.saltoColumna = 0; for (String vString : titulosFila) { if (vString.equals("DETALLE EFECTIVO") || vString.equals("RESUMEN") || vString.equals("DETALLE CHEQUES")) { //this.hoja.addMergedRegion(new Region(this.lineaTitulosFilas, (short) (0 + (saltoColumna * p)), this.lineaTitulosFilas, (short) (4 + (saltoColumna * p)))); this.hoja.addMergedRegion(new CellRangeAddress(this.lineaTitulosFilas, this.lineaTitulosFilas, (short) (0 + (saltoColumna * p)), (short) (4 + (saltoColumna * p)))); linea = new LineaXLSDali40(this, this.lineaTitulosFilas, EstiloLineaXLS.TITULO_SECCION); celda = new Celda((short) (0 + (10 * p)), (Object) vString, TipoDatoCelda.TITULO_HOJA); linea.asignarCelda(celda); Celda cel = new Celda((short) (celda.columna + 1), "", TipoDatoCelda.DATO_VACIO); linea.asignarCelda(cel); Celda cel1 = new Celda((short) (celda.columna + 2), "", TipoDatoCelda.DATO_VACIO); linea.asignarCelda(cel1); Celda cel2 = new Celda((short) (celda.columna + 3), "", TipoDatoCelda.DATO_VACIO); linea.asignarCelda(cel2); Celda cel3 = new Celda((short) (celda.columna + 3), "", TipoDatoCelda.DATO_VACIO); linea.asignarCelda(cel3); Celda cel4 = new Celda((short) (celda.columna + 4), "", TipoDatoCelda.TITULO_HOJA); linea.asignarCelda(cel4); this.lineaTitulosFilas = this.lineaTitulosFilas + 2; } else { linea = new LineaXLSDali40(this, this.lineaTitulosFilas, EstiloLineaXLS.TITULO_FILA); celda = new Celda((short) (0 + (10 * p)), (Object) vString, TipoDatoCelda.TITULO_HOJA); linea.asignarCelda(celda); } if (vString.equals("CODIGO CAJERO")) { this.lineaTitulosFilas = this.lineaTitulosFilas + 3; } else if (vString.equals("DEPOSITO CHQ") || vString.equals("PAGOS TC CHQ") || vString.equals("PAGOS FM CHQ") || vString.equals("RECAUDOS CHQ")) { //this.hoja.addMergedRegion(new Region(this.lineaTitulosFilas, (short) (0 + (saltoColumna * p)), this.lineaTitulosFilas, (short) (1 + (saltoColumna * p)))); this.hoja.addMergedRegion(new CellRangeAddress(this.lineaTitulosFilas, this.lineaTitulosFilas, (short) (0 + (saltoColumna * p)), (short) (1 + (saltoColumna * p)))); Celda cel = new Celda((short) (celda.columna + 1), "", TipoDatoCelda.TITULO_HOJA); linea.asignarCelda(cel); this.lineaTitulosFilas++; // if(vString.equals("RECAUDOS CHQ")) // { // this.lineaTitulosFilas=this.lineaTitulosFilas+2; // } // else // { // this.lineaTitulosFilas++; // } //this.hoja.addMergedRegion(new Region(this.lineaTitulosFilas, (short) (0 + (saltoColumna * p)), this.lineaTitulosFilas, (short) (1 + (saltoColumna * p)))); this.hoja.addMergedRegion(new CellRangeAddress(this.lineaTitulosFilas, this.lineaTitulosFilas, (short) (0 + (saltoColumna * p)), (short) (1 + (saltoColumna * p)))); linea = new LineaXLSDali40(this, this.lineaTitulosFilas, EstiloLineaXLS.TITULO_FILA); Celda cel1 = new Celda((short) (0 + this.saltoColumna * p), "", TipoDatoCelda.TITULO_HOJA); linea.asignarCelda(cel1); Celda cel2 = new Celda((short) (1 + this.saltoColumna * p), "", TipoDatoCelda.TITULO_HOJA); linea.asignarCelda(cel2); // HLGomez: Se agregó "TOTALES" dentro del if. } else if (vString.equals("TOTALES") || vString.equals("DENOMINACION 50000") || vString.equals("CANTIDAD") || vString.equals("FALTANTES") || vString.equals("DENOMINACION 1000") || vString.equals("DENOMINACION 2000") || vString.equals("DENOMINACION 5000") || vString.equals("DENOMINACION 10000") || vString.equals("DENOMINACION 20000") || vString.equals("VALOR")) { this.lineaTitulosFilas++; // if (vString.equals("TOTALES")) // { // this.lineaTitulosFilas++; // } } else if (vString.equals("DEPOSITO EFE") || vString.equals("PAGOS TC EFE") || vString.equals("PAGOS FM EFE") || vString.equals("RECAUDOS EFE")) { //this.hoja.addMergedRegion(new Region(this.lineaTitulosFilas, (short) (0 + (saltoColumna * p)), this.lineaTitulosFilas, (short) (1 + (saltoColumna * p)))); this.hoja.addMergedRegion(new CellRangeAddress(this.lineaTitulosFilas, this.lineaTitulosFilas, (short) (0 + (saltoColumna * p)), (short) (1 + (saltoColumna * p)))); Celda cel = new Celda((short) (celda.columna + 1), "", TipoDatoCelda.TITULO_HOJA); linea.asignarCelda(cel); this.lineaTitulosFilas++; } else if (vString.equals("SOBRANTES")) { this.lineaTitulosFilas = this.lineaTitulosFilas + saltoFila1; } } // if (p == 0) { // this.lineaTitulosFilas = lineasAdicionadas; // } } public void crearTitulosColumnaDali40(String[] titulosColumna, boolean borde, Integer p) { if (borde) { crearEstilosBorde(); } Integer lineasAdicionadas = this.lineasTitulos; short numColumna = 1; LineaXLSDali40 linea = new LineaXLSDali40(this, ++this.lineasTitulos, EstiloLineaXLS.TITULO_COLUMNA); this.saltoColumna = 0; int posicion = 0; for (String vString : titulosColumna) { if (posicion == 0) { linea = new LineaXLSDali40(this, this.lineasTitulos, EstiloLineaXLS.TITULO_SECCION); Celda celda = new Celda((short) ((short) (0 + (saltoColumna * p))), (Object) vString, TipoDatoCelda.TITULO_HOJA); linea.asignarCelda(celda); //this.hoja.addMergedRegion(new Region(this.lineasTitulos, (short) (0 + (saltoColumna * p)), this.lineasTitulos, (short) (4 + (saltoColumna * p)))); CellRangeAddress cellAddress = new CellRangeAddress(this.lineasTitulos, this.lineasTitulos, (short) (0 + (saltoColumna * p)), (short) (4 + (saltoColumna * p))); this.hoja.addMergedRegion(cellAddress); Celda cel = new Celda((short) (celda.columna + 1), "", TipoDatoCelda.DATO_VACIO); linea.asignarCelda(cel); Celda cel1 = new Celda((short) (celda.columna + 2), "", TipoDatoCelda.DATO_VACIO); linea.asignarCelda(cel1); Celda cel2 = new Celda((short) (celda.columna + 3), "", TipoDatoCelda.DATO_VACIO); linea.asignarCelda(cel2); Celda cel3 = new Celda((short) (celda.columna + 3), "", TipoDatoCelda.DATO_VACIO); linea.asignarCelda(cel3); Celda cel4 = new Celda((short) (celda.columna + 4), "", TipoDatoCelda.TITULO_HOJA); linea.asignarCelda(cel4); numColumna++; this.lineasTitulos++; posicion++; } else if (posicion >= 1 && posicion < 4) { if (posicion == 1) { numColumna = 2; linea = new LineaXLSDali40(this, this.lineasTitulos, EstiloLineaXLS.TITULO_COLUMNA); } linea = new LineaXLSDali40(this, this.lineasTitulos, EstiloLineaXLS.TITULO_COLUMNA); Celda celda = new Celda((short) (numColumna + (saltoColumna * p)), (Object) vString, TipoDatoCelda.TITULO_COLUMNA); linea.asignarCelda(celda); numColumna++; posicion++; } else if (posicion >= 4 && posicion < 8) { if (posicion == 4) { this.lineasTitulos = this.lineasTitulos + 10; numColumna = 1; linea = new LineaXLSDali40(this, this.lineasTitulos, EstiloLineaXLS.TITULO_COLUMNA); } linea = new LineaXLSDali40(this, this.lineasTitulos, EstiloLineaXLS.TITULO_COLUMNA); Celda celda = new Celda((short) (numColumna + (saltoColumna * p)), (Object) vString, TipoDatoCelda.TITULO_COLUMNA); linea.asignarCelda(celda); numColumna++; posicion++; } else if (posicion >= 8 && posicion < 12) { if (posicion == 8) { this.lineasTitulos = this.lineasTitulos + 9; numColumna = 1; linea = new LineaXLSDali40(this, this.lineasTitulos, EstiloLineaXLS.TITULO_COLUMNA); } Celda celda = new Celda((short) (numColumna + (saltoColumna * p)), (Object) vString, TipoDatoCelda.TITULO_COLUMNA); linea.asignarCelda(celda); numColumna++; posicion++; } else if (posicion >= 12) { if (posicion == 12) { this.lineasTitulos = this.lineasTitulos + 4; numColumna = 1; linea = new LineaXLSDali40(this, this.lineasTitulos, EstiloLineaXLS.TITULO_COLUMNA); } Celda celda = new Celda((short) (numColumna + (this.saltoColumna * p)), (Object) vString, TipoDatoCelda.TITULO_COLUMNA); linea.asignarCelda(celda); numColumna++; posicion++; } if (posicion == 13) { this.lineasTitulos = this.lineasTitulos + this.saltoFila; } } // if (p == 0) { // this.lineasTitulos = lineasAdicionadas; // } } public void crearLineasNormalesDali40(Collection<Registro> lineas, boolean borde) { if (borde) { crearEstilosBorde(); } Boolean p = true; LineaXLSDali40 linea = null; Integer cont, aux = 0; this.saltoColumna = 0; for (Registro registro : lineas) { Integer lineasAdicionadas = this.lineaDatos; aux++; cont = 0; Collection<Celda> listaCeldas = registro.getCeldas(); for (Celda celda : listaCeldas) { if (aux % 2 == 0) { celda.columna = (short) (celda.columna + saltoColumna); } else if (celda.columna > 10) { celda.columna = (short) (celda.columna - saltoColumna); } if (cont == 1 || cont == 53 || cont == 61) { this.lineaDatos = this.lineaDatos + 3; } else if (cont == 4 || cont == 10 || cont == 49 || cont == 16 || cont == 22 || cont == 57 || cont == 63 || cont == 29 || cont == 33 || cont == 37 || cont == 41 || cont == 45) { this.lineaDatos++; } else if (cont == 7 || cont == 13 || cont == 19) { this.lineaDatos = this.lineaDatos + 1; } else if (cont == 25) { this.lineaDatos = this.lineaDatos + 3; } HSSFRow currentLine = this.libro.getSheet(this.nombreHoja).getRow(this.lineaDatos); if (cont == 0) { // //Region r1 = new Region(this.lineaDatos, celda.columna, this.lineaDatos, (short) (celda.columna + 3)); // CellRangeAddress r1 = new CellRangeAddress(this.lineaDatos, this.lineaDatos, celda.columna, (short) (celda.columna + 3)); // this.hoja.addMergedRegion(r1); // // Celda cel = new Celda((short) (celda.columna + 1), "", TipoDatoCelda.DATO_VACIO); // linea.asignarCelda(cel); // Celda cel1 = new Celda((short) (celda.columna + 2), "", TipoDatoCelda.DATO_VACIO); // linea.asignarCelda(cel1); // Celda cel2 = new Celda((short) (celda.columna + 3), "", TipoDatoCelda.DATO_VACIO); // linea.asignarCelda(cel2); CellRangeAddress r1 = new CellRangeAddress(this.lineaDatos, this.lineaDatos, celda.columna, (celda.columna + 3)); this.hoja.addMergedRegion(r1); } HSSFCell currentCell = currentLine.createCell(Integer.parseInt(celda.columna.toString())); LineaXLSDali40 currentXls = new LineaXLSDali40(); currentXls.archivo = this; currentXls.asignarEstiloCelda(currentCell, celda); currentXls.asignarValorCelda(currentCell, celda); if (cont == 0) { currentCell = currentLine.createCell(Integer.parseInt(celda.columna.toString()) + 1); currentXls = new LineaXLSDali40(); currentXls.archivo = this; currentXls.asignarEstiloCelda(currentCell, celda); currentCell = currentLine.createCell(Integer.parseInt(celda.columna.toString()) + 2); currentXls = new LineaXLSDali40(); currentXls.archivo = this; currentXls.asignarEstiloCelda(currentCell, celda); currentCell = currentLine.createCell(Integer.parseInt(celda.columna.toString()) + 3); currentXls = new LineaXLSDali40(); currentXls.archivo = this; currentXls.asignarEstiloCelda(currentCell, celda); } // linea.asignarCelda(celda); cont++; } if (cont == 65) { this.lineaDatos = this.lineaDatos + saltoFila1; } // if (p == true) { // this.lineaDatos = lineasAdicionadas; // } p = !p; } } public void grabarArchivo() throws IOException { this.hoja.setColumnWidth(0, 7000); this.hoja.setColumnWidth(1, 5000); this.hoja.setColumnWidth(2, 5000); this.hoja.setColumnWidth(3, 5000); this.hoja.setColumnWidth(4, 5000); this.hoja.setColumnWidth((0 + this.saltoColumna), 7000); this.hoja.setColumnWidth((1 + this.saltoColumna), 5000); this.hoja.setColumnWidth((2 + this.saltoColumna), 5000); this.hoja.setColumnWidth((3 + this.saltoColumna), 5000); this.hoja.setColumnWidth((4 + this.saltoColumna), 5000); libro.write(fos); } private void crearEstilos() { estiloCeldaDatoFecha = libro.createCellStyle(); estiloCeldaDatoFecha.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm")); estiloCeldaDatoMoneda = libro.createCellStyle(); estiloCeldaDatoMoneda.setDataFormat(HSSFDataFormat.getBuiltinFormat("($#,##0_);[Red]($#,##0)")); estiloCeldaDatoNumerico = libro.createCellStyle(); estiloCeldaDatoNumerico.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0")); HSSFFont fTituloHoja = libro.createFont(); fTituloHoja.setFontHeightInPoints((short) 14); fTituloHoja.setColor(HSSFFont.COLOR_RED); estiloTituloHoja = libro.createCellStyle(); estiloTituloHoja.setFont(fTituloHoja); HSSFFont fTituloHojaNormal = libro.createFont(); fTituloHojaNormal.setFontHeightInPoints((short) 14); fTituloHojaNormal.setColor(HSSFFont.COLOR_NORMAL); estiloTituloHojaNormal = libro.createCellStyle(); estiloTituloHojaNormal.setFont(fTituloHojaNormal); HSSFFont fTituloHojaNormalCentrado = libro.createFont(); fTituloHojaNormalCentrado.setFontHeightInPoints((short) 12); fTituloHojaNormalCentrado.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); fTituloHojaNormalCentrado.setColor(HSSFFont.COLOR_NORMAL); estiloTituloHojaNormalCentrado = libro.createCellStyle(); estiloTituloHojaNormalCentrado.setAlignment(HSSFCellStyle.ALIGN_CENTER); estiloTituloHojaNormalCentrado.setFont(fTituloHojaNormalCentrado); HSSFFont fTituloGrandeHoja = libro.createFont(); fTituloGrandeHoja.setFontHeightInPoints((short) 24); fTituloGrandeHoja.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); fTituloGrandeHoja.setColor(HSSFFont.COLOR_RED); estiloTituloGrandeHoja = libro.createCellStyle(); estiloTituloGrandeHoja.setFont(fTituloGrandeHoja); HSSFFont fTituloColumna = libro.createFont(); fTituloColumna.setFontHeightInPoints((short) 12); fTituloColumna.setColor(HSSFFont.COLOR_NORMAL); fTituloColumna.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); estiloTituloColumna = libro.createCellStyle(); estiloTituloColumna.setAlignment(HSSFCellStyle.ALIGN_CENTER); estiloTituloColumna.setFont(fTituloColumna); HSSFFont fnormal = libro.createFont(); fnormal.setFontHeightInPoints((short) 10); fnormal.setFontName(HSSFFont.FONT_ARIAL); estiloLineaNormal = libro.createCellStyle(); estiloLineaNormal.setFont(fnormal); //nuevo HSSFFont fSubTituloHoja = libro.createFont(); fSubTituloHoja.setFontHeightInPoints((short) 10); fSubTituloHoja.setColor(HSSFFont.COLOR_NORMAL); fSubTituloHoja.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); estiloSubtituloTituloHoja = libro.createCellStyle(); //estiloSubtituloTituloHoja.setAlignment(HSSFCellStyle.ALIGN_LEFT); estiloSubtituloTituloHoja.setFont(fSubTituloHoja); HSSFFont fSubTituloHojaNormal = libro.createFont(); fSubTituloHojaNormal.setFontHeightInPoints((short) 12); fSubTituloHojaNormal.setColor(HSSFFont.COLOR_NORMAL); estiloSubTituloNormal = libro.createCellStyle(); estiloSubTituloNormal.setFont(fSubTituloHojaNormal); HSSFFont fSubTituloFirma = libro.createFont(); fSubTituloFirma.setFontHeightInPoints((short) 11); fSubTituloFirma.setColor(HSSFFont.COLOR_NORMAL); fSubTituloFirma.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); estiloSubTituloFirma = libro.createCellStyle(); estiloSubTituloFirma.setFont(fSubTituloFirma); HSSFFont fTituloSeccion = libro.createFont(); fTituloSeccion.setFontHeightInPoints((short) 10); fTituloSeccion.setColor(HSSFFont.COLOR_NORMAL); fTituloSeccion.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); estiloTituloSeccion = libro.createCellStyle(); estiloTituloSeccion.setAlignment(HSSFCellStyle.ALIGN_CENTER); estiloTituloSeccion.setFont(fTituloSeccion); HSSFFont fDatoVacio = libro.createFont(); fDatoVacio.setFontHeightInPoints((short) 12); fDatoVacio.setColor(HSSFFont.COLOR_NORMAL); fDatoVacio.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); estiloDatoVacio = libro.createCellStyle(); estiloDatoVacio.setAlignment(HSSFCellStyle.ALIGN_CENTER); estiloDatoVacio.setFont(fDatoVacio); HSSFFont fTituloFila = libro.createFont(); fTituloFila.setFontHeightInPoints((short) 12); fTituloFila.setColor(HSSFFont.COLOR_NORMAL); fTituloFila.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); estiloTituloFila = libro.createCellStyle(); estiloTituloFila.setAlignment(HSSFCellStyle.ALIGN_CENTER); estiloTituloFila.setFont(fDatoVacio); } private void crearEstilosBorde() { estiloCeldaDatoFecha = libro.createCellStyle(); estiloCeldaDatoFecha.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm")); estiloCeldaDatoFecha.setAlignment(HSSFCellStyle.ALIGN_CENTER); estiloCeldaDatoFecha.setBorderBottom(HSSFCellStyle.BORDER_THIN); estiloCeldaDatoFecha.setBorderLeft(HSSFCellStyle.BORDER_THIN); estiloCeldaDatoFecha.setBorderRight(HSSFCellStyle.BORDER_THIN); estiloCeldaDatoFecha.setBorderTop(HSSFCellStyle.BORDER_THIN); estiloCeldaDatoMoneda = libro.createCellStyle(); estiloCeldaDatoMoneda.setDataFormat(HSSFDataFormat.getBuiltinFormat("($#,##0_);[Red]($#,##0)")); estiloCeldaDatoMoneda.setAlignment(HSSFCellStyle.ALIGN_CENTER); estiloCeldaDatoMoneda.setBorderBottom(HSSFCellStyle.BORDER_THIN); estiloCeldaDatoMoneda.setBorderLeft(HSSFCellStyle.BORDER_THIN); estiloCeldaDatoMoneda.setBorderRight(HSSFCellStyle.BORDER_THIN); estiloCeldaDatoMoneda.setBorderTop(HSSFCellStyle.BORDER_THIN); estiloCeldaDatoNumerico = libro.createCellStyle(); estiloCeldaDatoNumerico.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0")); estiloCeldaDatoNumerico.setAlignment(HSSFCellStyle.ALIGN_CENTER); estiloCeldaDatoNumerico.setBorderBottom(HSSFCellStyle.BORDER_THIN); estiloCeldaDatoNumerico.setBorderLeft(HSSFCellStyle.BORDER_THIN); estiloCeldaDatoNumerico.setBorderRight(HSSFCellStyle.BORDER_THIN); estiloCeldaDatoNumerico.setBorderTop(HSSFCellStyle.BORDER_THIN); HSSFFont fTituloHoja = libro.createFont(); fTituloHoja.setFontHeightInPoints((short) 10); fTituloHoja.setColor(HSSFFont.COLOR_RED); estiloTituloHoja = libro.createCellStyle(); estiloTituloHoja.setFont(fTituloHoja); HSSFFont fTituloHojaNormal = libro.createFont(); fTituloHojaNormal.setFontHeightInPoints((short) 14); fTituloHojaNormal.setColor(HSSFFont.COLOR_NORMAL); estiloTituloHojaNormal = libro.createCellStyle(); estiloTituloHojaNormal.setFont(fTituloHojaNormal); //estiloTituloHojaNormalCentrado HSSFFont fTituloHojaNormalCentrado = libro.createFont(); fTituloHojaNormalCentrado.setFontHeightInPoints((short) 12); fTituloHojaNormalCentrado.setColor(HSSFFont.COLOR_NORMAL); estiloTituloHojaNormalCentrado = libro.createCellStyle(); estiloTituloHojaNormalCentrado.setAlignment(HSSFCellStyle.ALIGN_CENTER); estiloTituloHojaNormalCentrado.setFont(fTituloHojaNormalCentrado); HSSFFont fTituloGrandeHoja = libro.createFont(); fTituloGrandeHoja.setFontHeightInPoints((short) 24); fTituloGrandeHoja.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); fTituloGrandeHoja.setColor(HSSFFont.COLOR_RED); estiloTituloGrandeHoja = libro.createCellStyle(); estiloTituloGrandeHoja.setFont(fTituloGrandeHoja); HSSFFont fTituloColumna = libro.createFont(); fTituloColumna.setFontHeightInPoints((short) 12); fTituloColumna.setColor(HSSFFont.COLOR_NORMAL); fTituloColumna.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); estiloTituloColumna = libro.createCellStyle(); estiloTituloColumna.setAlignment(HSSFCellStyle.ALIGN_CENTER); estiloTituloColumna.setBorderBottom(HSSFCellStyle.BORDER_THIN); estiloTituloColumna.setBorderLeft(HSSFCellStyle.BORDER_THIN); estiloTituloColumna.setBorderRight(HSSFCellStyle.BORDER_THIN); estiloTituloColumna.setBorderTop(HSSFCellStyle.BORDER_THIN); estiloTituloColumna.setFillBackgroundColor(HSSFColor.BRIGHT_GREEN.index); estiloTituloColumna.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index); estiloTituloColumna.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); estiloTituloColumna.setFont(fTituloColumna); HSSFFont fTituloSeccion = libro.createFont(); fTituloSeccion.setFontHeightInPoints((short) 10); fTituloSeccion.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); estiloTituloSeccion = libro.createCellStyle(); estiloTituloSeccion.setAlignment(HSSFCellStyle.ALIGN_CENTER); estiloTituloSeccion.setBorderBottom(HSSFCellStyle.BORDER_THIN); estiloTituloSeccion.setBorderLeft(HSSFCellStyle.BORDER_THIN); estiloTituloSeccion.setBorderRight(HSSFCellStyle.BORDER_THIN); estiloTituloSeccion.setBorderTop(HSSFCellStyle.BORDER_THIN); estiloTituloSeccion.setFont(fTituloSeccion); HSSFFont fDatoVacio = libro.createFont(); fDatoVacio.setFontHeightInPoints((short) 12); fDatoVacio.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); estiloDatoVacio = libro.createCellStyle(); estiloDatoVacio.setAlignment(HSSFCellStyle.ALIGN_CENTER); estiloDatoVacio.setBorderBottom(HSSFCellStyle.BORDER_MEDIUM); estiloDatoVacio.setBorderTop(HSSFCellStyle.BORDER_MEDIUM); estiloDatoVacio.setFont(fDatoVacio); HSSFFont fTituloFila = libro.createFont(); fTituloFila.setFontHeightInPoints((short) 10); fTituloFila.setColor(HSSFFont.COLOR_NORMAL); fTituloFila.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); estiloTituloFila = libro.createCellStyle(); estiloTituloFila.setAlignment(HSSFCellStyle.ALIGN_LEFT); estiloTituloFila.setBorderBottom(HSSFCellStyle.BORDER_THIN); estiloTituloFila.setBorderLeft(HSSFCellStyle.BORDER_THIN); estiloTituloFila.setBorderRight(HSSFCellStyle.BORDER_THIN); estiloTituloFila.setBorderTop(HSSFCellStyle.BORDER_THIN); estiloTituloFila.setFillBackgroundColor(HSSFColor.BRIGHT_GREEN.index); estiloTituloFila.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index); estiloTituloFila.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); estiloTituloFila.setFont(fDatoVacio); HSSFFont fnormal = libro.createFont(); fnormal.setFontHeightInPoints((short) 10); fnormal.setFontName(HSSFFont.FONT_ARIAL); estiloLineaNormal = libro.createCellStyle(); estiloLineaNormal.setAlignment(HSSFCellStyle.ALIGN_CENTER); estiloLineaNormal.setBorderBottom(HSSFCellStyle.BORDER_THIN); estiloLineaNormal.setBorderLeft(HSSFCellStyle.BORDER_THIN); estiloLineaNormal.setBorderRight(HSSFCellStyle.BORDER_THIN); estiloLineaNormal.setBorderTop(HSSFCellStyle.BORDER_THIN); estiloLineaNormal.setFont(fnormal); //nuevo HSSFFont fSubTituloHoja = libro.createFont(); fSubTituloHoja.setFontHeightInPoints((short) 12); fSubTituloHoja.setColor(HSSFFont.COLOR_NORMAL); fSubTituloHoja.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); estiloSubtituloTituloHoja = libro.createCellStyle(); //estiloSubtituloTituloHoja.setAlignment(HSSFCellStyle.ALIGN_LEFT); estiloSubtituloTituloHoja.setFont(fSubTituloHoja); // HSSFFont fSubTituloHojaNormal = libro.createFont(); // fSubTituloHojaNormal.setFontHeightInPoints((short) 12); // fSubTituloHojaNormal.setColor(HSSFFont.COLOR_NORMAL); // estiloSubTituloNormal = libro.createCellStyle(); // estiloSubTituloNormal.setFont(fSubTituloHojaNormal); // // HSSFFont fSubTituloFirma = libro.createFont(); // fSubTituloFirma.setFontHeightInPoints((short) 11); // fSubTituloFirma.setColor(HSSFFont.COLOR_NORMAL); // estiloSubTituloFirma = libro.createCellStyle(); // estiloSubTituloFirma.setFont(fSubTituloFirma); } }
package com.symetricum.brainsalad.adventofcode.day3; import com.symetricum.brainsalad.adventofcode.day1.ReportRepair; import java.util.ArrayList; import java.util.List; import java.util.Scanner; import java.util.concurrent.atomic.AtomicLong; import java.util.function.BiConsumer; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collector; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.LongStream; public class Toboggan2 { public static void main(String[] args) { Scanner scanner = new Scanner(ReportRepair.class.getClassLoader().getResourceAsStream("adventofcode/day3/data2.txt")); List<TreeCounter> counters = new ArrayList<>(); counters.add(new TreeCounter(1, 1)); counters.add(new TreeCounter(3, 1)); counters.add(new TreeCounter(5, 1)); counters.add(new TreeCounter(7, 1)); counters.add(new TreeCounter(1, 2)); while (scanner.hasNext()) { String line = scanner.next(); System.out.println(">> " + line); counters.forEach(c -> c.step(line)); } AtomicLong res = counters.stream().map(treeCounter -> treeCounter.count) .collect(() -> new AtomicLong(1), (a, b) -> a.set(a.get() * b), (a, b) -> {}); System.out.println("res = " + res.get()); } static class TreeCounter { int x = 0, y = 0; int stepX, stepY; public int count = 0; public TreeCounter(int stepX, int stepY) { this.stepX = stepX; this.stepY = stepY; } public void step(String str) { if (y != 0) { char c = str.charAt(x); // if (y % stepY == 0) System.out.println("[" + x + ", " + y + "] = " + c); if (y % stepY == 0 && c == '#') { count++; } } doStep(str.length()); } private void doStep(int length) { y = y + 1; if (y % stepY == 0) { x = x + stepX; x = x >= length ? x - length : x; } } } }
import java.util.ArrayList; import java.util.List; /** * FileManager class is the class that creates level details and items * by reading them from corresponding files */ public class FileManager { private LevelManager levelManager; //reference to level manager which creates FileManager //Constructor of FileManager - it takes reference to LevelManager public FileManager(LevelManager levelManager) { this.levelManager = levelManager; } //Instantiates level objects and details given the frameWidth and level number public void createLevelFromFile( int frameWidth, int levelId ){ if( levelId == 1){ levelManager.setLevelTimePeriod(30); levelManager.setLevelPointThreshold(50); levelManager.setCoinCoefficient(1); //Target Planes TargetPlane tp = new TargetPlane(TargetPlaneEnum.REPUBLIC_ATTACK.image(), TargetPlaneEnum.REPUBLIC_ATTACK.health(),frameWidth, 1400, 1, TargetPlaneEnum.REPUBLIC_ATTACK.shoot()); TargetPlane tp2 = new TargetPlane(TargetPlaneEnum.IMPERIAL_SHUTTLE.image(), TargetPlaneEnum.IMPERIAL_SHUTTLE.health(),frameWidth, 900, 8, TargetPlaneEnum.IMPERIAL_SHUTTLE.shoot()); TargetPlane tp3 = new TargetPlane(TargetPlaneEnum.F16.image(), TargetPlaneEnum.F16.health(), frameWidth, 780, 12, TargetPlaneEnum.F16.shoot()); TargetPlane tp4 = new TargetPlane(TargetPlaneEnum.REPUBLIC_ATTACK.image(), TargetPlaneEnum.REPUBLIC_ATTACK.health(),frameWidth, 1000, 21, TargetPlaneEnum.REPUBLIC_ATTACK.shoot()); List<TargetPlane> targetPlanes = new ArrayList<TargetPlane>(); targetPlanes.add(tp); targetPlanes.add(tp2); targetPlanes.add(tp3); targetPlanes.add(tp4); levelManager.setCreatedTargetPlanes(targetPlanes); //Targets Rocket rocket1 = new Rocket(RocketEnum.SMALL.damage(), RocketEnum.SMALL.damageArea(), 50, frameWidth, 200, 4); Rocket rocket2 = new Rocket(RocketEnum.LARGE.damage(), RocketEnum.LARGE.damageArea(), RocketEnum.LARGE.health(), frameWidth, 300, 20); List<Target> targets = new ArrayList<Target>(); targets.add(rocket1); targets.add(rocket2); Ally ally1 = new Ally(AllyEnum.ALDERAAN_CRUISER.image(), AllyEnum.ALDERAAN_CRUISER.health(), frameWidth, 230, 10); Ally ally2 = new Ally(AllyEnum.SAAB_GRIPEN.image(), AllyEnum.SAAB_GRIPEN.health(), frameWidth, 700, 21); targets.add(ally1); targets.add(ally2); Carriage carriage1 = new Carriage(CarriageEnum.SMALL.health(), frameWidth, 450, 5); Carriage carriage3 = new Carriage(CarriageEnum.LARGE.health(), frameWidth, 680, 18); Carriage carriage4 = new Carriage(CarriageEnum.LARGE.health(), frameWidth, 1300, 20); targets.add(carriage1); targets.add(carriage3); targets.add(carriage4); levelManager.setCreatedTargets(targets); HealthBonusPackage bp1 = new HealthBonusPackage(50, frameWidth, 1250, 10); List<BonusPackage> bonusPackages = new ArrayList<BonusPackage>(); bonusPackages.add(bp1); levelManager.setCreatedBonusPackages(bonusPackages); } else if( levelId == 2 ){ levelManager.setLevelTimePeriod(60); levelManager.setLevelPointThreshold(1000); levelManager.setCoinCoefficient(2); //Target Planes TargetPlane tp = new TargetPlane(TargetPlaneEnum.F16.image(), TargetPlaneEnum.F16.health(),frameWidth, 800, 0, TargetPlaneEnum.F16.shoot()); TargetPlane tp2 = new TargetPlane(TargetPlaneEnum.IMPERIAL_SHUTTLE.image(), TargetPlaneEnum.IMPERIAL_SHUTTLE.health(),frameWidth,500, 2, TargetPlaneEnum.IMPERIAL_SHUTTLE.shoot()); TargetPlane tp3 = new TargetPlane(TargetPlaneEnum.F16.image(), TargetPlaneEnum.F16.health(), frameWidth,1500,5, TargetPlaneEnum.F16.shoot()); TargetPlane tp4 = new TargetPlane(TargetPlaneEnum.REPUBLIC_ATTACK.image(), TargetPlaneEnum.REPUBLIC_ATTACK.health(),frameWidth,1000,15, TargetPlaneEnum.REPUBLIC_ATTACK.shoot()); TargetPlane tp5 = new TargetPlane(TargetPlaneEnum.HAVOC_MARAUDER.image(), TargetPlaneEnum.HAVOC_MARAUDER.health(),frameWidth,800,26, TargetPlaneEnum.HAVOC_MARAUDER.shoot()); TargetPlane tp6 = new TargetPlane(TargetPlaneEnum.F16.image(), TargetPlaneEnum.F16.health(), frameWidth, 1320, 37, TargetPlaneEnum.F16.shoot()); TargetPlane tp7 = new TargetPlane(TargetPlaneEnum.HAVOC_MARAUDER.image(), TargetPlaneEnum.HAVOC_MARAUDER.health(),frameWidth, 1270, 39, TargetPlaneEnum.HAVOC_MARAUDER.shoot()); TargetPlane tp8 = new TargetPlane(TargetPlaneEnum.BOSS.image(), TargetPlaneEnum.BOSS.health(),frameWidth, 520, 48, TargetPlaneEnum.BOSS.shoot()); List<TargetPlane> targetPlanes = new ArrayList<TargetPlane>(); targetPlanes.add(tp); targetPlanes.add(tp2); targetPlanes.add(tp3); targetPlanes.add(tp4); targetPlanes.add(tp5); targetPlanes.add(tp6); targetPlanes.add(tp7); targetPlanes.add(tp8); levelManager.setCreatedTargetPlanes(targetPlanes); //Targets Rocket rocket1 = new Rocket(RocketEnum.SMALL.damage(), RocketEnum.SMALL.damageArea(), 50, frameWidth, 200, 4); Rocket rocket2 = new Rocket(RocketEnum.SMALL.damage(), RocketEnum.SMALL.damageArea(), RocketEnum.SMALL.health(), frameWidth, 760, 20); Rocket rocket3 = new Rocket(RocketEnum.MEDIUM.damage(), RocketEnum.MEDIUM.damageArea(), RocketEnum.MEDIUM.health(), frameWidth, 200, 45); Rocket rocket4 = new Rocket(RocketEnum.MEDIUM.damage(), RocketEnum.MEDIUM.damageArea(), RocketEnum.MEDIUM.health(), frameWidth, 300, 60); List<Target> targets = new ArrayList<Target>(); targets.add(rocket1); targets.add(rocket2); targets.add(rocket3); targets.add(rocket4); Ally ally1 = new Ally(AllyEnum.ALDERAAN_CRUISER.image(), AllyEnum.ALDERAAN_CRUISER.health(), frameWidth, 500, 10); Ally ally2 = new Ally(AllyEnum.TOMCAT.image(), AllyEnum.TOMCAT.health(), frameWidth, 300, 21); Ally ally3 = new Ally(AllyEnum.TOMCAT.image(), AllyEnum.TOMCAT.health(), frameWidth, 240, 38); targets.add(ally1); targets.add(ally2); targets.add(ally3); Carriage carriage1 = new Carriage(CarriageEnum.SMALL.health(), frameWidth, 450, 5); Carriage carriage2 = new Carriage(CarriageEnum.MEDIUM.health(), frameWidth, 1430, 17); Carriage carriage3 = new Carriage(CarriageEnum.LARGE.health(), frameWidth, 680, 28); Carriage carriage4 = new Carriage(CarriageEnum.LARGE.health(), frameWidth, 300, 40); targets.add(carriage1); targets.add(carriage2); targets.add(carriage3); targets.add(carriage4); levelManager.setCreatedTargets(targets); Obstacle obs1 = new Obstacle( ImageConstants.cityObstacleImage2, frameWidth, 1400, 20); obs1.setScaledImage(300); List<Obstacle> obstacles = new ArrayList<Obstacle>(); obstacles.add(obs1); levelManager.setCreatedObstacles(obstacles); HealthBonusPackage bp1 = new HealthBonusPackage(50, frameWidth, 1250, 10); HealthBonusPackage bp2 = new HealthBonusPackage(80, frameWidth, 1000, 22); HealthTrapPackage bp3 = new HealthTrapPackage(50, frameWidth, 880, 30); HealthTrapPackage bp4 = new HealthTrapPackage(30, frameWidth, 540, 18); CoinPackage bp5 = new CoinPackage(10, frameWidth, 1000, 38); List<BonusPackage> bonusPackages = new ArrayList<BonusPackage>(); bonusPackages.add(bp1); bonusPackages.add(bp2); bonusPackages.add(bp3); bonusPackages.add(bp4); bonusPackages.add(bp5); levelManager.setCreatedBonusPackages(bonusPackages); } else if( levelId == 3 ){ levelManager.setLevelTimePeriod(20); levelManager.setLevelPointThreshold(10); levelManager.setCoinCoefficient(10); //Target Planes TargetPlane tp = new TargetPlane(TargetPlaneEnum.REPUBLIC_ATTACK.image(), TargetPlaneEnum.REPUBLIC_ATTACK.health(),frameWidth, 300, 1, TargetPlaneEnum.REPUBLIC_ATTACK.shoot()); TargetPlane tp2 = new TargetPlane(TargetPlaneEnum.IMPERIAL_SHUTTLE.image(), TargetPlaneEnum.IMPERIAL_SHUTTLE.health(),frameWidth, 1500, 8, TargetPlaneEnum.IMPERIAL_SHUTTLE.shoot()); List<TargetPlane> targetPlanes = new ArrayList<TargetPlane>(); targetPlanes.add(tp); targetPlanes.add(tp2); levelManager.setCreatedTargetPlanes(targetPlanes); //Targets Rocket rocket1 = new Rocket(RocketEnum.SMALL.damage(), RocketEnum.SMALL.damageArea(), 50, frameWidth, 850, 4); List<Target> targets = new ArrayList<Target>(); targets.add(rocket1); Ally ally1 = new Ally(AllyEnum.SAAB_GRIPEN.image(), AllyEnum.SAAB_GRIPEN.health(), frameWidth, 700, 11); targets.add(ally1); Carriage carriage1 = new Carriage(CarriageEnum.SMALL.health(), frameWidth, 1050, 0); Carriage carriage2 = new Carriage(CarriageEnum.LARGE.health(), frameWidth, 280, 8); Carriage carriage3 = new Carriage(CarriageEnum.LARGE.health(), frameWidth, 670, 13); targets.add(carriage1); targets.add(carriage2); targets.add(carriage3); levelManager.setCreatedTargets(targets); Obstacle obs1 = new Obstacle( ImageConstants.sandObstacleImage, frameWidth, 1300, 10); obs1.setScaledImage(500); List<Obstacle> obstacles = new ArrayList<Obstacle>(); obstacles.add(obs1); levelManager.setCreatedObstacles(obstacles); HealthBonusPackage bp1 = new HealthBonusPackage(50, frameWidth, 250, 10); List<BonusPackage> bonusPackages = new ArrayList<BonusPackage>(); bonusPackages.add(bp1); levelManager.setCreatedBonusPackages(bonusPackages); } else if( levelId == 4 ){ levelManager.setLevelTimePeriod(25); levelManager.setLevelPointThreshold(100); levelManager.setCoinCoefficient(50); TargetPlane tp1 = new TargetPlane(TargetPlaneEnum.REPUBLIC_ATTACK.image(), TargetPlaneEnum.REPUBLIC_ATTACK.health(),frameWidth, 690, 0, TargetPlaneEnum.REPUBLIC_ATTACK.shoot()); TargetPlane tp2 = new TargetPlane(TargetPlaneEnum.HAVOC_MARAUDER.image(), TargetPlaneEnum.HAVOC_MARAUDER.health(),frameWidth, 1400,12, TargetPlaneEnum.HAVOC_MARAUDER.shoot()); List<TargetPlane> targetPlanes = new ArrayList<TargetPlane>(); targetPlanes.add(tp1); targetPlanes.add(tp2); levelManager.setCreatedTargetPlanes(targetPlanes); //Targets Rocket rocket1 = new Rocket(RocketEnum.MEDIUM.damage(), RocketEnum.MEDIUM.damageArea(), RocketEnum.MEDIUM.health(), frameWidth, 200, 11); List<Target> targets = new ArrayList<Target>(); targets.add(rocket1); Carriage carriage1 = new Carriage(CarriageEnum.SMALL.health(), frameWidth, 450, 5); Carriage carriage2 = new Carriage(CarriageEnum.MEDIUM.health(), frameWidth, 1430, 9); targets.add(carriage1); targets.add(carriage2); levelManager.setCreatedTargets(targets); Obstacle obs1 = new Obstacle( ImageConstants.iceObstacleImage, frameWidth, 1000, 14); List<Obstacle> obstacles = new ArrayList<Obstacle>(); obstacles.add(obs1); levelManager.setCreatedObstacles(obstacles); HealthBonusPackage bp1 = new HealthBonusPackage(50, frameWidth, 250, 5); HealthTrapPackage bp2 = new HealthTrapPackage(50, frameWidth, 880, 10); List<BonusPackage> bonusPackages = new ArrayList<BonusPackage>(); bonusPackages.add(bp1); bonusPackages.add(bp2); levelManager.setCreatedBonusPackages(bonusPackages); } else if( levelId == 5 ){ levelManager.setLevelTimePeriod(60); levelManager.setLevelPointThreshold(1500); levelManager.setCoinCoefficient(50); TargetPlane tp = new TargetPlane(TargetPlaneEnum.F16.image(), TargetPlaneEnum.F16.health(),frameWidth, 800, 0, TargetPlaneEnum.F16.shoot()); TargetPlane tp2 = new TargetPlane(TargetPlaneEnum.IMPERIAL_SHUTTLE.image(), TargetPlaneEnum.IMPERIAL_SHUTTLE.health(),frameWidth,500, 2, TargetPlaneEnum.IMPERIAL_SHUTTLE.shoot()); TargetPlane tp3 = new TargetPlane(TargetPlaneEnum.F16.image(), TargetPlaneEnum.F16.health(), frameWidth,1500,5, TargetPlaneEnum.F16.shoot()); TargetPlane tp4 = new TargetPlane(TargetPlaneEnum.REPUBLIC_ATTACK.image(), TargetPlaneEnum.REPUBLIC_ATTACK.health(),frameWidth,1000,15, TargetPlaneEnum.REPUBLIC_ATTACK.shoot()); TargetPlane tp5 = new TargetPlane(TargetPlaneEnum.HAVOC_MARAUDER.image(), TargetPlaneEnum.HAVOC_MARAUDER.health(),frameWidth,800,26, TargetPlaneEnum.HAVOC_MARAUDER.shoot()); TargetPlane tp6 = new TargetPlane(TargetPlaneEnum.F16.image(), TargetPlaneEnum.F16.health(), frameWidth, 1320, 37, TargetPlaneEnum.F16.shoot()); TargetPlane tp7 = new TargetPlane(TargetPlaneEnum.BOSS.image(), TargetPlaneEnum.BOSS.health(), frameWidth , 500, 50, TargetPlaneEnum.BOSS.shoot()); tp7.setScaledImage(500); List<TargetPlane> targetPlanes = new ArrayList<TargetPlane>(); targetPlanes.add(tp); targetPlanes.add(tp2); targetPlanes.add(tp3); targetPlanes.add(tp4); targetPlanes.add(tp5); targetPlanes.add(tp6); targetPlanes.add(tp7); levelManager.setCreatedTargetPlanes(targetPlanes); //Targets Rocket rocket1 = new Rocket(RocketEnum.SMALL.damage(), RocketEnum.SMALL.damageArea(), 50, frameWidth, 200, 4); Rocket rocket2 = new Rocket(RocketEnum.SMALL.damage(), RocketEnum.SMALL.damageArea(), RocketEnum.SMALL.health(), frameWidth, 760, 18); Rocket rocket3 = new Rocket(RocketEnum.MEDIUM.damage(), RocketEnum.MEDIUM.damageArea(), RocketEnum.MEDIUM.health(), frameWidth, 200, 30); Rocket rocket4 = new Rocket(RocketEnum.MEDIUM.damage(), RocketEnum.MEDIUM.damageArea(), RocketEnum.MEDIUM.health(), frameWidth, 1000, 45); List<Target> targets = new ArrayList<Target>(); targets.add(rocket1); targets.add(rocket2); targets.add(rocket3); targets.add(rocket4); Ally ally2 = new Ally(AllyEnum.WUNDERWAFFE.image(), AllyEnum.WUNDERWAFFE.health(), frameWidth, 1500, 35); Ally ally3 = new Ally(AllyEnum.TOMCAT.image(), AllyEnum.TOMCAT.health(), frameWidth, 240, 50); targets.add(ally2); targets.add(ally3); Carriage carriage1 = new Carriage(CarriageEnum.SMALL.health(), frameWidth,670, 5); Carriage carriage2 = new Carriage(CarriageEnum.MEDIUM.health(), frameWidth, 200, 17); Carriage carriage3 = new Carriage(CarriageEnum.LARGE.health(), frameWidth, 1290, 28); Carriage carriage4 = new Carriage(CarriageEnum.LARGE.health(), frameWidth, 300, 40); targets.add(carriage1); targets.add(carriage2); targets.add(carriage3); targets.add(carriage4); levelManager.setCreatedTargets(targets); Obstacle obs1 = new Obstacle( ImageConstants.fieldObstacleImage, frameWidth, 800, 20); List<Obstacle> obstacles = new ArrayList<Obstacle>(); obstacles.add(obs1); levelManager.setCreatedObstacles(obstacles); HealthBonusPackage bp1 = new HealthBonusPackage(50, frameWidth, 250, 10); HealthBonusPackage bp2 = new HealthBonusPackage(80, frameWidth, 400, 22); HealthTrapPackage bp3 = new HealthTrapPackage(50, frameWidth, 880, 30); HealthTrapPackage bp4 = new HealthTrapPackage(30, frameWidth, 540, 18); CoinPackage bp5 = new CoinPackage(10, frameWidth, 740, 38); List<BonusPackage> bonusPackages = new ArrayList<BonusPackage>(); bonusPackages.add(bp1); bonusPackages.add(bp2); bonusPackages.add(bp3); bonusPackages.add(bp4); bonusPackages.add(bp5); levelManager.setCreatedBonusPackages(bonusPackages); } } }
package jsonparsing; import java.io.File; import java.io.IOException; import java.util.Scanner; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonNode; import pojo.QuizPOJO; import pojo.QuestionPOJO; @SuppressWarnings("unused") class QuizCommandLine { public static void main(String[] args) throws IllegalArgumentException, IOException { // Creation of objects needed to excecute the program Scanner scnr = new Scanner(System.in); System.out.println("Please paste the absolute path to your JSON Quiz!"); String filePath = scnr.nextLine(); File quizFile = new File(filePath); JsonNode node = Json.parseFile(quizFile); QuizPOJO pojo = Json.fromJson(node, QuizPOJO.class); char userChoice = 0; int numQuestions = 0; int numCorrect = 0; double percentage = 0; // Initial heading upon program start System.out.println("Program: " + pojo.getProgramName()); System.out.println("Author: " + pojo.getAuthorName()); System.out.println("Date Published: " + pojo.getDatePublished()); System.out.println("---------------------------------------------------------------------------------------------------------------------------------------\n"); // Enhanced for loop that loops through every question in the file specified for(QuestionPOJO question:pojo.getQuestions()) { System.out.println("Question: " + question.getQuestion()); if(question.getAnswer1() != null) { System.out.println("A: " + question.getAnswer1()); } if(question.getAnswer2() != null) { System.out.println("B: " + question.getAnswer2()); } if(question.getAnswer3() != null) { System.out.println("C: " + question.getAnswer3()); } if(question.getAnswer4() != null) { System.out.println("D: " + question.getAnswer4()); } // Get the user answer as a single character. // Only a/A b/B c/C or d/D are valid System.out.print("Enter your answer: "); userChoice = scnr.next().charAt(0); System.out.println(); if(Character.toUpperCase(userChoice) == question.getCorrect().charAt(0)) { System.out.println("CORRECT! Answer is: " + question.getCorrect()); } else{ System.out.println("WRONG! Answer is: " + question.getCorrect()); } System.out.println("\n"); userChoice = 0; } percentage = ( (double)numCorrect / (double)numQuestions ) * 100.00; System.out.printf("Quiz over. You Scored %d/%d OR %.2f%%", numCorrect, numQuestions, percentage); scnr.close(); }//end main }//end class
package behaviour; public class ActionController { private static final ActionController INSTANCE = new ActionController();; public static ActionController getInstance(){ return INSTANCE; } String proximo = "Mage"; public boolean getActionTurn(String agentName){ try { Thread.sleep(5000); if(agentName.equals("Mage")){ proximo = "Ranger"; return true; } if(agentName.equals("Ranger")){ proximo = "Warrior"; return true; } if(agentName.equals("Warrior")){ proximo = "Mage"; return true; } if(agentName.equals("Boss")){ proximo = "Mage"; return true; } } catch (InterruptedException ex) { System.out.println(ex); } return true; } }
package fr.cea.nabla.interpreter.utils; import com.oracle.truffle.api.CompilerDirectives; import com.oracle.truffle.api.CompilerDirectives.CompilationFinal; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.frame.Frame; import com.oracle.truffle.api.frame.FrameDescriptor; import com.oracle.truffle.api.frame.VirtualFrame; import com.oracle.truffle.api.nodes.ExplodeLoop; import com.oracle.truffle.api.nodes.Node; import fr.cea.nabla.interpreter.runtime.NablaInitializationPerformedException; public abstract class GetFrameNode extends Node { @CompilationFinal protected int depth = 0; private final String slotName; public GetFrameNode(String name) { this.slotName = name; } public abstract Frame execute(VirtualFrame frame); @Specialization(rewriteOn = NablaInitializationPerformedException.class) protected Frame initialize(VirtualFrame frame) throws NablaInitializationPerformedException { CompilerDirectives.transferToInterpreterAndInvalidate(); final FrameDescriptor descriptor = frame.getFrameDescriptor(); if (descriptor.findFrameSlot(slotName) == null) { Frame theFrame = frame; while (theFrame.getArguments().length != 0) { theFrame = (Frame) theFrame.getArguments()[0]; depth++; } } throw new NablaInitializationPerformedException(); } @ExplodeLoop @Specialization protected Frame doCached(VirtualFrame frame) { Frame theFrame = frame; for (int i = 0; i < depth; i++) { theFrame = (Frame) theFrame.getArguments()[0]; } return theFrame; } }
package com.console.webservice.WSClient; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.XmlElementDecl; import javax.xml.bind.annotation.XmlRegistry; import javax.xml.namespace.QName; /** * This object contains factory methods for each * Java content interface and Java element interface * generated in the com.console.webservice.WSClient package. * <p>An ObjectFactory allows you to programatically * construct new instances of the Java representation * for XML content. The Java representation of XML * content can consist of schema derived interfaces * and classes representing the binding of schema * type definitions, element declarations and model * groups. Factory methods for each of these are * provided in this class. * */ @XmlRegistry public class ObjectFactory { private final static QName _Salute_QNAME = new QName("http://webservice.console.com/", "salute"); private final static QName _SaluteResponse_QNAME = new QName("http://webservice.console.com/", "saluteResponse"); /** * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: com.console.webservice.WSClient * */ public ObjectFactory() { } /** * Create an instance of {@link SaluteResponse } * */ public SaluteResponse createSaluteResponse() { return new SaluteResponse(); } /** * Create an instance of {@link Salute } * */ public Salute createSalute() { return new Salute(); } /** * Create an instance of {@link JAXBElement }{@code <}{@link Salute }{@code >}} * */ @XmlElementDecl(namespace = "http://webservice.console.com/", name = "salute") public JAXBElement<Salute> createSalute(Salute value) { return new JAXBElement<Salute>(_Salute_QNAME, Salute.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link SaluteResponse }{@code >}} * */ @XmlElementDecl(namespace = "http://webservice.console.com/", name = "saluteResponse") public JAXBElement<SaluteResponse> createSaluteResponse(SaluteResponse value) { return new JAXBElement<SaluteResponse>(_SaluteResponse_QNAME, SaluteResponse.class, null, value); } }
package 배열; import java.util.Arrays; import java.util.Random; import java.util.Scanner; // 10개의 성적 입력을 랜덤하게 받고, 총합/평균 출력 public class 랜덤생성총점평균 { public static void main(String[] args) { Random r = new Random(); int[] grades = new int[11]; for (int i = 0; i <grades.length; i++) { grades[i] = r.nextInt(101); } System.out.println("##랜덤으로 생성된 점수들은 다음과 같습니다##"); System.out.println(Arrays.toString(grades)); int total = 0; for (int i = 0; i < grades.length; i++) { total = total + grades[i]; } System.out.println("총점 : " + total); double avg = (double)total / grades.length; avg = (double)Math.round(avg * 100) / 100; //Math.round 소숫점둘째자리까지출력 System.out.println("평균 : " + avg); } }
package br.com.icaro.chat.controller; import java.util.List; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; import org.ocpsoft.rewrite.annotation.Join; import org.ocpsoft.rewrite.el.ELBeanName; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import br.com.icaro.chat.config.MessageMode; import br.com.icaro.chat.dto.Message; import br.com.icaro.chat.model.ChatUser; import br.com.icaro.chat.model.RestrictWord; import br.com.icaro.chat.service.ChatUserService; import br.com.icaro.chat.service.RestrictWordService; import br.com.icaro.chat.service.WebSocketService; @Scope ("view") @Component (value = "chatController") @ELBeanName(value = "chatController") @Join(path = "/chat", to = "/principal/chat.jsf") public class ChatController { private List<ChatUser> users; private String message; private String privateMessage; @Autowired ChatUserService userService; @Autowired RestrictWordService restrictWordService; @Autowired LoginController loginController; ChatUser toUser; @Autowired WebSocketService wsService; public String sendMessage() throws Exception { String [] wordsFromText = message.split(" "); if (badWordsValidation(wordsFromText)) { Message chatMessage = new Message(null, loginController.getUser(), message, MessageMode.PUBLIC); wsService.send("/topic/chat", chatMessage); } message = ""; return message; } public String sendPrivate() throws Exception { String [] wordsFromText = privateMessage.split(" "); if (badWordsValidation(wordsFromText)) { Message chatMessage = new Message(toUser, loginController.getUser(), privateMessage, MessageMode.PRIVATE); wsService.send(toUser.getEmail(),"/queue/chat", chatMessage); wsService.send(loginController.getUser().getEmail(),"/queue/chat", chatMessage); toUser = new ChatUser(); } privateMessage = ""; return privateMessage; } private Boolean badWordsValidation(String [] wordsFromText ) { List<RestrictWord> restrictWords = restrictWordService.findAll(); Boolean thatsOk = true; if (!restrictWords.isEmpty()) for (int i = 0; i < wordsFromText.length;i++) { String wordFromText = wordsFromText[i]; if (restrictWords.stream().filter(word-> word.getWord().equalsIgnoreCase(wordFromText)).count() > 0) { thatsOk = false; FacesContext context = FacesContext.getCurrentInstance(); context.addMessage(null, new FacesMessage( FacesMessage.SEVERITY_ERROR, "Erro", "Não são permitidas palavras de baixo calão.")); break; } } return thatsOk; } public List<ChatUser> refreshUsers() { return getUsers(); } private List<ChatUser> findAllUsers() { return userService.findAll(); } public List<ChatUser> getUsers() { setUsers(findAllUsers()); return users; } public void setUsers(List<ChatUser> users) { this.users = users; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public ChatUser getToUser() { return toUser; } public void setToUser(ChatUser toUser) { this.toUser = toUser; } public String getPrivateMessage() { return privateMessage; } public void setPrivateMessage(String privateMessage) { this.privateMessage = privateMessage; } }
package com.beadhouse.service; import com.beadhouse.in.CollectionParam; import com.beadhouse.out.BasicData; public interface CollectionService { /** * 用户收藏消息 */ BasicData collection(CollectionParam param); /** * 删除收藏消息 */ BasicData delcollection(CollectionParam param); /** * 老人收藏消息 */ BasicData eldercollection(CollectionParam param); /** * 删除老人收藏消息 */ BasicData deleldercollection(CollectionParam param); }
package com.amundi.tech.onsite.rest; import com.amundi.tech.onsite.db.WorkingDayRepository; import com.amundi.tech.onsite.db.model.ParkingDefinition; import com.amundi.tech.onsite.db.model.RestaurantDefinition; import com.amundi.tech.onsite.db.model.SiteDefinition; import com.amundi.tech.onsite.db.model.WorkingDay; import com.amundi.tech.onsite.model.UserDay; import com.amundi.tech.onsite.model.UserDays; import com.amundi.tech.onsite.model.mapper.WorkingDayMapper; import io.swagger.v3.oas.annotations.tags.Tag; import lombok.AllArgsConstructor; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*; import org.springframework.web.server.ResponseStatusException; import java.time.LocalDate; import java.util.List; import java.util.stream.Collectors; import static com.amundi.tech.onsite.exception.AppException.*; @RestController @RequestMapping("/api/day") @AllArgsConstructor @Tag(name = "day", description = "user defined working days") public class UserDayResource { private final WorkingDayMapper workingDayMapper; private final WorkingDayRepository workingDayRepository; @GetMapping(path = "/all", produces = MediaType.APPLICATION_JSON_VALUE) public List<UserDay> all() { return workingDayRepository.findAll() .stream() .map(workingDayMapper::convert) .collect(Collectors.toList()); } @GetMapping(path = "/site/{id}", produces = MediaType.APPLICATION_JSON_VALUE) public List<UserDay> site(@PathVariable("id") Long siteId, @RequestParam(value = "startDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate ) { LocalDate date = startDate != null ? startDate.minusDays(1) : LocalDate.now().minusDays(1); return workingDayRepository.findAllBySiteAndDateAfter(SiteDefinition.builder().id(siteId).build(), date) .stream() .map(workingDayMapper::convert) .collect(Collectors.toList()); } @GetMapping(path = "/restaurant/{id}", produces = MediaType.APPLICATION_JSON_VALUE) public List<UserDay> restaurant(@PathVariable("id") Long restaurantId, @RequestParam(value = "startDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate ) { LocalDate date = startDate != null ? startDate.minusDays(1) : LocalDate.now().minusDays(1); return workingDayRepository.findAllByRestaurantAndDateAfter(RestaurantDefinition.builder().id(restaurantId).build(), date) .stream() .map(workingDayMapper::convert) .collect(Collectors.toList()); } @GetMapping(path = "/parking/{id}", produces = MediaType.APPLICATION_JSON_VALUE) public List<UserDay> parking(@PathVariable("id") Long parkingId, @RequestParam(value = "startDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate ) { LocalDate date = startDate != null ? startDate.minusDays(1) : LocalDate.now().minusDays(1); return workingDayRepository.findAllByParkingAndDateAfter(ParkingDefinition.builder().id(parkingId).build(), date) .stream() .map(workingDayMapper::convert) .collect(Collectors.toList()); } @GetMapping(path = "/user/{id}", produces = MediaType.APPLICATION_JSON_VALUE) public List<UserDay> user(@PathVariable("id") String user, @RequestParam(value = "startDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate ) { LocalDate date = startDate != null ? startDate.minusDays(1) : LocalDate.now().minusDays(1); List<UserDay> userDays = workingDayRepository.findAllByUserAndDateAfter(user, date) .stream() .map(workingDayMapper::convert) .collect(Collectors.toList()); return userDays; } @PostMapping(path = "", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) public UserDays update(@RequestBody UserDays userDays) { if (userDays == null) { throw new ResponseStatusException(HttpStatus.NOT_ACCEPTABLE, EMPTY_PARAM); } if (userDays.getUser() == null) { throw new ResponseStatusException(HttpStatus.NOT_ACCEPTABLE, EMPTY_USER); } for (UserDay userDay : userDays.getUserDays()) { workingDayRepository.deleteAllByUserAndAndDateEquals(userDay.getUser(), userDay.getDate()); workingDayRepository.save(workingDayMapper.convert(userDay)); } List<WorkingDay> wds = userDays.getStartDate() != null ? workingDayRepository.findAllByUserAndDateAfter(userDays.getUser(), userDays.getStartDate()) : workingDayRepository.findAllByUser(userDays.getUser()); List<UserDay> ud = wds.stream().map(workingDayMapper::convert).collect(Collectors.toList()); return UserDays.builder() .user(userDays.getUser()) .userDays(ud) .build(); } @PostMapping(path = "/delete", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) public UserDays delete(@RequestBody UserDays userDays) { if (userDays == null) { throw new ResponseStatusException(HttpStatus.NOT_ACCEPTABLE, EMPTY_PARAM); } if (userDays.getUser() == null) { throw new ResponseStatusException(HttpStatus.NOT_ACCEPTABLE, EMPTY_USER); } for (UserDay userDay : userDays.getUserDays()) { workingDayRepository.deleteAllByUserAndAndDateEquals(userDay.getUser(), userDay.getDate()); } List<WorkingDay> wds = userDays.getStartDate() != null ? workingDayRepository.findAllByUserAndDateAfter(userDays.getUser(), userDays.getStartDate()) : workingDayRepository.findAllByUser(userDays.getUser()); List<UserDay> ud = wds.stream().map(workingDayMapper::convert).collect(Collectors.toList()); return UserDays.builder() .user(userDays.getUser()) .userDays(ud) .build(); } }
package org.andrill.conop.core; /** * Thrown when a simulation has been halted. * * @author Josh Reed (jareed@andrill.org) */ public class HaltedException extends RuntimeException { private static final long serialVersionUID = 1L; protected final Solution solution; public HaltedException(final String message) { super(message); solution = null; } public HaltedException(final String message, final Solution solution) { super(message); this.solution = solution; } public Solution getSolution() { return solution; } }
package shoppingpad.com.recycler; import android.animation.Animator; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.animation.PropertyValuesHolder; import android.support.v7.widget.RecyclerView; import android.view.View; import android.view.animation.AnticipateInterpolator; import android.view.animation.DecelerateInterpolator; /** * Created by bridgelabz5 on 1/2/16. */ public class AnimationUtils { // private static int counter = 0; // public static void scaleXY(RecyclerView.ViewHolder holder) { // holder.itemView.setScaleX(0); // holder.itemView.setScaleY(0); // // PropertyValuesHolder propx = PropertyValuesHolder.ofFloat("scaleX", 1); // PropertyValuesHolder propy = PropertyValuesHolder.ofFloat("scaleY", 1); // // ObjectAnimator animator = ObjectAnimator.ofPropertyValuesHolder(holder.itemView, propx, propy); // // // animator.setDuration(800); // animator.start(); // } public static void animate(RecyclerView.ViewHolder holder,boolean goesDown) { AnimatorSet animatorSet = new AnimatorSet(); /* ObjectAnimator animatorTranslateY = ObjectAnimator.ofFloat(holder.itemView,"translationY",goesDown==true ?300:-300,0); animatorTranslateY.setDuration(1000); animatorTranslateY.start();*/ ObjectAnimator animatorScaleX = ObjectAnimator.ofFloat(holder.itemView, "scaleX" ,0.5F, 0.8F, 1.0F); ObjectAnimator animatorScaleY = ObjectAnimator.ofFloat(holder.itemView, "scaleY", 0.5F, 0.8F, 1.0F); ObjectAnimator animatorTranslateY = ObjectAnimator.ofFloat(holder.itemView, "translationY", goesDown == true ? 300 : -300, 0); ObjectAnimator animatorTranslateX = ObjectAnimator.ofFloat(holder.itemView, "translationX", -50, 50, -30, 30, -20, 20, -5, 5, 0); animatorSet.playTogether(animatorTranslateX, animatorTranslateY, animatorScaleX, animatorScaleY); animatorSet.setInterpolator(new AnticipateInterpolator()); animatorSet.setDuration(1000); animatorSet.start(); } public static void animateToolbarDroppingDown(View containerToolbar) { containerToolbar.setRotationX(-90); containerToolbar.setAlpha(0.2F); containerToolbar.setPivotX(0.0F); containerToolbar.setPivotY(0.0F); Animator alpha = ObjectAnimator.ofFloat(containerToolbar, "alpha", 0.2F, 0.4F, 0.6F, 0.8F, 1.0F).setDuration(2000); Animator rotationX = ObjectAnimator.ofFloat(containerToolbar, "rotationX", -90, 60, -45, 45, -10, 30, 0, 20, 0, 5, 0).setDuration(2500); AnimatorSet animatorSet = new AnimatorSet(); animatorSet.setInterpolator(new AnticipateInterpolator()); animatorSet.playTogether(alpha, rotationX); animatorSet.start(); } }
package com.services.myapp; public class Item { String Email,Date,Phone,Constituency,kitambulisho,Jina; public Item(String email, String date, String phone, String constituency, String kitambulisho, String jina) { Email = email; Date = date; Phone = phone; Constituency = constituency; this.kitambulisho = kitambulisho; Jina = jina; } public Item() { } public String getEmail() { return Email; } public void setEmail(String email) { Email = email; } public String getDate() { return Date; } public void setDate(String date) { Date = date; } public String getPhone() { return Phone; } public void setPhone(String phone) { Phone = phone; } public String getConstituency() { return Constituency; } public void setConstituency(String constituency) { Constituency = constituency; } public String getKitambulisho() { return kitambulisho; } public void setKitambulisho(String kitambulisho) { this.kitambulisho = kitambulisho; } public String getJina() { return Jina; } public void setJina(String jina) { Jina = jina; } }
package com.example.admin.mvp; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.example.admin.mvp.xulylogin.PresenterlLogicXuLyDangNhap; import com.example.admin.mvp.xulylogin.ViewXuLyDangNhap; public class MainActivity extends AppCompatActivity implements ViewXuLyDangNhap,View.OnClickListener { private EditText edName, edPass; private Button btLogin; private PresenterlLogicXuLyDangNhap logicXuLyDangNhap; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); anhXa(); } @Override public void dangNhapThnahCong(String thongBao) { Toast.makeText(MainActivity.this, "thành công " + thongBao ,Toast.LENGTH_SHORT).show(); } @Override public void dangNhapThatBai() { Toast.makeText(MainActivity.this, "thất bại",Toast.LENGTH_SHORT).show(); } private void anhXa(){ edName = (EditText) findViewById(R.id.edEmail); edPass = (EditText) findViewById(R.id.edPass); btLogin = (Button) findViewById(R.id.btLogin); logicXuLyDangNhap = new PresenterlLogicXuLyDangNhap(this); btLogin.setOnClickListener(this); } @Override public void onClick(View v) { String nameDN; String passDN; nameDN = edName.getText().toString(); passDN = edPass.getText().toString(); logicXuLyDangNhap.kiemTraDangNhap(nameDN, passDN); } }
package PrototypePattern05.example; import PrototypePattern05.example.pattern.PrototypeManager; import PrototypePattern05.example.product.OfficialDocument; import java.util.Optional; import java.util.stream.Stream; public class Client { public static void main(String[] args) { OfficialDocument officialDocument = (OfficialDocument) XMLUtil.getBean(); String key = officialDocument.getClass().getSimpleName(); PrototypeManager prototypeManager = PrototypeManager.getPrototypeManager(); prototypeManager.add(key,officialDocument); OfficialDocument obj1 = prototypeManager.getOfficialDocument(key); OfficialDocument obj2 = prototypeManager.getOfficialDocument(key); OfficialDocument obj3 = prototypeManager.getOfficialDocument(key); Stream.of(officialDocument,obj1,obj2,obj3) .forEach(t->{ t.display(); }); } }
package com.icanit.app_v2.entity; import java.util.ArrayList; import java.util.List; public class MerchantOrderItems { public AppMerchant merchant=new AppMerchant(); public List<AppOrderItems> items=new ArrayList<AppOrderItems>(); }
package com.gaoshin.onsalelocal.osl.logging; import java.io.IOException; import java.net.InetAddress; import java.util.Enumeration; import java.util.UUID; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.apache.log4j.MDC; public class OslMdcFilter implements Filter { private static final Logger logger = Logger.getLogger(OslMdcFilter.class); private static final String RegisterUri = "/user/register-"; private static final int RegisterUriLen = RegisterUri.length(); private static String hostname; static { try { hostname = InetAddress.getLocalHost().getHostName(); } catch (Exception e) { e.printStackTrace(); } } @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void destroy() { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { StatusExposingServletResponse resp = new StatusExposingServletResponse((HttpServletResponse)response); try { initMdc((HttpServletRequest)request, resp); chain.doFilter(request, resp); resp.flushBuffer(); } finally { int status = resp.getStatus(); MDC.put(MdcKeys.Status.name(), status); Object bytes = request.getAttribute("resp_bytes"); if(bytes != null) MDC.put(MdcKeys.Bytes.name(), bytes); logger.info("done"); } } private void initMdc(HttpServletRequest request, HttpServletResponse response) { resetMdc(); MDC.put(MdcKeys.Method.name(), request.getMethod()); parsedRequest(request, response); } public static void resetMdc() { for(MdcKeys mk : MdcKeys.class.getEnumConstants()) { MDC.remove(mk.name()); } for(String key : MdcKeys.getAllKeys()) { MDC.remove(key); } MDC.put(MdcKeys.Hostname.name(), hostname); MDC.put(MdcKeys.StartTime.name(), String.valueOf(System.currentTimeMillis())); MDC.put(MdcKeys.TimeDiff.name(), new TimeDiff()); MDC.put(MdcKeys.TimeSince.name(), new TimeSince()); MDC.put(MdcKeys.ClientRequestTime.name(), System.currentTimeMillis()); MDC.put(MdcKeys.Bytes.name(), 0); } public void parsedRequest(HttpServletRequest request, HttpServletResponse response) { Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie c : cookies) { MdcKeys.addKey(c.getName()); MDC.put(c.getName(), c.getValue()); } } Enumeration headerNames = request.getHeaderNames(); while(headerNames.hasMoreElements()) { String name = (String) headerNames.nextElement(); MdcKeys.addKey(name); MDC.put(name, request.getHeader(name)); } String reqid = request.getHeader(MdcKeys.Reqid.name()); if(reqid != null) { RequestId ar = new RequestId(reqid); MDC.put(MdcKeys.AppVer.name(), ar.getAppVersion()); MDC.put(MdcKeys.DeviceId.name(), ar.getDeviceId()); MDC.put(MdcKeys.ClientRequestTime.name(), ar.getTimestamp()); MDC.put(MdcKeys.UserId.name(), ar.getUserId()); MDC.put(MdcKeys.DeviceType.name(), ar.getDeviceType()); MDC.put(MdcKeys.Latitude.name(), ar.getLatitude()); MDC.put(MdcKeys.Longitude.name(), ar.getLongitude()); } String uri = request.getRequestURI(); MDC.put(MdcKeys.Uri.name(), uri); String query = request.getQueryString(); if(query != null) MDC.put(MdcKeys.Query.name(), request.getQueryString()); if(MDC.get(MdcKeys.Reqid.name()) == null) { reqid = UUID.randomUUID().toString(); MDC.put(MdcKeys.Reqid.name(), reqid); } response.setHeader(MdcKeys.Reqid.name(), reqid); } }
package rafaxplayer.cheftools.stocks.fragment; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.Fragment; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.TextView; import java.util.ArrayList; import butterknife.BindView; import butterknife.ButterKnife; import rafaxplayer.cheftools.Globalclasses.GlobalUttilities; import rafaxplayer.cheftools.Globalclasses.models.Stock_Product; import rafaxplayer.cheftools.Globalclasses.models.Stocks; import rafaxplayer.cheftools.R; import rafaxplayer.cheftools.database.DBHelper; import rafaxplayer.cheftools.database.SqliteWrapper; import rafaxplayer.cheftools.stocks.StocksDetalle_Activity; import rafaxplayer.cheftools.stocks.Stocks_Activity; /** * A placeholder fragment containing a simple view. */ public class StocksDetalle_Fragment extends Fragment { @BindView(R.id.stocknamedetalle) TextView stockName; @BindView(R.id.textComment) TextView stockComment; @BindView(R.id.list_items) RecyclerView listStock; private SqliteWrapper sql; private int ID; public static StocksDetalle_Fragment newInstance(int id) { StocksDetalle_Fragment fr = new StocksDetalle_Fragment(); Bundle args = new Bundle(); args.putInt("id", id); fr.setArguments(args); return fr; } @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_stocks_detalle, container, false); ButterKnife.bind(this, v); listStock.setHasFixedSize(true); listStock.setLayoutManager(new LinearLayoutManager(getActivity())); listStock.setItemAnimator(new DefaultItemAnimator()); return v; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); sql = new SqliteWrapper(getActivity()); sql.open(); } @Override public void onResume() { super.onResume(); if (getArguments() != null) { displayWithId(getArguments().getInt("id")); this.ID = getArguments().getInt("id"); } setHasOptionsMenu(!(this.ID == 0)); } @Override public void onCreateOptionsMenu(android.view.Menu menu, MenuInflater inflater) { // Inflate the menu; this adds items to the action bar if it is present. inflater.inflate(R.menu.menu_detalle, menu); MenuItem share = menu.findItem(R.id.share); MenuItem edit = menu.findItem(R.id.edit); share.setTitle(R.string.menu_share_stock); edit.setTitle(R.string.menu_edit_stock); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.edit: if (ID != 0) { boolean islayout = (getActivity().getSupportFragmentManager().findFragmentById(R.id.detallestocks) != null); if (getResources().getBoolean(R.bool.dual_pane) && islayout) { ((Stocks_Activity) getActivity()).showMenuEdit(ID); } else { ((StocksDetalle_Activity) getActivity()).showMenuEdit(ID); } } break; case R.id.share: if (!sql.IsOpen()) { sql.open(); } if (ID != 0) { Stocks stock = (Stocks) sql.SelectWithId("Stocks", DBHelper.TABLE_INVENTARIOS, ID); String sharedStr = GlobalUttilities.shareDataText(getActivity(), stock); Intent shareIntent = new Intent(Intent.ACTION_SEND); shareIntent.setType("*/*"); shareIntent.putExtra(Intent.EXTRA_TEXT, sharedStr); startActivity(Intent.createChooser(shareIntent, getString(R.string.share_recipe_use))); } //Toast.makeText(getActivity(), "Share", Toast.LENGTH_LONG).show(); break; default: break; } return super.onOptionsItemSelected(item); } public void displayWithId(int id) { if (!sql.IsOpen()) { sql.open(); } Stocks ord = (Stocks) sql.SelectWithId("Stocks", DBHelper.TABLE_INVENTARIOS, id); if (ord != null) { stockName.setText(ord.getName()); stockComment.setText(ord.getComentario()); ArrayList<Stock_Product> listProducts = (ArrayList<Stock_Product>) (Object) sql.getProductListWithListId("Stock_product", id); listStock.setAdapter(new RecyclerAdapter(listProducts)); } this.ID = id; setHasOptionsMenu(true); } @Override public void onPause() { super.onPause(); if (sql.IsOpen()) { sql.close(); } } public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> { private final ArrayList<Stock_Product> mDataset; RecyclerAdapter(ArrayList<Stock_Product> myDataset) { mDataset = myDataset; } @NonNull @Override public RecyclerAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_list_simple, parent, false); return new ViewHolder(v); } @Override public void onBindViewHolder(@NonNull RecyclerAdapter.ViewHolder viewHolder, int i) { if (!sql.IsOpen()) { sql.open(); } String productName = sql.getSimpleData(mDataset.get(i).getProductoId(), DBHelper.NAME, DBHelper.TABLE_PRODUCTOS); String formatName = sql.getSimpleData(mDataset.get(i).getProductoId(), DBHelper.PRODUCTO_FORMATO_NAME, DBHelper.TABLE_PRODUCTOS); viewHolder.delbut.setVisibility(View.GONE); viewHolder.editbut.setVisibility(View.GONE); viewHolder.txtProd.setText(productName); viewHolder.txtCantidad.setText(String.valueOf(mDataset.get(i).getCantidad())); viewHolder.txtFormat.setText(formatName); } @Override public int getItemCount() { return mDataset.size(); } public class ViewHolder extends RecyclerView.ViewHolder { final TextView txtProd; final TextView txtCantidad; final TextView txtFormat; final ImageButton delbut; final ImageButton editbut; ViewHolder(View v) { super(v); delbut = v.findViewById(R.id.ButtonDeleteProduct); editbut = v.findViewById(R.id.ButtonEditProduct); txtProd = v.findViewById(R.id.text1); txtCantidad = v.findViewById(R.id.text2); txtFormat = v.findViewById(R.id.text3); } } } }
package model; import java.io.IOException; public interface XCellFactory { public XCell makeXCellComment(String content); public XCell makeXCellExpr(String cellRef, String content) throws IOException; }
/* * Copyright (C) 2012 www.amsoft.cn * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.bnrc.task; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.concurrent.Executor; import android.os.Handler; import android.os.Message; import com.bnrc.util.AbLogUtil; // TODO: Auto-generated Javadoc /** * 漏 2012 amsoft.cn * 鍚嶇О锛欰bTaskQueue.java * 鎻忚堪锛氱嚎绋嬮槦鍒�. * * @author 杩樺涓�姊︿腑 * @version v1.0 * @date锛�2011-11-10 涓嬪崍11:52:13 */ public class AbTaskQueue extends Thread { /** 绛夊緟鎵ц鐨勪换鍔�. 鐢� LinkedList澧炲垹鏁堢巼楂�*/ private static LinkedList<AbTaskItem> mAbTaskItemList = null; /** 鍗曚緥瀵硅薄. */ private static AbTaskQueue abTaskQueue = null; /** 鍋滄鐨勬爣璁�. */ private boolean mQuit = false; /** 瀛樻斁杩斿洖鐨勪换鍔$粨鏋�. */ private static HashMap<String,Object> result; /** 鎵ц瀹屾垚鍚庣殑娑堟伅鍙ユ焺. */ private static Handler handler = new Handler() { @Override public void handleMessage(Message msg) { AbTaskItem item = (AbTaskItem)msg.obj; if(item.getListener() instanceof AbTaskListListener){ ((AbTaskListListener)item.getListener()).update((List<?>)result.get(item.toString())); }else if(item.getListener() instanceof AbTaskObjectListener){ ((AbTaskObjectListener)item.getListener()).update(result.get(item.toString())); }else{ item.getListener().update(); } result.remove(item.toString()); } }; /** * 鍗曚緥鏋勯��. * * @return single instance of AbTaskQueue */ public static AbTaskQueue getInstance() { if (abTaskQueue == null) { abTaskQueue = new AbTaskQueue(); } return abTaskQueue; } /** * 鏋勯�犳墽琛岀嚎绋嬮槦鍒�. */ public AbTaskQueue() { mQuit = false; mAbTaskItemList = new LinkedList<AbTaskItem>(); result = new HashMap<String,Object>(); //浠庣嚎绋嬫睜涓幏鍙� Executor mExecutorService = AbThreadFactory.getExecutorService(); mExecutorService.execute(this); } /** * 寮�濮嬩竴涓墽琛屼换鍔�. * * @param item 鎵ц鍗曚綅 */ public void execute(AbTaskItem item) { addTaskItem(item); } /** * 寮�濮嬩竴涓墽琛屼换鍔″苟娓呴櫎鍘熸潵闃熷垪. * @param item 鎵ц鍗曚綅 * @param cancel 娓呯┖涔嬪墠鐨勪换鍔� */ public void execute(AbTaskItem item,boolean cancel) { if(cancel){ cancel(true); } addTaskItem(item); } /** * 鎻忚堪锛氭坊鍔犲埌鎵ц绾跨▼闃熷垪. * * @param item 鎵ц鍗曚綅 */ private synchronized void addTaskItem(AbTaskItem item) { if (abTaskQueue == null) { abTaskQueue = new AbTaskQueue(); } mAbTaskItemList.add(item); //娣诲姞浜嗘墽琛岄」灏辨縺娲绘湰绾跨▼ this.notify(); } /** * 鎻忚堪锛氱嚎绋嬭繍琛�. * * @see java.lang.Thread#run() */ @Override public void run() { while(!mQuit) { try { while(mAbTaskItemList.size() > 0){ AbTaskItem item = mAbTaskItemList.remove(0); //瀹氫箟浜嗗洖璋� if (item.getListener() != null) { if(item.getListener() instanceof AbTaskListListener){ result.put(item.toString(), ((AbTaskListListener)item.getListener()).getList()); }else if(item.getListener() instanceof AbTaskObjectListener){ result.put(item.toString(), ((AbTaskObjectListener)item.getListener()).getObject()); }else{ item.getListener().get(); result.put(item.toString(), null); } //浜ょ敱UI绾跨▼澶勭悊 Message msg = handler.obtainMessage(); msg.obj = item; handler.sendMessage(msg); } //鍋滄鍚庢竻绌� if(mQuit){ mAbTaskItemList.clear(); return; } } try { //娌℃湁鎵ц椤规椂绛夊緟 synchronized(this) { this.wait(); } } catch (InterruptedException e) { AbLogUtil.e("AbTaskQueue","鏀跺埌绾跨▼涓柇璇锋眰"); e.printStackTrace(); //琚腑鏂殑鏄��鍑哄氨缁撴潫锛屽惁鍒欑户缁� if (mQuit) { mAbTaskItemList.clear(); return; } continue; } } catch (Exception e) { e.printStackTrace(); } } } /** * 鎻忚堪锛氱粓姝㈤槦鍒楅噴鏀剧嚎绋�. * * @param mayInterruptIfRunning the may interrupt if running */ public void cancel(boolean mayInterruptIfRunning){ mQuit = true; if(mayInterruptIfRunning){ interrupted(); } abTaskQueue = null; } }